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;
26 use Friendica\Core\Logger;
27 use Friendica\Core\Protocol;
28 use Friendica\Core\System;
29 use Friendica\Core\Worker;
30 use Friendica\Database\Database;
31 use Friendica\Database\DBA;
33 use Friendica\Module\Register;
34 use Friendica\Network\CurlResult;
35 use Friendica\Protocol\Relay;
36 use Friendica\Util\DateTimeFormat;
37 use Friendica\Util\Network;
38 use Friendica\Util\Strings;
39 use Friendica\Util\XML;
42 * This class handles GServer related functions
49 const DT_MASTODON = 2;
51 // Methods to detect server types
53 // Non endpoint specific methods
54 const DETECT_MANUAL = 0;
55 const DETECT_HEADER = 1;
56 const DETECT_BODY = 2;
58 // Implementation specific endpoints
59 const DETECT_FRIENDIKA = 10;
60 const DETECT_FRIENDICA = 11;
61 const DETECT_STATUSNET = 12;
62 const DETECT_GNUSOCIAL = 13;
63 const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix
64 const DETECT_SITEINFO_JSON = 15; // Newer Hubzilla
65 const DETECT_MASTODON_API = 16;
66 const DETECT_STATUS_PHP = 17; // Nextcloud
67 const DETECT_V1_CONFIG = 18;
69 // Standardized endpoints
70 const DETECT_STATISTICS_JSON = 100;
71 const DETECT_NODEINFO_1 = 101;
72 const DETECT_NODEINFO_2 = 102;
75 * Check for the existance of a server and adds it in the background if not existant
78 * @param boolean $only_nodeinfo
81 public static function add(string $url, bool $only_nodeinfo = false)
83 if (self::getID($url, false)) {
87 Worker::add(PRIORITY_LOW, 'UpdateGServer', $url, $only_nodeinfo);
91 * Get the ID for the given server URL
94 * @param boolean $no_check Don't check if the server hadn't been found
95 * @return int gserver id
97 public static function getID(string $url, bool $no_check = false)
103 $url = self::cleanURL($url);
105 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
106 if (DBA::isResult($gserver)) {
107 Logger::info('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
108 return $gserver['id'];
111 if ($no_check || !self::check($url)) {
115 return self::getID($url, true);
119 * Checks if the given server is reachable
121 * @param string $profile URL of the given profile
122 * @param string $server URL of the given server (If empty, taken from profile)
123 * @param string $network Network value that is used, when detection failed
124 * @param boolean $force Force an update.
126 * @return boolean 'true' if server seems vital
128 public static function reachable(string $profile, string $server = '', string $network = '', bool $force = false)
131 $contact = Contact::getByURL($profile, null, ['baseurl']);
132 if (!empty($contact['baseurl'])) {
133 $server = $contact['baseurl'];
141 return self::check($server, $network, $force);
144 public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '')
146 // On successful contact process check again next week
148 return DateTimeFormat::utc('now +7 day');
151 $now = strtotime(DateTimeFormat::utcNow());
153 if ($created > $last_contact) {
154 $contact_time = strtotime($created);
156 $contact_time = strtotime($last_contact);
159 // If the last contact was less than 6 hours before then try again in 6 hours
160 if (($now - $contact_time) < (60 * 60 * 6)) {
161 return DateTimeFormat::utc('now +6 hour');
164 // If the last contact was less than 12 hours before then try again in 12 hours
165 if (($now - $contact_time) < (60 * 60 * 12)) {
166 return DateTimeFormat::utc('now +12 hour');
169 // If the last contact was less than 24 hours before then try tomorrow again
170 if (($now - $contact_time) < (60 * 60 * 24)) {
171 return DateTimeFormat::utc('now +1 day');
174 // If the last contact was less than a week before then try again in a week
175 if (($now - $contact_time) < (60 * 60 * 24 * 7)) {
176 return DateTimeFormat::utc('now +1 week');
179 // If the last contact was less than two weeks before then try again in two week
180 if (($now - $contact_time) < (60 * 60 * 24 * 14)) {
181 return DateTimeFormat::utc('now +2 week');
184 // If the last contact was less than a month before then try again in a month
185 if (($now - $contact_time) < (60 * 60 * 24 * 30)) {
186 return DateTimeFormat::utc('now +1 month');
189 // The system hadn't been successul contacted for more than a month, so try again in three months
190 return DateTimeFormat::utc('now +3 month');
194 * Checks the state of the given server.
196 * @param string $server_url URL of the given server
197 * @param string $network Network value that is used, when detection failed
198 * @param boolean $force Force an update.
199 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
201 * @return boolean 'true' if server seems vital
203 public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false)
205 $server_url = self::cleanURL($server_url);
206 if ($server_url == '') {
210 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
211 if (DBA::isResult($gserver)) {
212 if ($gserver['created'] <= DBA::NULL_DATETIME) {
213 $fields = ['created' => DateTimeFormat::utcNow()];
214 $condition = ['nurl' => Strings::normaliseLink($server_url)];
215 DBA::update('gserver', $fields, $condition);
218 if (!$force && (strtotime($gserver['next_contact']) > time())) {
219 Logger::info('No update needed', ['server' => $server_url]);
220 return (!$gserver['failed']);
222 Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]);
224 Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
227 return self::detect($server_url, $network, $only_nodeinfo);
231 * Set failed server status
235 public static function setFailure(string $url)
237 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($url)]);
238 if (DBA::isResult($gserver)) {
239 $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
240 DBA::update('gserver', ['failed' => true, 'last_failure' => DateTimeFormat::utcNow(),
241 'next_contact' => $next_update, 'detection-method' => null],
242 ['nurl' => Strings::normaliseLink($url)]);
243 Logger::info('Set failed status for existing server', ['url' => $url]);
246 DBA::insert('gserver', ['url' => $url, 'nurl' => Strings::normaliseLink($url),
247 'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
248 'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
249 Logger::info('Set failed status for new server', ['url' => $url]);
253 * Remove unwanted content from the given URL
256 * @return string cleaned URL
258 public static function cleanURL(string $url)
260 $url = trim($url, '/');
261 $url = str_replace('/index.php', '', $url);
263 $urlparts = parse_url($url);
264 unset($urlparts['user']);
265 unset($urlparts['pass']);
266 unset($urlparts['query']);
267 unset($urlparts['fragment']);
268 return Network::unparseURL($urlparts);
272 * Return the base URL
275 * @return string base URL
277 private static function getBaseURL(string $url)
279 $urlparts = parse_url(self::cleanURL($url));
280 unset($urlparts['path']);
281 return Network::unparseURL($urlparts);
285 * Detect server data (type, protocol, version number, ...)
286 * The detected data is then updated or inserted in the gserver table.
288 * @param string $url URL of the given server
289 * @param string $network Network value that is used, when detection failed
290 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
292 * @return boolean 'true' if server could be detected
294 public static function detect(string $url, string $network = '', bool $only_nodeinfo = false)
296 Logger::info('Detect server type', ['server' => $url]);
297 $serverdata = ['detection-method' => self::DETECT_MANUAL];
299 $original_url = $url;
301 // Remove URL content that is not supposed to exist for a server url
302 $url = self::cleanURL($url);
305 $baseurl = self::getBaseURL($url);
307 // If the URL missmatches, then we mark the old entry as failure
308 if ($url != $original_url) {
309 /// @todo What to do with "next_contact" here?
310 DBA::update('gserver', ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()],
311 ['nurl' => Strings::normaliseLink($original_url)]);
314 // When a nodeinfo is present, we don't need to dig further
315 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
316 $curlResult = DI::httpRequest()->get($url . '/.well-known/nodeinfo', ['timeout' => $xrd_timeout]);
317 if ($curlResult->isTimeout()) {
318 self::setFailure($url);
322 // On a redirect follow the new host but mark the old one as failure
323 if ($curlResult->isSuccess() && (parse_url($url, PHP_URL_HOST) != parse_url($curlResult->getRedirectUrl(), PHP_URL_HOST))) {
324 $curlResult = DI::httpRequest()->get($url, ['timeout' => $xrd_timeout]);
325 if (parse_url($url, PHP_URL_HOST) != parse_url($curlResult->getRedirectUrl(), PHP_URL_HOST)) {
326 Logger::info('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $curlResult->getRedirectUrl()]);
327 self::setFailure($url);
328 self::detect($curlResult->getRedirectUrl(), $network, $only_nodeinfo);
333 $nodeinfo = self::fetchNodeinfo($url, $curlResult);
334 if ($only_nodeinfo && empty($nodeinfo)) {
335 Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
336 self::setFailure($url);
340 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
341 if (empty($nodeinfo)) {
342 $nodeinfo = self::fetchStatistics($url);
345 // If that didn't work out well, we use some protocol specific endpoints
346 // For Friendica and Zot based networks we have to dive deeper to reveal more details
347 if (empty($nodeinfo['network']) || in_array($nodeinfo['network'], [Protocol::DFRN, Protocol::ZOT])) {
348 if (!empty($nodeinfo['detection-method'])) {
349 $serverdata['detection-method'] = $nodeinfo['detection-method'];
352 // Fetch the landing page, possibly it reveals some data
353 if (empty($nodeinfo['network'])) {
354 if ($baseurl == $url) {
355 $basedata = $serverdata;
357 $basedata = ['detection-method' => self::DETECT_MANUAL];
360 $curlResult = DI::httpRequest()->get($baseurl, ['timeout' => $xrd_timeout]);
361 if ($curlResult->isSuccess()) {
362 if ((parse_url($baseurl, PHP_URL_HOST) != parse_url($curlResult->getRedirectUrl(), PHP_URL_HOST))) {
363 Logger::info('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $curlResult->getRedirectUrl()]);
364 self::setFailure($url);
365 self::detect($curlResult->getRedirectUrl(), $network, $only_nodeinfo);
369 $basedata = self::analyseRootHeader($curlResult, $basedata);
370 $basedata = self::analyseRootBody($curlResult, $basedata, $baseurl);
373 if (!$curlResult->isSuccess() || empty($curlResult->getBody()) || self::invalidBody($curlResult->getBody())) {
374 self::setFailure($url);
378 if ($baseurl == $url) {
379 $serverdata = $basedata;
381 // When the base path doesn't seem to contain a social network we try the complete path.
382 // Most detectable system have to be installed in the root directory.
383 // We checked the base to avoid false positives.
384 $curlResult = DI::httpRequest()->get($url, ['timeout' => $xrd_timeout]);
385 if ($curlResult->isSuccess()) {
386 $urldata = self::analyseRootHeader($curlResult, $serverdata);
387 $urldata = self::analyseRootBody($curlResult, $urldata, $url);
389 $comparebase = $basedata;
390 unset($comparebase['info']);
391 unset($comparebase['site_name']);
392 $compareurl = $urldata;
393 unset($compareurl['info']);
394 unset($compareurl['site_name']);
396 // We assume that no one will install the identical system in the root and a subfolder
397 if (!empty(array_diff($comparebase, $compareurl))) {
398 $serverdata = $urldata;
404 if (empty($serverdata['network']) || ($serverdata['network'] == Protocol::ACTIVITYPUB)) {
405 $serverdata = self::detectMastodonAlikes($url, $serverdata);
408 // All following checks are done for systems that always have got a "host-meta" endpoint.
409 // With this check we don't have to waste time and ressources for dead systems.
410 // Also this hopefully prevents us from receiving abuse messages.
411 if (empty($serverdata['network']) && !self::validHostMeta($url)) {
412 self::setFailure($url);
416 if (empty($serverdata['network']) || in_array($serverdata['network'], [Protocol::DFRN, Protocol::ACTIVITYPUB])) {
417 $serverdata = self::detectFriendica($url, $serverdata);
420 // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
421 if (empty($serverdata['network']) || ($serverdata['network'] == Protocol::ZOT)) {
422 $serverdata = self::fetchSiteinfo($url, $serverdata);
425 // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations
426 if (empty($serverdata['network'])) {
427 $serverdata = self::detectHubzilla($url, $serverdata);
430 if (empty($serverdata['network']) || in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_BODY])) {
431 $serverdata = self::detectPeertube($url, $serverdata);
434 if (empty($serverdata['network'])) {
435 $serverdata = self::detectNextcloud($url, $serverdata);
438 if (empty($serverdata['network'])) {
439 $serverdata = self::detectGNUSocial($url, $serverdata);
442 $serverdata = array_merge($nodeinfo, $serverdata);
444 $serverdata = $nodeinfo;
447 // Detect the directory type
448 $serverdata['directory-type'] = self::DT_NONE;
449 $serverdata = self::checkPoCo($url, $serverdata);
450 $serverdata = self::checkMastodonDirectory($url, $serverdata);
452 // We can't detect the network type. Possibly it is some system that we don't know yet
453 if (empty($serverdata['network'])) {
454 $serverdata['network'] = Protocol::PHANTOM;
457 // When we hadn't been able to detect the network type, we use the hint from the parameter
458 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
459 $serverdata['network'] = $network;
462 $serverdata['url'] = $url;
463 $serverdata['nurl'] = Strings::normaliseLink($url);
465 // We take the highest number that we do find
466 $registeredUsers = $serverdata['registered-users'] ?? 0;
468 // On an active server there has to be at least a single user
469 if (($serverdata['network'] != Protocol::PHANTOM) && ($registeredUsers == 0)) {
470 $registeredUsers = 1;
473 if ($serverdata['network'] == Protocol::PHANTOM) {
474 $serverdata['registered-users'] = max($registeredUsers, 1);
475 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
478 $serverdata['next_contact'] = self::getNextUpdateDate(true);
480 $serverdata['last_contact'] = DateTimeFormat::utcNow();
481 $serverdata['failed'] = false;
483 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
484 if (!DBA::isResult($gserver)) {
485 $serverdata['created'] = DateTimeFormat::utcNow();
486 $ret = DBA::insert('gserver', $serverdata);
487 $id = DBA::lastInsertId();
489 // Don't override the network with 'unknown' when there had been a valid entry before
490 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($gserver['network'])) {
491 unset($serverdata['network']);
494 $ret = DBA::update('gserver', $serverdata, ['nurl' => $serverdata['nurl']]);
495 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
496 if (DBA::isResult($gserver)) {
497 $id = $gserver['id'];
501 if (!empty($serverdata['network']) && !empty($id) && ($serverdata['network'] != Protocol::PHANTOM)) {
502 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
503 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id]);
504 $max_users = max($apcontacts, $contacts, $registeredUsers, 1);
505 if ($max_users > $registeredUsers) {
506 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
507 DBA::update('gserver', ['registered-users' => $max_users], ['id' => $id]);
511 if (!empty($serverdata['network']) && in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
512 self::discoverRelay($url);
519 * Fetch relay data from a given server url
521 * @param string $server_url address of the server
522 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
524 private static function discoverRelay(string $server_url)
526 Logger::info('Discover relay data', ['server' => $server_url]);
528 $curlResult = DI::httpRequest()->get($server_url . '/.well-known/x-social-relay');
529 if (!$curlResult->isSuccess()) {
533 $data = json_decode($curlResult->getBody(), true);
534 if (!is_array($data)) {
538 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
539 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
541 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
543 $data['subscribe'] = false;
547 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
548 if (!DBA::isResult($gserver)) {
552 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
553 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
554 DBA::update('gserver', $fields, ['id' => $gserver['id']]);
557 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
559 if ($data['scope'] == 'tags') {
562 foreach ($data['tags'] as $tag) {
563 $tag = mb_strtolower($tag);
564 if (strlen($tag) < 100) {
569 foreach ($tags as $tag) {
570 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
574 // Create or update the relay contact
576 if (isset($data['protocols'])) {
577 if (isset($data['protocols']['diaspora'])) {
578 $fields['network'] = Protocol::DIASPORA;
580 if (isset($data['protocols']['diaspora']['receive'])) {
581 $fields['batch'] = $data['protocols']['diaspora']['receive'];
582 } elseif (is_string($data['protocols']['diaspora'])) {
583 $fields['batch'] = $data['protocols']['diaspora'];
587 if (isset($data['protocols']['dfrn'])) {
588 $fields['network'] = Protocol::DFRN;
590 if (isset($data['protocols']['dfrn']['receive'])) {
591 $fields['batch'] = $data['protocols']['dfrn']['receive'];
592 } elseif (is_string($data['protocols']['dfrn'])) {
593 $fields['batch'] = $data['protocols']['dfrn'];
597 if (isset($data['protocols']['activitypub'])) {
598 $fields['network'] = Protocol::ACTIVITYPUB;
600 if (!empty($data['protocols']['activitypub']['actor'])) {
601 $fields['url'] = $data['protocols']['activitypub']['actor'];
603 if (!empty($data['protocols']['activitypub']['receive'])) {
604 $fields['batch'] = $data['protocols']['activitypub']['receive'];
609 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
611 Relay::updateContact($gserver, $fields);
615 * Fetch server data from '/statistics.json' on the given server
617 * @param string $url URL of the given server
619 * @return array server data
621 private static function fetchStatistics(string $url)
623 $curlResult = DI::httpRequest()->get($url . '/statistics.json');
624 if (!$curlResult->isSuccess()) {
628 $data = json_decode($curlResult->getBody(), true);
633 $serverdata = ['detection-method' => self::DETECT_STATISTICS_JSON];
635 if (!empty($data['version'])) {
636 $serverdata['version'] = $data['version'];
637 // Version numbers on statistics.json are presented with additional info, e.g.:
638 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
639 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
642 if (!empty($data['name'])) {
643 $serverdata['site_name'] = $data['name'];
646 if (!empty($data['network'])) {
647 $serverdata['platform'] = strtolower($data['network']);
649 if ($serverdata['platform'] == 'diaspora') {
650 $serverdata['network'] = Protocol::DIASPORA;
651 } elseif ($serverdata['platform'] == 'friendica') {
652 $serverdata['network'] = Protocol::DFRN;
653 } elseif ($serverdata['platform'] == 'hubzilla') {
654 $serverdata['network'] = Protocol::ZOT;
655 } elseif ($serverdata['platform'] == 'redmatrix') {
656 $serverdata['network'] = Protocol::ZOT;
661 if (!empty($data['registrations_open'])) {
662 $serverdata['register_policy'] = Register::OPEN;
664 $serverdata['register_policy'] = Register::CLOSED;
671 * Detect server type by using the nodeinfo data
673 * @param string $url address of the server
674 * @param CurlResult $curlResult
675 * @return array Server data
676 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
678 private static function fetchNodeinfo(string $url, CurlResult $curlResult)
680 if (!$curlResult->isSuccess()) {
684 $nodeinfo = json_decode($curlResult->getBody(), true);
686 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
693 foreach ($nodeinfo['links'] as $link) {
694 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
695 Logger::info('Invalid nodeinfo format', ['url' => $url]);
698 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
699 $nodeinfo1_url = $link['href'];
700 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
701 $nodeinfo2_url = $link['href'];
705 if ($nodeinfo1_url . $nodeinfo2_url == '') {
711 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
712 if (!empty($nodeinfo2_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
713 $server = self::parseNodeinfo2($nodeinfo2_url);
716 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
717 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
718 $server = self::parseNodeinfo1($nodeinfo1_url);
727 * @param string $nodeinfo_url address of the nodeinfo path
728 * @return array Server data
729 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
731 private static function parseNodeinfo1(string $nodeinfo_url)
733 $curlResult = DI::httpRequest()->get($nodeinfo_url);
735 if (!$curlResult->isSuccess()) {
739 $nodeinfo = json_decode($curlResult->getBody(), true);
741 if (!is_array($nodeinfo)) {
745 $server = ['detection-method' => self::DETECT_NODEINFO_1,
746 'register_policy' => Register::CLOSED];
748 if (!empty($nodeinfo['openRegistrations'])) {
749 $server['register_policy'] = Register::OPEN;
752 if (is_array($nodeinfo['software'])) {
753 if (!empty($nodeinfo['software']['name'])) {
754 $server['platform'] = strtolower($nodeinfo['software']['name']);
757 if (!empty($nodeinfo['software']['version'])) {
758 $server['version'] = $nodeinfo['software']['version'];
759 // Version numbers on Nodeinfo are presented with additional info, e.g.:
760 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
761 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
765 if (!empty($nodeinfo['metadata']['nodeName'])) {
766 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
769 if (!empty($nodeinfo['usage']['users']['total'])) {
770 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
773 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
775 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
776 $protocols[$protocol] = true;
779 if (!empty($protocols['friendica'])) {
780 $server['network'] = Protocol::DFRN;
781 } elseif (!empty($protocols['activitypub'])) {
782 $server['network'] = Protocol::ACTIVITYPUB;
783 } elseif (!empty($protocols['diaspora'])) {
784 $server['network'] = Protocol::DIASPORA;
785 } elseif (!empty($protocols['ostatus'])) {
786 $server['network'] = Protocol::OSTATUS;
787 } elseif (!empty($protocols['gnusocial'])) {
788 $server['network'] = Protocol::OSTATUS;
789 } elseif (!empty($protocols['zot'])) {
790 $server['network'] = Protocol::ZOT;
794 if (empty($server)) {
804 * @param string $nodeinfo_url address of the nodeinfo path
805 * @return array Server data
806 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
808 private static function parseNodeinfo2(string $nodeinfo_url)
810 $curlResult = DI::httpRequest()->get($nodeinfo_url);
811 if (!$curlResult->isSuccess()) {
815 $nodeinfo = json_decode($curlResult->getBody(), true);
817 if (!is_array($nodeinfo)) {
821 $server = ['detection-method' => self::DETECT_NODEINFO_2,
822 'register_policy' => Register::CLOSED];
824 if (!empty($nodeinfo['openRegistrations'])) {
825 $server['register_policy'] = Register::OPEN;
828 if (is_array($nodeinfo['software'])) {
829 if (!empty($nodeinfo['software']['name'])) {
830 $server['platform'] = strtolower($nodeinfo['software']['name']);
833 if (!empty($nodeinfo['software']['version'])) {
834 $server['version'] = $nodeinfo['software']['version'];
835 // Version numbers on Nodeinfo are presented with additional info, e.g.:
836 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
837 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
841 if (!empty($nodeinfo['metadata']['nodeName'])) {
842 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
845 if (!empty($nodeinfo['usage']['users']['total'])) {
846 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
849 if (!empty($nodeinfo['protocols'])) {
851 foreach ($nodeinfo['protocols'] as $protocol) {
852 $protocols[$protocol] = true;
855 if (!empty($protocols['dfrn'])) {
856 $server['network'] = Protocol::DFRN;
857 } elseif (!empty($protocols['activitypub'])) {
858 $server['network'] = Protocol::ACTIVITYPUB;
859 } elseif (!empty($protocols['diaspora'])) {
860 $server['network'] = Protocol::DIASPORA;
861 } elseif (!empty($protocols['ostatus'])) {
862 $server['network'] = Protocol::OSTATUS;
863 } elseif (!empty($protocols['gnusocial'])) {
864 $server['network'] = Protocol::OSTATUS;
865 } elseif (!empty($protocols['zot'])) {
866 $server['network'] = Protocol::ZOT;
870 if (empty($server)) {
878 * Fetch server information from a 'siteinfo.json' file on the given server
880 * @param string $url URL of the given server
881 * @param array $serverdata array with server data
883 * @return array server data
885 private static function fetchSiteinfo(string $url, array $serverdata)
887 $curlResult = DI::httpRequest()->get($url . '/siteinfo.json');
888 if (!$curlResult->isSuccess()) {
892 $data = json_decode($curlResult->getBody(), true);
897 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
898 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
901 if (!empty($data['url'])) {
902 $serverdata['platform'] = strtolower($data['platform']);
903 $serverdata['version'] = $data['version'];
906 if (!empty($data['plugins'])) {
907 if (in_array('pubcrawl', $data['plugins'])) {
908 $serverdata['network'] = Protocol::ACTIVITYPUB;
909 } elseif (in_array('diaspora', $data['plugins'])) {
910 $serverdata['network'] = Protocol::DIASPORA;
911 } elseif (in_array('gnusoc', $data['plugins'])) {
912 $serverdata['network'] = Protocol::OSTATUS;
914 $serverdata['network'] = Protocol::ZOT;
918 if (!empty($data['site_name'])) {
919 $serverdata['site_name'] = $data['site_name'];
922 if (!empty($data['channels_total'])) {
923 $serverdata['registered-users'] = max($data['channels_total'], 1);
926 if (!empty($data['register_policy'])) {
927 switch ($data['register_policy']) {
928 case 'REGISTER_OPEN':
929 $serverdata['register_policy'] = Register::OPEN;
932 case 'REGISTER_APPROVE':
933 $serverdata['register_policy'] = Register::APPROVE;
936 case 'REGISTER_CLOSED':
938 $serverdata['register_policy'] = Register::CLOSED;
947 * Checks if the server contains a valid host meta file
949 * @param string $url URL of the given server
951 * @return boolean 'true' if the server seems to be vital
953 private static function validHostMeta(string $url)
955 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
956 $curlResult = DI::httpRequest()->get($url . '/.well-known/host-meta', ['timeout' => $xrd_timeout]);
957 if (!$curlResult->isSuccess()) {
961 $xrd = XML::parseString($curlResult->getBody());
962 if (!is_object($xrd)) {
966 $elements = XML::elementToArray($xrd);
967 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
972 foreach ($elements['xrd']['link'] as $link) {
973 // When there is more than a single "link" element, the array looks slightly different
974 if (!empty($link['@attributes'])) {
975 $link = $link['@attributes'];
978 if (empty($link['rel']) || empty($link['template'])) {
982 if ($link['rel'] == 'lrdd') {
983 // When the webfinger host is the same like the system host, it should be ok.
984 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
992 * Detect the network of the given server via their known contacts
994 * @param string $url URL of the given server
995 * @param array $serverdata array with server data
997 * @return array server data
999 private static function detectNetworkViaContacts(string $url, array $serverdata)
1003 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $serverdata['nurl']]]);
1004 while ($apcontact = DBA::fetch($apcontacts)) {
1005 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1007 DBA::close($apcontacts);
1009 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $serverdata['nurl']]]);
1010 while ($pcontact = DBA::fetch($pcontacts)) {
1011 $contacts[$pcontact['nurl']] = $pcontact['url'];
1013 DBA::close($pcontacts);
1015 if (empty($contacts)) {
1019 foreach ($contacts as $contact) {
1020 $probed = Contact::getByURL($contact);
1021 if (!empty($probed) && in_array($probed['network'], Protocol::FEDERATED)) {
1022 $serverdata['network'] = $probed['network'];
1027 $serverdata['registered-users'] = max($serverdata['registered-users'], count($contacts), 1);
1033 * Checks if the given server does have a '/poco' endpoint.
1034 * This is used for the 'PortableContact' functionality,
1035 * which is used by both Friendica and Hubzilla.
1037 * @param string $url URL of the given server
1038 * @param array $serverdata array with server data
1040 * @return array server data
1042 private static function checkPoCo(string $url, array $serverdata)
1044 $serverdata['poco'] = '';
1046 $curlResult = DI::httpRequest()->get($url . '/poco');
1047 if (!$curlResult->isSuccess()) {
1051 $data = json_decode($curlResult->getBody(), true);
1056 if (!empty($data['totalResults'])) {
1057 $registeredUsers = $serverdata['registered-users'] ?? 0;
1058 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1059 $serverdata['directory-type'] = self::DT_POCO;
1060 $serverdata['poco'] = $url . '/poco';
1067 * Checks if the given server does have a Mastodon style directory endpoint.
1069 * @param string $url URL of the given server
1070 * @param array $serverdata array with server data
1072 * @return array server data
1074 public static function checkMastodonDirectory(string $url, array $serverdata)
1076 $curlResult = DI::httpRequest()->get($url . '/api/v1/directory?limit=1');
1077 if (!$curlResult->isSuccess()) {
1081 $data = json_decode($curlResult->getBody(), true);
1086 if (count($data) == 1) {
1087 $serverdata['directory-type'] = self::DT_MASTODON;
1094 * Detects Peertube via their known endpoint
1096 * @param string $url URL of the given server
1097 * @param array $serverdata array with server data
1099 * @return array server data
1101 private static function detectPeertube(string $url, array $serverdata)
1103 $curlResult = DI::httpRequest()->get($url . '/api/v1/config');
1105 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1109 $data = json_decode($curlResult->getBody(), true);
1114 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1115 $serverdata['platform'] = 'peertube';
1116 $serverdata['version'] = $data['serverVersion'];
1117 $serverdata['network'] = Protocol::ACTIVITYPUB;
1119 if (!empty($data['instance']['name'])) {
1120 $serverdata['site_name'] = $data['instance']['name'];
1123 if (!empty($data['instance']['shortDescription'])) {
1124 $serverdata['info'] = $data['instance']['shortDescription'];
1127 if (!empty($data['signup'])) {
1128 if (!empty($data['signup']['allowed'])) {
1129 $serverdata['register_policy'] = Register::OPEN;
1133 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1134 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1142 * Detects the version number of a given server when it was a NextCloud installation
1144 * @param string $url URL of the given server
1145 * @param array $serverdata array with server data
1147 * @return array server data
1149 private static function detectNextcloud(string $url, array $serverdata)
1151 $curlResult = DI::httpRequest()->get($url . '/status.php');
1153 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1157 $data = json_decode($curlResult->getBody(), true);
1162 if (!empty($data['version'])) {
1163 $serverdata['platform'] = 'nextcloud';
1164 $serverdata['version'] = $data['version'];
1165 $serverdata['network'] = Protocol::ACTIVITYPUB;
1167 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1168 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1176 * Detects data from a given server url if it was a mastodon alike system
1178 * @param string $url URL of the given server
1179 * @param array $serverdata array with server data
1181 * @return array server data
1183 private static function detectMastodonAlikes(string $url, array $serverdata)
1185 $curlResult = DI::httpRequest()->get($url . '/api/v1/instance');
1187 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1191 $data = json_decode($curlResult->getBody(), true);
1196 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1197 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1200 if (!empty($data['version'])) {
1201 $serverdata['platform'] = 'mastodon';
1202 $serverdata['version'] = $data['version'] ?? '';
1203 $serverdata['network'] = Protocol::ACTIVITYPUB;
1206 if (!empty($data['title'])) {
1207 $serverdata['site_name'] = $data['title'];
1210 if (!empty($data['title']) && empty($serverdata['platform']) && empty($serverdata['network'])) {
1211 $serverdata['platform'] = 'mastodon';
1212 $serverdata['network'] = Protocol::ACTIVITYPUB;
1215 if (!empty($data['description'])) {
1216 $serverdata['info'] = trim($data['description']);
1219 if (!empty($data['stats']['user_count'])) {
1220 $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1223 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1224 $serverdata['platform'] = strtolower($matches[1]);
1225 $serverdata['version'] = $matches[2];
1228 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1229 $serverdata['platform'] = 'pleroma';
1230 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1233 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1234 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1235 $serverdata['platform'] = 'pleroma';
1242 * Detects data from typical Hubzilla endpoints
1244 * @param string $url URL of the given server
1245 * @param array $serverdata array with server data
1247 * @return array server data
1249 private static function detectHubzilla(string $url, array $serverdata)
1251 $curlResult = DI::httpRequest()->get($url . '/api/statusnet/config.json');
1252 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1256 $data = json_decode($curlResult->getBody(), true);
1257 if (empty($data) || empty($data['site'])) {
1261 if (!empty($data['site']['name'])) {
1262 $serverdata['site_name'] = $data['site']['name'];
1265 if (!empty($data['site']['platform'])) {
1266 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1267 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1268 $serverdata['network'] = Protocol::ZOT;
1271 if (!empty($data['site']['hubzilla'])) {
1272 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1273 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1274 $serverdata['network'] = Protocol::ZOT;
1277 if (!empty($data['site']['redmatrix'])) {
1278 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1279 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1280 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1281 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1284 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1285 $serverdata['network'] = Protocol::ZOT;
1289 $inviteonly = false;
1292 if (!empty($data['site']['closed'])) {
1293 $closed = self::toBoolean($data['site']['closed']);
1296 if (!empty($data['site']['private'])) {
1297 $private = self::toBoolean($data['site']['private']);
1300 if (!empty($data['site']['inviteonly'])) {
1301 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1304 if (!$closed && !$private and $inviteonly) {
1305 $serverdata['register_policy'] = Register::APPROVE;
1306 } elseif (!$closed && !$private) {
1307 $serverdata['register_policy'] = Register::OPEN;
1309 $serverdata['register_policy'] = Register::CLOSED;
1312 if (!empty($serverdata['network']) && in_array($serverdata['detection-method'],
1313 [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1314 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1321 * Converts input value to a boolean value
1323 * @param string|integer $val
1327 private static function toBoolean($val)
1329 if (($val == 'true') || ($val == 1)) {
1331 } elseif (($val == 'false') || ($val == 0)) {
1339 * Detect if the URL belongs to a GNU Social server
1341 * @param string $url URL of the given server
1342 * @param array $serverdata array with server data
1344 * @return array server data
1346 private static function detectGNUSocial(string $url, array $serverdata)
1348 // Test for GNU Social
1349 $curlResult = DI::httpRequest()->get($url . '/api/gnusocial/version.json');
1350 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1351 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1352 $serverdata['platform'] = 'gnusocial';
1353 // Remove junk that some GNU Social servers return
1354 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1355 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1356 $serverdata['version'] = trim($serverdata['version'], '"');
1357 $serverdata['network'] = Protocol::OSTATUS;
1359 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1360 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1366 // Test for Statusnet
1367 $curlResult = DI::httpRequest()->get($url . '/api/statusnet/version.json');
1368 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1369 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1371 // Remove junk that some GNU Social servers return
1372 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1373 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1374 $serverdata['version'] = trim($serverdata['version'], '"');
1376 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1377 $serverdata['platform'] = 'pleroma';
1378 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1379 $serverdata['network'] = Protocol::ACTIVITYPUB;
1381 $serverdata['platform'] = 'statusnet';
1382 $serverdata['network'] = Protocol::OSTATUS;
1385 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1386 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1394 * Detect if the URL belongs to a Friendica server
1396 * @param string $url URL of the given server
1397 * @param array $serverdata array with server data
1399 * @return array server data
1401 private static function detectFriendica(string $url, array $serverdata)
1403 $curlResult = DI::httpRequest()->get($url . '/friendica/json');
1404 if (!$curlResult->isSuccess()) {
1405 $curlResult = DI::httpRequest()->get($url . '/friendika/json');
1407 $platform = 'Friendika';
1410 $platform = 'Friendica';
1413 if (!$curlResult->isSuccess()) {
1417 $data = json_decode($curlResult->getBody(), true);
1418 if (empty($data) || empty($data['version'])) {
1422 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1423 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1426 $serverdata['network'] = Protocol::DFRN;
1427 $serverdata['version'] = $data['version'];
1429 if (!empty($data['no_scrape_url'])) {
1430 $serverdata['noscrape'] = $data['no_scrape_url'];
1433 if (!empty($data['site_name'])) {
1434 $serverdata['site_name'] = $data['site_name'];
1437 if (!empty($data['info'])) {
1438 $serverdata['info'] = trim($data['info']);
1441 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1442 switch ($register_policy) {
1443 case 'REGISTER_OPEN':
1444 $serverdata['register_policy'] = Register::OPEN;
1447 case 'REGISTER_APPROVE':
1448 $serverdata['register_policy'] = Register::APPROVE;
1451 case 'REGISTER_CLOSED':
1452 case 'REGISTER_INVITATION':
1453 $serverdata['register_policy'] = Register::CLOSED;
1456 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
1457 $serverdata['register_policy'] = Register::CLOSED;
1461 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
1467 * Analyses the landing page of a given server for hints about type and system of that server
1469 * @param object $curlResult result of curl execution
1470 * @param array $serverdata array with server data
1471 * @param string $url Server URL
1473 * @return array server data
1475 private static function analyseRootBody($curlResult, array $serverdata, string $url)
1477 $doc = new DOMDocument();
1478 @$doc->loadHTML($curlResult->getBody());
1479 $xpath = new DOMXPath($doc);
1481 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
1482 if (!empty($title)) {
1483 $serverdata['site_name'] = $title;
1486 $list = $xpath->query('//meta[@name]');
1488 foreach ($list as $node) {
1490 if ($node->attributes->length) {
1491 foreach ($node->attributes as $attribute) {
1492 $value = trim($attribute->value);
1493 if (empty($value)) {
1497 $attr[$attribute->name] = $value;
1500 if (empty($attr['name']) || empty($attr['content'])) {
1505 if ($attr['name'] == 'description') {
1506 $serverdata['info'] = $attr['content'];
1509 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
1510 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad'])) {
1511 $serverdata['platform'] = strtolower($attr['content']);
1512 if (in_array($attr['content'], ['Misskey', 'Write.as'])) {
1513 $serverdata['network'] = Protocol::ACTIVITYPUB;
1516 if (($attr['name'] == 'generator') && (empty($serverdata['platform']) || (substr(strtolower($attr['content']), 0, 9) == 'wordpress'))) {
1517 $serverdata['platform'] = strtolower($attr['content']);
1518 $version_part = explode(' ', $attr['content']);
1520 if (count($version_part) == 2) {
1521 if (in_array($version_part[0], ['WordPress'])) {
1522 $serverdata['platform'] = 'wordpress';
1523 $serverdata['version'] = $version_part[1];
1525 // We still do need a reliable test if some AP plugin is activated
1526 if (DBA::exists('apcontact', ['baseurl' => $url])) {
1527 $serverdata['network'] = Protocol::ACTIVITYPUB;
1529 $serverdata['network'] = Protocol::FEED;
1532 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1533 $serverdata['detection-method'] = self::DETECT_BODY;
1536 if (in_array($version_part[0], ['Friendika', 'Friendica'])) {
1537 $serverdata['platform'] = strtolower($version_part[0]);
1538 $serverdata['version'] = $version_part[1];
1539 $serverdata['network'] = Protocol::DFRN;
1545 $list = $xpath->query('//meta[@property]');
1547 foreach ($list as $node) {
1549 if ($node->attributes->length) {
1550 foreach ($node->attributes as $attribute) {
1551 $value = trim($attribute->value);
1552 if (empty($value)) {
1556 $attr[$attribute->name] = $value;
1559 if (empty($attr['property']) || empty($attr['content'])) {
1564 if ($attr['property'] == 'og:site_name') {
1565 $serverdata['site_name'] = $attr['content'];
1568 if ($attr['property'] == 'og:description') {
1569 $serverdata['info'] = $attr['content'];
1572 if ($attr['property'] == 'og:platform') {
1573 $serverdata['platform'] = strtolower($attr['content']);
1575 if (in_array($attr['content'], ['PeerTube'])) {
1576 $serverdata['network'] = Protocol::ACTIVITYPUB;
1580 if ($attr['property'] == 'generator') {
1581 $serverdata['platform'] = strtolower($attr['content']);
1583 if (in_array($attr['content'], ['hubzilla'])) {
1584 // We later check which compatible protocol modules are loaded.
1585 $serverdata['network'] = Protocol::ZOT;
1590 if (!empty($serverdata['network']) && ($serverdata['detection-method'] == self::DETECT_MANUAL)) {
1591 $serverdata['detection-method'] = self::DETECT_BODY;
1598 * Analyses the header data of a given server for hints about type and system of that server
1600 * @param object $curlResult result of curl execution
1601 * @param array $serverdata array with server data
1603 * @return array server data
1605 private static function analyseRootHeader($curlResult, array $serverdata)
1607 if ($curlResult->getHeader('server') == 'Mastodon') {
1608 $serverdata['platform'] = 'mastodon';
1609 $serverdata['network'] = Protocol::ACTIVITYPUB;
1610 } elseif ($curlResult->inHeader('x-diaspora-version')) {
1611 $serverdata['platform'] = 'diaspora';
1612 $serverdata['network'] = Protocol::DIASPORA;
1613 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version');
1614 } elseif ($curlResult->inHeader('x-friendica-version')) {
1615 $serverdata['platform'] = 'friendica';
1616 $serverdata['network'] = Protocol::DFRN;
1617 $serverdata['version'] = $curlResult->getHeader('x-friendica-version');
1622 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1623 $serverdata['detection-method'] = self::DETECT_HEADER;
1630 * Test if the body contains valid content
1632 * @param string $body
1635 private static function invalidBody(string $body)
1637 // Currently we only test for a HTML element.
1638 // Possibly we enhance this in the future.
1639 return !strpos($body, '>');
1643 * Update GServer entries
1645 public static function discover()
1647 // Update the server list
1648 self::discoverFederation();
1652 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
1654 if ($requery_days == 0) {
1658 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
1660 $gservers = DBA::p("SELECT `id`, `url`, `nurl`, `network`, `poco`, `directory-type`
1663 AND `directory-type` != ?
1664 AND `last_poco_query` < ?
1665 ORDER BY RAND()", self::DT_NONE, $last_update
1668 while ($gserver = DBA::fetch($gservers)) {
1669 Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1670 Worker::add(PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
1672 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1673 Worker::add(PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
1675 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1676 DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);
1678 if (--$no_of_queries == 0) {
1683 DBA::close($gservers);
1687 * Discover federated servers
1689 private static function discoverFederation()
1691 $last = DI::config()->get('poco', 'last_federation_discovery');
1694 $next = $last + (24 * 60 * 60);
1696 if ($next > time()) {
1701 // Discover federated servers
1702 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
1703 foreach ($protocols as $protocol) {
1704 $query = '{nodes(protocol:"' . $protocol . '"){host}}';
1705 $curlResult = DI::httpRequest()->fetch('https://the-federation.info/graphql?query=' . urlencode($query));
1706 if (!empty($curlResult)) {
1707 $data = json_decode($curlResult, true);
1708 if (!empty($data['data']['nodes'])) {
1709 foreach ($data['data']['nodes'] as $server) {
1710 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
1711 self::add('https://' . $server['host'], true);
1717 // Disvover Mastodon servers
1718 $accesstoken = DI::config()->get('system', 'instances_social_key');
1720 if (!empty($accesstoken)) {
1721 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1722 $header = ['Authorization: Bearer '.$accesstoken];
1723 $curlResult = DI::httpRequest()->get($api, ['header' => $header]);
1725 if ($curlResult->isSuccess()) {
1726 $servers = json_decode($curlResult->getBody(), true);
1728 foreach ($servers['instances'] as $server) {
1729 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
1735 DI::config()->set('poco', 'last_federation_discovery', time());