3 * @copyright Copyright (C) 2020, Friendica
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\CurlResult;
36 use Friendica\Protocol\Relay;
37 use Friendica\Util\DateTimeFormat;
38 use Friendica\Util\Network;
39 use Friendica\Util\Strings;
40 use Friendica\Util\XML;
43 * This class handles GServer related functions
50 const DT_MASTODON = 2;
52 // Methods to detect server types
54 // Non endpoint specific methods
55 const DETECT_MANUAL = 0;
56 const DETECT_HEADER = 1;
57 const DETECT_BODY = 2;
59 // Implementation specific endpoints
60 const DETECT_FRIENDIKA = 10;
61 const DETECT_FRIENDICA = 11;
62 const DETECT_STATUSNET = 12;
63 const DETECT_GNUSOCIAL = 13;
64 const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix
65 const DETECT_SITEINFO_JSON = 15; // Newer Hubzilla
66 const DETECT_MASTODON_API = 16;
67 const DETECT_STATUS_PHP = 17; // Nextcloud
68 const DETECT_V1_CONFIG = 18;
70 // Standardized endpoints
71 const DETECT_STATISTICS_JSON = 100;
72 const DETECT_NODEINFO_1 = 101;
73 const DETECT_NODEINFO_2 = 102;
76 * Check for the existance of a server and adds it in the background if not existant
79 * @param boolean $only_nodeinfo
82 public static function add(string $url, bool $only_nodeinfo = false)
84 if (self::getID($url, false)) {
88 Worker::add(PRIORITY_LOW, 'UpdateGServer', $url, $only_nodeinfo);
92 * Get the ID for the given server URL
95 * @param boolean $no_check Don't check if the server hadn't been found
96 * @return int gserver id
98 public static function getID(string $url, bool $no_check = false)
104 $url = self::cleanURL($url);
106 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
107 if (DBA::isResult($gserver)) {
108 Logger::info('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
109 return $gserver['id'];
112 if ($no_check || !self::check($url)) {
116 return self::getID($url, true);
120 * Checks if the given server is reachable
122 * @param string $profile URL of the given profile
123 * @param string $server URL of the given server (If empty, taken from profile)
124 * @param string $network Network value that is used, when detection failed
125 * @param boolean $force Force an update.
127 * @return boolean 'true' if server seems vital
129 public static function reachable(string $profile, string $server = '', string $network = '', bool $force = false)
132 $contact = Contact::getByURL($profile, null, ['baseurl']);
133 if (!empty($contact['baseurl'])) {
134 $server = $contact['baseurl'];
142 return self::check($server, $network, $force);
145 public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '')
147 // On successful contact process check again next week
149 return DateTimeFormat::utc('now +7 day');
152 $now = strtotime(DateTimeFormat::utcNow());
154 if ($created > $last_contact) {
155 $contact_time = strtotime($created);
157 $contact_time = strtotime($last_contact);
160 // If the last contact was less than 6 hours before then try again in 6 hours
161 if (($now - $contact_time) < (60 * 60 * 6)) {
162 return DateTimeFormat::utc('now +6 hour');
165 // If the last contact was less than 12 hours before then try again in 12 hours
166 if (($now - $contact_time) < (60 * 60 * 12)) {
167 return DateTimeFormat::utc('now +12 hour');
170 // If the last contact was less than 24 hours before then try tomorrow again
171 if (($now - $contact_time) < (60 * 60 * 24)) {
172 return DateTimeFormat::utc('now +1 day');
175 // If the last contact was less than a week before then try again in a week
176 if (($now - $contact_time) < (60 * 60 * 24 * 7)) {
177 return DateTimeFormat::utc('now +1 week');
180 // If the last contact was less than two weeks before then try again in two week
181 if (($now - $contact_time) < (60 * 60 * 24 * 14)) {
182 return DateTimeFormat::utc('now +2 week');
185 // If the last contact was less than a month before then try again in a month
186 if (($now - $contact_time) < (60 * 60 * 24 * 30)) {
187 return DateTimeFormat::utc('now +1 month');
190 // The system hadn't been successul contacted for more than a month, so try again in three months
191 return DateTimeFormat::utc('now +3 month');
195 * Checks the state of the given server.
197 * @param string $server_url URL of the given server
198 * @param string $network Network value that is used, when detection failed
199 * @param boolean $force Force an update.
200 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
202 * @return boolean 'true' if server seems vital
204 public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false)
206 $server_url = self::cleanURL($server_url);
207 if ($server_url == '') {
211 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
212 if (DBA::isResult($gserver)) {
213 if ($gserver['created'] <= DBA::NULL_DATETIME) {
214 $fields = ['created' => DateTimeFormat::utcNow()];
215 $condition = ['nurl' => Strings::normaliseLink($server_url)];
216 DBA::update('gserver', $fields, $condition);
219 if (!$force && (strtotime($gserver['next_contact']) > time())) {
220 Logger::info('No update needed', ['server' => $server_url]);
221 return (!$gserver['failed']);
223 Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]);
225 Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
228 return self::detect($server_url, $network, $only_nodeinfo);
232 * Set failed server status
236 public static function setFailure(string $url)
238 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($url)]);
239 if (DBA::isResult($gserver)) {
240 $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
241 DBA::update('gserver', ['failed' => true, 'last_failure' => DateTimeFormat::utcNow(),
242 'next_contact' => $next_update, 'detection-method' => null],
243 ['nurl' => Strings::normaliseLink($url)]);
244 Logger::info('Set failed status for existing server', ['url' => $url]);
247 DBA::insert('gserver', ['url' => $url, 'nurl' => Strings::normaliseLink($url),
248 'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
249 'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
250 Logger::info('Set failed status for new server', ['url' => $url]);
254 * Remove unwanted content from the given URL
257 * @return string cleaned URL
259 public static function cleanURL(string $url)
261 $url = trim($url, '/');
262 $url = str_replace('/index.php', '', $url);
264 $urlparts = parse_url($url);
265 unset($urlparts['user']);
266 unset($urlparts['pass']);
267 unset($urlparts['query']);
268 unset($urlparts['fragment']);
269 return Network::unparseURL($urlparts);
273 * Return the base URL
276 * @return string base URL
278 private static function getBaseURL(string $url)
280 $urlparts = parse_url(self::cleanURL($url));
281 unset($urlparts['path']);
282 return Network::unparseURL($urlparts);
286 * Detect server data (type, protocol, version number, ...)
287 * The detected data is then updated or inserted in the gserver table.
289 * @param string $url URL of the given server
290 * @param string $network Network value that is used, when detection failed
291 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
293 * @return boolean 'true' if server could be detected
295 public static function detect(string $url, string $network = '', bool $only_nodeinfo = false)
297 Logger::info('Detect server type', ['server' => $url]);
298 $serverdata = ['detection-method' => self::DETECT_MANUAL];
300 $original_url = $url;
302 // Remove URL content that is not supposed to exist for a server url
303 $url = self::cleanURL($url);
306 $baseurl = self::getBaseURL($url);
308 // If the URL missmatches, then we mark the old entry as failure
309 if ($url != $original_url) {
310 /// @todo What to do with "next_contact" here?
311 DBA::update('gserver', ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()],
312 ['nurl' => Strings::normaliseLink($original_url)]);
315 // When a nodeinfo is present, we don't need to dig further
316 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
317 $curlResult = DI::httpRequest()->get($url . '/.well-known/nodeinfo', ['timeout' => $xrd_timeout]);
318 if ($curlResult->isTimeout()) {
319 self::setFailure($url);
323 // On a redirect follow the new host but mark the old one as failure
324 if ($curlResult->isSuccess() && (parse_url($url, PHP_URL_HOST) != parse_url($curlResult->getRedirectUrl(), PHP_URL_HOST))) {
325 $curlResult = DI::httpRequest()->get($url, ['timeout' => $xrd_timeout]);
326 if (parse_url($url, PHP_URL_HOST) != parse_url($curlResult->getRedirectUrl(), PHP_URL_HOST)) {
327 Logger::info('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $curlResult->getRedirectUrl()]);
328 self::setFailure($url);
329 self::detect($curlResult->getRedirectUrl(), $network, $only_nodeinfo);
334 $nodeinfo = self::fetchNodeinfo($url, $curlResult);
335 if ($only_nodeinfo && empty($nodeinfo)) {
336 Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
337 self::setFailure($url);
341 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
342 if (empty($nodeinfo)) {
343 $nodeinfo = self::fetchStatistics($url);
346 // If that didn't work out well, we use some protocol specific endpoints
347 // For Friendica and Zot based networks we have to dive deeper to reveal more details
348 if (empty($nodeinfo['network']) || in_array($nodeinfo['network'], [Protocol::DFRN, Protocol::ZOT])) {
349 if (!empty($nodeinfo['detection-method'])) {
350 $serverdata['detection-method'] = $nodeinfo['detection-method'];
353 // Fetch the landing page, possibly it reveals some data
354 if (empty($nodeinfo['network'])) {
355 if ($baseurl == $url) {
356 $basedata = $serverdata;
358 $basedata = ['detection-method' => self::DETECT_MANUAL];
361 $curlResult = DI::httpRequest()->get($baseurl, ['timeout' => $xrd_timeout]);
362 if ($curlResult->isSuccess()) {
363 if ((parse_url($baseurl, PHP_URL_HOST) != parse_url($curlResult->getRedirectUrl(), PHP_URL_HOST))) {
364 Logger::info('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $curlResult->getRedirectUrl()]);
365 self::setFailure($url);
366 self::detect($curlResult->getRedirectUrl(), $network, $only_nodeinfo);
370 $basedata = self::analyseRootHeader($curlResult, $basedata);
371 $basedata = self::analyseRootBody($curlResult, $basedata, $baseurl);
374 if (!$curlResult->isSuccess() || empty($curlResult->getBody()) || self::invalidBody($curlResult->getBody())) {
375 self::setFailure($url);
379 if ($baseurl == $url) {
380 $serverdata = $basedata;
382 // When the base path doesn't seem to contain a social network we try the complete path.
383 // Most detectable system have to be installed in the root directory.
384 // We checked the base to avoid false positives.
385 $curlResult = DI::httpRequest()->get($url, ['timeout' => $xrd_timeout]);
386 if ($curlResult->isSuccess()) {
387 $urldata = self::analyseRootHeader($curlResult, $serverdata);
388 $urldata = self::analyseRootBody($curlResult, $urldata, $url);
390 $comparebase = $basedata;
391 unset($comparebase['info']);
392 unset($comparebase['site_name']);
393 $compareurl = $urldata;
394 unset($compareurl['info']);
395 unset($compareurl['site_name']);
397 // We assume that no one will install the identical system in the root and a subfolder
398 if (!empty(array_diff($comparebase, $compareurl))) {
399 $serverdata = $urldata;
405 if (empty($serverdata['network']) || ($serverdata['network'] == Protocol::ACTIVITYPUB)) {
406 $serverdata = self::detectMastodonAlikes($url, $serverdata);
409 // All following checks are done for systems that always have got a "host-meta" endpoint.
410 // With this check we don't have to waste time and ressources for dead systems.
411 // Also this hopefully prevents us from receiving abuse messages.
412 if (empty($serverdata['network']) && !self::validHostMeta($url)) {
413 self::setFailure($url);
417 if (empty($serverdata['network']) || in_array($serverdata['network'], [Protocol::DFRN, Protocol::ACTIVITYPUB])) {
418 $serverdata = self::detectFriendica($url, $serverdata);
421 // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
422 if (empty($serverdata['network']) || ($serverdata['network'] == Protocol::ZOT)) {
423 $serverdata = self::fetchSiteinfo($url, $serverdata);
426 // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations
427 if (empty($serverdata['network'])) {
428 $serverdata = self::detectHubzilla($url, $serverdata);
431 if (empty($serverdata['network']) || in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_BODY])) {
432 $serverdata = self::detectPeertube($url, $serverdata);
435 if (empty($serverdata['network'])) {
436 $serverdata = self::detectNextcloud($url, $serverdata);
439 if (empty($serverdata['network'])) {
440 $serverdata = self::detectGNUSocial($url, $serverdata);
443 $serverdata = array_merge($nodeinfo, $serverdata);
445 $serverdata = $nodeinfo;
448 // Detect the directory type
449 $serverdata['directory-type'] = self::DT_NONE;
450 $serverdata = self::checkPoCo($url, $serverdata);
451 $serverdata = self::checkMastodonDirectory($url, $serverdata);
453 // We can't detect the network type. Possibly it is some system that we don't know yet
454 if (empty($serverdata['network'])) {
455 $serverdata['network'] = Protocol::PHANTOM;
458 // When we hadn't been able to detect the network type, we use the hint from the parameter
459 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
460 $serverdata['network'] = $network;
463 $serverdata['url'] = $url;
464 $serverdata['nurl'] = Strings::normaliseLink($url);
466 // We take the highest number that we do find
467 $registeredUsers = $serverdata['registered-users'] ?? 0;
469 // On an active server there has to be at least a single user
470 if (($serverdata['network'] != Protocol::PHANTOM) && ($registeredUsers == 0)) {
471 $registeredUsers = 1;
474 if ($serverdata['network'] == Protocol::PHANTOM) {
475 $serverdata['registered-users'] = max($registeredUsers, 1);
476 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
479 $serverdata['next_contact'] = self::getNextUpdateDate(true);
481 $serverdata['last_contact'] = DateTimeFormat::utcNow();
482 $serverdata['failed'] = false;
484 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
485 if (!DBA::isResult($gserver)) {
486 $serverdata['created'] = DateTimeFormat::utcNow();
487 $ret = DBA::insert('gserver', $serverdata);
488 $id = DBA::lastInsertId();
490 // Don't override the network with 'unknown' when there had been a valid entry before
491 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($gserver['network'])) {
492 unset($serverdata['network']);
495 $ret = DBA::update('gserver', $serverdata, ['nurl' => $serverdata['nurl']]);
496 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
497 if (DBA::isResult($gserver)) {
498 $id = $gserver['id'];
502 if (!empty($serverdata['network']) && !empty($id) && ($serverdata['network'] != Protocol::PHANTOM)) {
503 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
504 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id]);
505 $max_users = max($apcontacts, $contacts, $registeredUsers, 1);
506 if ($max_users > $registeredUsers) {
507 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
508 DBA::update('gserver', ['registered-users' => $max_users], ['id' => $id]);
512 if (!empty($serverdata['network']) && in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
513 self::discoverRelay($url);
520 * Fetch relay data from a given server url
522 * @param string $server_url address of the server
523 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
525 private static function discoverRelay(string $server_url)
527 Logger::info('Discover relay data', ['server' => $server_url]);
529 $curlResult = DI::httpRequest()->get($server_url . '/.well-known/x-social-relay');
530 if (!$curlResult->isSuccess()) {
534 $data = json_decode($curlResult->getBody(), true);
535 if (!is_array($data)) {
539 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
540 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
542 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
544 $data['subscribe'] = false;
548 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
549 if (!DBA::isResult($gserver)) {
553 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
554 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
555 DBA::update('gserver', $fields, ['id' => $gserver['id']]);
558 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
560 if ($data['scope'] == 'tags') {
563 foreach ($data['tags'] as $tag) {
564 $tag = mb_strtolower($tag);
565 if (strlen($tag) < 100) {
570 foreach ($tags as $tag) {
571 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
575 // Create or update the relay contact
577 if (isset($data['protocols'])) {
578 if (isset($data['protocols']['diaspora'])) {
579 $fields['network'] = Protocol::DIASPORA;
581 if (isset($data['protocols']['diaspora']['receive'])) {
582 $fields['batch'] = $data['protocols']['diaspora']['receive'];
583 } elseif (is_string($data['protocols']['diaspora'])) {
584 $fields['batch'] = $data['protocols']['diaspora'];
588 if (isset($data['protocols']['dfrn'])) {
589 $fields['network'] = Protocol::DFRN;
591 if (isset($data['protocols']['dfrn']['receive'])) {
592 $fields['batch'] = $data['protocols']['dfrn']['receive'];
593 } elseif (is_string($data['protocols']['dfrn'])) {
594 $fields['batch'] = $data['protocols']['dfrn'];
598 if (isset($data['protocols']['activitypub'])) {
599 $fields['network'] = Protocol::ACTIVITYPUB;
601 if (!empty($data['protocols']['activitypub']['actor'])) {
602 $fields['url'] = $data['protocols']['activitypub']['actor'];
604 if (!empty($data['protocols']['activitypub']['receive'])) {
605 $fields['batch'] = $data['protocols']['activitypub']['receive'];
610 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
612 Relay::updateContact($gserver, $fields);
616 * Fetch server data from '/statistics.json' on the given server
618 * @param string $url URL of the given server
620 * @return array server data
622 private static function fetchStatistics(string $url)
624 $curlResult = DI::httpRequest()->get($url . '/statistics.json');
625 if (!$curlResult->isSuccess()) {
629 $data = json_decode($curlResult->getBody(), true);
634 $serverdata = ['detection-method' => self::DETECT_STATISTICS_JSON];
636 if (!empty($data['version'])) {
637 $serverdata['version'] = $data['version'];
638 // Version numbers on statistics.json are presented with additional info, e.g.:
639 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
640 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
643 if (!empty($data['name'])) {
644 $serverdata['site_name'] = $data['name'];
647 if (!empty($data['network'])) {
648 $serverdata['platform'] = strtolower($data['network']);
650 if ($serverdata['platform'] == 'diaspora') {
651 $serverdata['network'] = Protocol::DIASPORA;
652 } elseif ($serverdata['platform'] == 'friendica') {
653 $serverdata['network'] = Protocol::DFRN;
654 } elseif ($serverdata['platform'] == 'hubzilla') {
655 $serverdata['network'] = Protocol::ZOT;
656 } elseif ($serverdata['platform'] == 'redmatrix') {
657 $serverdata['network'] = Protocol::ZOT;
662 if (!empty($data['registrations_open'])) {
663 $serverdata['register_policy'] = Register::OPEN;
665 $serverdata['register_policy'] = Register::CLOSED;
672 * Detect server type by using the nodeinfo data
674 * @param string $url address of the server
675 * @param CurlResult $curlResult
676 * @return array Server data
677 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
679 private static function fetchNodeinfo(string $url, CurlResult $curlResult)
681 if (!$curlResult->isSuccess()) {
685 $nodeinfo = json_decode($curlResult->getBody(), true);
687 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
694 foreach ($nodeinfo['links'] as $link) {
695 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
696 Logger::info('Invalid nodeinfo format', ['url' => $url]);
699 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
700 $nodeinfo1_url = $link['href'];
701 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
702 $nodeinfo2_url = $link['href'];
706 if ($nodeinfo1_url . $nodeinfo2_url == '') {
712 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
713 if (!empty($nodeinfo2_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
714 $server = self::parseNodeinfo2($nodeinfo2_url);
717 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
718 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
719 $server = self::parseNodeinfo1($nodeinfo1_url);
728 * @param string $nodeinfo_url address of the nodeinfo path
729 * @return array Server data
730 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
732 private static function parseNodeinfo1(string $nodeinfo_url)
734 $curlResult = DI::httpRequest()->get($nodeinfo_url);
736 if (!$curlResult->isSuccess()) {
740 $nodeinfo = json_decode($curlResult->getBody(), true);
742 if (!is_array($nodeinfo)) {
746 $server = ['detection-method' => self::DETECT_NODEINFO_1,
747 'register_policy' => Register::CLOSED];
749 if (!empty($nodeinfo['openRegistrations'])) {
750 $server['register_policy'] = Register::OPEN;
753 if (is_array($nodeinfo['software'])) {
754 if (!empty($nodeinfo['software']['name'])) {
755 $server['platform'] = strtolower($nodeinfo['software']['name']);
758 if (!empty($nodeinfo['software']['version'])) {
759 $server['version'] = $nodeinfo['software']['version'];
760 // Version numbers on Nodeinfo are presented with additional info, e.g.:
761 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
762 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
766 if (!empty($nodeinfo['metadata']['nodeName'])) {
767 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
770 if (!empty($nodeinfo['usage']['users']['total'])) {
771 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
774 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
776 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
777 $protocols[$protocol] = true;
780 if (!empty($protocols['friendica'])) {
781 $server['network'] = Protocol::DFRN;
782 } elseif (!empty($protocols['activitypub'])) {
783 $server['network'] = Protocol::ACTIVITYPUB;
784 } elseif (!empty($protocols['diaspora'])) {
785 $server['network'] = Protocol::DIASPORA;
786 } elseif (!empty($protocols['ostatus'])) {
787 $server['network'] = Protocol::OSTATUS;
788 } elseif (!empty($protocols['gnusocial'])) {
789 $server['network'] = Protocol::OSTATUS;
790 } elseif (!empty($protocols['zot'])) {
791 $server['network'] = Protocol::ZOT;
795 if (empty($server)) {
805 * @param string $nodeinfo_url address of the nodeinfo path
806 * @return array Server data
807 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
809 private static function parseNodeinfo2(string $nodeinfo_url)
811 $curlResult = DI::httpRequest()->get($nodeinfo_url);
812 if (!$curlResult->isSuccess()) {
816 $nodeinfo = json_decode($curlResult->getBody(), true);
818 if (!is_array($nodeinfo)) {
822 $server = ['detection-method' => self::DETECT_NODEINFO_2,
823 'register_policy' => Register::CLOSED];
825 if (!empty($nodeinfo['openRegistrations'])) {
826 $server['register_policy'] = Register::OPEN;
829 if (is_array($nodeinfo['software'])) {
830 if (!empty($nodeinfo['software']['name'])) {
831 $server['platform'] = strtolower($nodeinfo['software']['name']);
834 if (!empty($nodeinfo['software']['version'])) {
835 $server['version'] = $nodeinfo['software']['version'];
836 // Version numbers on Nodeinfo are presented with additional info, e.g.:
837 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
838 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
842 if (!empty($nodeinfo['metadata']['nodeName'])) {
843 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
846 if (!empty($nodeinfo['usage']['users']['total'])) {
847 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
850 if (!empty($nodeinfo['protocols'])) {
852 foreach ($nodeinfo['protocols'] as $protocol) {
853 $protocols[$protocol] = true;
856 if (!empty($protocols['dfrn'])) {
857 $server['network'] = Protocol::DFRN;
858 } elseif (!empty($protocols['activitypub'])) {
859 $server['network'] = Protocol::ACTIVITYPUB;
860 } elseif (!empty($protocols['diaspora'])) {
861 $server['network'] = Protocol::DIASPORA;
862 } elseif (!empty($protocols['ostatus'])) {
863 $server['network'] = Protocol::OSTATUS;
864 } elseif (!empty($protocols['gnusocial'])) {
865 $server['network'] = Protocol::OSTATUS;
866 } elseif (!empty($protocols['zot'])) {
867 $server['network'] = Protocol::ZOT;
871 if (empty($server)) {
879 * Fetch server information from a 'siteinfo.json' file on the given server
881 * @param string $url URL of the given server
882 * @param array $serverdata array with server data
884 * @return array server data
886 private static function fetchSiteinfo(string $url, array $serverdata)
888 $curlResult = DI::httpRequest()->get($url . '/siteinfo.json');
889 if (!$curlResult->isSuccess()) {
893 $data = json_decode($curlResult->getBody(), true);
898 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
899 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
902 if (!empty($data['url'])) {
903 $serverdata['platform'] = strtolower($data['platform']);
904 $serverdata['version'] = $data['version'];
907 if (!empty($data['plugins'])) {
908 if (in_array('pubcrawl', $data['plugins'])) {
909 $serverdata['network'] = Protocol::ACTIVITYPUB;
910 } elseif (in_array('diaspora', $data['plugins'])) {
911 $serverdata['network'] = Protocol::DIASPORA;
912 } elseif (in_array('gnusoc', $data['plugins'])) {
913 $serverdata['network'] = Protocol::OSTATUS;
915 $serverdata['network'] = Protocol::ZOT;
919 if (!empty($data['site_name'])) {
920 $serverdata['site_name'] = $data['site_name'];
923 if (!empty($data['channels_total'])) {
924 $serverdata['registered-users'] = max($data['channels_total'], 1);
927 if (!empty($data['register_policy'])) {
928 switch ($data['register_policy']) {
929 case 'REGISTER_OPEN':
930 $serverdata['register_policy'] = Register::OPEN;
933 case 'REGISTER_APPROVE':
934 $serverdata['register_policy'] = Register::APPROVE;
937 case 'REGISTER_CLOSED':
939 $serverdata['register_policy'] = Register::CLOSED;
948 * Checks if the server contains a valid host meta file
950 * @param string $url URL of the given server
952 * @return boolean 'true' if the server seems to be vital
954 private static function validHostMeta(string $url)
956 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
957 $curlResult = DI::httpRequest()->get($url . '/.well-known/host-meta', ['timeout' => $xrd_timeout]);
958 if (!$curlResult->isSuccess()) {
962 $xrd = XML::parseString($curlResult->getBody());
963 if (!is_object($xrd)) {
967 $elements = XML::elementToArray($xrd);
968 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
973 foreach ($elements['xrd']['link'] as $link) {
974 // When there is more than a single "link" element, the array looks slightly different
975 if (!empty($link['@attributes'])) {
976 $link = $link['@attributes'];
979 if (empty($link['rel']) || empty($link['template'])) {
983 if ($link['rel'] == 'lrdd') {
984 // When the webfinger host is the same like the system host, it should be ok.
985 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
993 * Detect the network of the given server via their known contacts
995 * @param string $url URL of the given server
996 * @param array $serverdata array with server data
998 * @return array server data
1000 private static function detectNetworkViaContacts(string $url, array $serverdata)
1004 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $serverdata['nurl']]]);
1005 while ($apcontact = DBA::fetch($apcontacts)) {
1006 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1008 DBA::close($apcontacts);
1010 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $serverdata['nurl']]]);
1011 while ($pcontact = DBA::fetch($pcontacts)) {
1012 $contacts[$pcontact['nurl']] = $pcontact['url'];
1014 DBA::close($pcontacts);
1016 if (empty($contacts)) {
1020 foreach ($contacts as $contact) {
1021 $probed = Contact::getByURL($contact);
1022 if (!empty($probed) && in_array($probed['network'], Protocol::FEDERATED)) {
1023 $serverdata['network'] = $probed['network'];
1028 $serverdata['registered-users'] = max($serverdata['registered-users'], count($contacts), 1);
1034 * Checks if the given server does have a '/poco' endpoint.
1035 * This is used for the 'PortableContact' functionality,
1036 * which is used by both Friendica and Hubzilla.
1038 * @param string $url URL of the given server
1039 * @param array $serverdata array with server data
1041 * @return array server data
1043 private static function checkPoCo(string $url, array $serverdata)
1045 $serverdata['poco'] = '';
1047 $curlResult = DI::httpRequest()->get($url . '/poco');
1048 if (!$curlResult->isSuccess()) {
1052 $data = json_decode($curlResult->getBody(), true);
1057 if (!empty($data['totalResults'])) {
1058 $registeredUsers = $serverdata['registered-users'] ?? 0;
1059 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1060 $serverdata['directory-type'] = self::DT_POCO;
1061 $serverdata['poco'] = $url . '/poco';
1068 * Checks if the given server does have a Mastodon style directory endpoint.
1070 * @param string $url URL of the given server
1071 * @param array $serverdata array with server data
1073 * @return array server data
1075 public static function checkMastodonDirectory(string $url, array $serverdata)
1077 $curlResult = DI::httpRequest()->get($url . '/api/v1/directory?limit=1');
1078 if (!$curlResult->isSuccess()) {
1082 $data = json_decode($curlResult->getBody(), true);
1087 if (count($data) == 1) {
1088 $serverdata['directory-type'] = self::DT_MASTODON;
1095 * Detects Peertube via their known endpoint
1097 * @param string $url URL of the given server
1098 * @param array $serverdata array with server data
1100 * @return array server data
1102 private static function detectPeertube(string $url, array $serverdata)
1104 $curlResult = DI::httpRequest()->get($url . '/api/v1/config');
1106 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1110 $data = json_decode($curlResult->getBody(), true);
1115 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1116 $serverdata['platform'] = 'peertube';
1117 $serverdata['version'] = $data['serverVersion'];
1118 $serverdata['network'] = Protocol::ACTIVITYPUB;
1120 if (!empty($data['instance']['name'])) {
1121 $serverdata['site_name'] = $data['instance']['name'];
1124 if (!empty($data['instance']['shortDescription'])) {
1125 $serverdata['info'] = $data['instance']['shortDescription'];
1128 if (!empty($data['signup'])) {
1129 if (!empty($data['signup']['allowed'])) {
1130 $serverdata['register_policy'] = Register::OPEN;
1134 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1135 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1143 * Detects the version number of a given server when it was a NextCloud installation
1145 * @param string $url URL of the given server
1146 * @param array $serverdata array with server data
1148 * @return array server data
1150 private static function detectNextcloud(string $url, array $serverdata)
1152 $curlResult = DI::httpRequest()->get($url . '/status.php');
1154 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1158 $data = json_decode($curlResult->getBody(), true);
1163 if (!empty($data['version'])) {
1164 $serverdata['platform'] = 'nextcloud';
1165 $serverdata['version'] = $data['version'];
1166 $serverdata['network'] = Protocol::ACTIVITYPUB;
1168 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1169 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1177 * Detects data from a given server url if it was a mastodon alike system
1179 * @param string $url URL of the given server
1180 * @param array $serverdata array with server data
1182 * @return array server data
1184 private static function detectMastodonAlikes(string $url, array $serverdata)
1186 $curlResult = DI::httpRequest()->get($url . '/api/v1/instance');
1188 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1192 $data = json_decode($curlResult->getBody(), true);
1197 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1198 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1201 if (!empty($data['version'])) {
1202 $serverdata['platform'] = 'mastodon';
1203 $serverdata['version'] = $data['version'] ?? '';
1204 $serverdata['network'] = Protocol::ACTIVITYPUB;
1207 if (!empty($data['title'])) {
1208 $serverdata['site_name'] = $data['title'];
1211 if (!empty($data['title']) && empty($serverdata['platform']) && empty($serverdata['network'])) {
1212 $serverdata['platform'] = 'mastodon';
1213 $serverdata['network'] = Protocol::ACTIVITYPUB;
1216 if (!empty($data['description'])) {
1217 $serverdata['info'] = trim($data['description']);
1220 if (!empty($data['stats']['user_count'])) {
1221 $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1224 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1225 $serverdata['platform'] = strtolower($matches[1]);
1226 $serverdata['version'] = $matches[2];
1229 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1230 $serverdata['platform'] = 'pleroma';
1231 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1234 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1235 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1236 $serverdata['platform'] = 'pleroma';
1243 * Detects data from typical Hubzilla endpoints
1245 * @param string $url URL of the given server
1246 * @param array $serverdata array with server data
1248 * @return array server data
1250 private static function detectHubzilla(string $url, array $serverdata)
1252 $curlResult = DI::httpRequest()->get($url . '/api/statusnet/config.json');
1253 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1257 $data = json_decode($curlResult->getBody(), true);
1258 if (empty($data) || empty($data['site'])) {
1262 if (!empty($data['site']['name'])) {
1263 $serverdata['site_name'] = $data['site']['name'];
1266 if (!empty($data['site']['platform'])) {
1267 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1268 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1269 $serverdata['network'] = Protocol::ZOT;
1272 if (!empty($data['site']['hubzilla'])) {
1273 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1274 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1275 $serverdata['network'] = Protocol::ZOT;
1278 if (!empty($data['site']['redmatrix'])) {
1279 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1280 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1281 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1282 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1285 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1286 $serverdata['network'] = Protocol::ZOT;
1290 $inviteonly = false;
1293 if (!empty($data['site']['closed'])) {
1294 $closed = self::toBoolean($data['site']['closed']);
1297 if (!empty($data['site']['private'])) {
1298 $private = self::toBoolean($data['site']['private']);
1301 if (!empty($data['site']['inviteonly'])) {
1302 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1305 if (!$closed && !$private and $inviteonly) {
1306 $serverdata['register_policy'] = Register::APPROVE;
1307 } elseif (!$closed && !$private) {
1308 $serverdata['register_policy'] = Register::OPEN;
1310 $serverdata['register_policy'] = Register::CLOSED;
1313 if (!empty($serverdata['network']) && in_array($serverdata['detection-method'],
1314 [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1315 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1322 * Converts input value to a boolean value
1324 * @param string|integer $val
1328 private static function toBoolean($val)
1330 if (($val == 'true') || ($val == 1)) {
1332 } elseif (($val == 'false') || ($val == 0)) {
1340 * Detect if the URL belongs to a GNU Social server
1342 * @param string $url URL of the given server
1343 * @param array $serverdata array with server data
1345 * @return array server data
1347 private static function detectGNUSocial(string $url, array $serverdata)
1349 // Test for GNU Social
1350 $curlResult = DI::httpRequest()->get($url . '/api/gnusocial/version.json');
1351 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1352 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1353 $serverdata['platform'] = 'gnusocial';
1354 // Remove junk that some GNU Social servers return
1355 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1356 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1357 $serverdata['version'] = trim($serverdata['version'], '"');
1358 $serverdata['network'] = Protocol::OSTATUS;
1360 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1361 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1367 // Test for Statusnet
1368 $curlResult = DI::httpRequest()->get($url . '/api/statusnet/version.json');
1369 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1370 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1372 // Remove junk that some GNU Social servers return
1373 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1374 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1375 $serverdata['version'] = trim($serverdata['version'], '"');
1377 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1378 $serverdata['platform'] = 'pleroma';
1379 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1380 $serverdata['network'] = Protocol::ACTIVITYPUB;
1382 $serverdata['platform'] = 'statusnet';
1383 $serverdata['network'] = Protocol::OSTATUS;
1386 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1387 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1395 * Detect if the URL belongs to a Friendica server
1397 * @param string $url URL of the given server
1398 * @param array $serverdata array with server data
1400 * @return array server data
1402 private static function detectFriendica(string $url, array $serverdata)
1404 $curlResult = DI::httpRequest()->get($url . '/friendica/json');
1405 if (!$curlResult->isSuccess()) {
1406 $curlResult = DI::httpRequest()->get($url . '/friendika/json');
1408 $platform = 'Friendika';
1411 $platform = 'Friendica';
1414 if (!$curlResult->isSuccess()) {
1418 $data = json_decode($curlResult->getBody(), true);
1419 if (empty($data) || empty($data['version'])) {
1423 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1424 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1427 $serverdata['network'] = Protocol::DFRN;
1428 $serverdata['version'] = $data['version'];
1430 if (!empty($data['no_scrape_url'])) {
1431 $serverdata['noscrape'] = $data['no_scrape_url'];
1434 if (!empty($data['site_name'])) {
1435 $serverdata['site_name'] = $data['site_name'];
1438 if (!empty($data['info'])) {
1439 $serverdata['info'] = trim($data['info']);
1442 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1443 switch ($register_policy) {
1444 case 'REGISTER_OPEN':
1445 $serverdata['register_policy'] = Register::OPEN;
1448 case 'REGISTER_APPROVE':
1449 $serverdata['register_policy'] = Register::APPROVE;
1452 case 'REGISTER_CLOSED':
1453 case 'REGISTER_INVITATION':
1454 $serverdata['register_policy'] = Register::CLOSED;
1457 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
1458 $serverdata['register_policy'] = Register::CLOSED;
1462 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
1468 * Analyses the landing page of a given server for hints about type and system of that server
1470 * @param object $curlResult result of curl execution
1471 * @param array $serverdata array with server data
1472 * @param string $url Server URL
1474 * @return array server data
1476 private static function analyseRootBody($curlResult, array $serverdata, string $url)
1478 $doc = new DOMDocument();
1479 @$doc->loadHTML($curlResult->getBody());
1480 $xpath = new DOMXPath($doc);
1482 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
1483 if (!empty($title)) {
1484 $serverdata['site_name'] = $title;
1487 $list = $xpath->query('//meta[@name]');
1489 foreach ($list as $node) {
1491 if ($node->attributes->length) {
1492 foreach ($node->attributes as $attribute) {
1493 $value = trim($attribute->value);
1494 if (empty($value)) {
1498 $attr[$attribute->name] = $value;
1501 if (empty($attr['name']) || empty($attr['content'])) {
1506 if ($attr['name'] == 'description') {
1507 $serverdata['info'] = $attr['content'];
1510 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
1511 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad'])) {
1512 $serverdata['platform'] = strtolower($attr['content']);
1513 if (in_array($attr['content'], ['Misskey', 'Write.as'])) {
1514 $serverdata['network'] = Protocol::ACTIVITYPUB;
1517 if (($attr['name'] == 'generator') && (empty($serverdata['platform']) || (substr(strtolower($attr['content']), 0, 9) == 'wordpress'))) {
1518 $serverdata['platform'] = strtolower($attr['content']);
1519 $version_part = explode(' ', $attr['content']);
1521 if (count($version_part) == 2) {
1522 if (in_array($version_part[0], ['WordPress'])) {
1523 $serverdata['platform'] = 'wordpress';
1524 $serverdata['version'] = $version_part[1];
1526 // We still do need a reliable test if some AP plugin is activated
1527 if (DBA::exists('apcontact', ['baseurl' => $url])) {
1528 $serverdata['network'] = Protocol::ACTIVITYPUB;
1530 $serverdata['network'] = Protocol::FEED;
1533 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1534 $serverdata['detection-method'] = self::DETECT_BODY;
1537 if (in_array($version_part[0], ['Friendika', 'Friendica'])) {
1538 $serverdata['platform'] = strtolower($version_part[0]);
1539 $serverdata['version'] = $version_part[1];
1540 $serverdata['network'] = Protocol::DFRN;
1546 $list = $xpath->query('//meta[@property]');
1548 foreach ($list as $node) {
1550 if ($node->attributes->length) {
1551 foreach ($node->attributes as $attribute) {
1552 $value = trim($attribute->value);
1553 if (empty($value)) {
1557 $attr[$attribute->name] = $value;
1560 if (empty($attr['property']) || empty($attr['content'])) {
1565 if ($attr['property'] == 'og:site_name') {
1566 $serverdata['site_name'] = $attr['content'];
1569 if ($attr['property'] == 'og:description') {
1570 $serverdata['info'] = $attr['content'];
1573 if ($attr['property'] == 'og:platform') {
1574 $serverdata['platform'] = strtolower($attr['content']);
1576 if (in_array($attr['content'], ['PeerTube'])) {
1577 $serverdata['network'] = Protocol::ACTIVITYPUB;
1581 if ($attr['property'] == 'generator') {
1582 $serverdata['platform'] = strtolower($attr['content']);
1584 if (in_array($attr['content'], ['hubzilla'])) {
1585 // We later check which compatible protocol modules are loaded.
1586 $serverdata['network'] = Protocol::ZOT;
1591 if (!empty($serverdata['network']) && ($serverdata['detection-method'] == self::DETECT_MANUAL)) {
1592 $serverdata['detection-method'] = self::DETECT_BODY;
1599 * Analyses the header data of a given server for hints about type and system of that server
1601 * @param object $curlResult result of curl execution
1602 * @param array $serverdata array with server data
1604 * @return array server data
1606 private static function analyseRootHeader($curlResult, array $serverdata)
1608 if ($curlResult->getHeader('server') == 'Mastodon') {
1609 $serverdata['platform'] = 'mastodon';
1610 $serverdata['network'] = Protocol::ACTIVITYPUB;
1611 } elseif ($curlResult->inHeader('x-diaspora-version')) {
1612 $serverdata['platform'] = 'diaspora';
1613 $serverdata['network'] = Protocol::DIASPORA;
1614 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version');
1615 } elseif ($curlResult->inHeader('x-friendica-version')) {
1616 $serverdata['platform'] = 'friendica';
1617 $serverdata['network'] = Protocol::DFRN;
1618 $serverdata['version'] = $curlResult->getHeader('x-friendica-version');
1623 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1624 $serverdata['detection-method'] = self::DETECT_HEADER;
1631 * Test if the body contains valid content
1633 * @param string $body
1636 private static function invalidBody(string $body)
1638 // Currently we only test for a HTML element.
1639 // Possibly we enhance this in the future.
1640 return !strpos($body, '>');
1644 * Update GServer entries
1646 public static function discover()
1648 // Update the server list
1649 self::discoverFederation();
1653 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
1655 if ($requery_days == 0) {
1659 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
1661 $gservers = DBA::p("SELECT `id`, `url`, `nurl`, `network`, `poco`, `directory-type`
1664 AND `directory-type` != ?
1665 AND `last_poco_query` < ?
1666 ORDER BY RAND()", self::DT_NONE, $last_update
1669 while ($gserver = DBA::fetch($gservers)) {
1670 Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1671 Worker::add(PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
1673 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1674 Worker::add(PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
1676 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1677 DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);
1679 if (--$no_of_queries == 0) {
1684 DBA::close($gservers);
1688 * Discover federated servers
1690 private static function discoverFederation()
1692 $last = DI::config()->get('poco', 'last_federation_discovery');
1695 $next = $last + (24 * 60 * 60);
1697 if ($next > time()) {
1702 // Discover federated servers
1703 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
1704 foreach ($protocols as $protocol) {
1705 $query = '{nodes(protocol:"' . $protocol . '"){host}}';
1706 $curlResult = DI::httpRequest()->fetch('https://the-federation.info/graphql?query=' . urlencode($query));
1707 if (!empty($curlResult)) {
1708 $data = json_decode($curlResult, true);
1709 if (!empty($data['data']['nodes'])) {
1710 foreach ($data['data']['nodes'] as $server) {
1711 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
1712 self::add('https://' . $server['host'], true);
1718 // Disvover Mastodon servers
1719 $accesstoken = DI::config()->get('system', 'instances_social_key');
1721 if (!empty($accesstoken)) {
1722 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1723 $header = ['Authorization: Bearer '.$accesstoken];
1724 $curlResult = DI::httpRequest()->get($api, ['header' => $header]);
1726 if ($curlResult->isSuccess()) {
1727 $servers = json_decode($curlResult->getBody(), true);
1729 foreach ($servers['instances'] as $server) {
1730 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
1736 DI::config()->set('poco', 'last_federation_discovery', time());
1740 * Set the protocol for the given server
1742 * @param int $gsid Server id
1743 * @param int $protocol Protocol id
1747 public static function setProtocol(int $gsid, int $protocol)
1753 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
1754 if (!DBA::isResult($gserver)) {
1758 $old = $gserver['protocol'];
1760 if (!is_null($old)) {
1762 The priority for the protocols is:
1764 2. DFRN via Diaspora
1770 // We don't need to change it when nothing is to be changed
1771 if ($old == $protocol) {
1775 // We don't want to mark a server as OStatus when it had been marked with any other protocol before
1776 if ($protocol == Post\DeliveryData::OSTATUS) {
1780 // If the server is marked as ActivityPub then we won't change it to anything different
1781 if ($old == Post\DeliveryData::ACTIVITYPUB) {
1785 // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
1786 if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
1790 // Don't change it to Diaspora when it is a legacy DFRN server
1791 if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
1796 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url'], 'callstack' => System::callstack(20)]);
1797 DBA::update('gserver', ['protocol' => $protocol], ['id' => $gsid]);
1801 * Fetch the protocol of the given server
1803 * @param int $gsid Server id
1807 public static function getProtocol(int $gsid)
1813 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
1814 if (DBA::isResult($gserver)) {
1815 return $gserver['protocol'];