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
68 // Standardized endpoints
69 const DETECT_STATISTICS_JSON = 100;
70 const DETECT_NODEINFO_1 = 101;
71 const DETECT_NODEINFO_2 = 102;
74 * Get the ID for the given server URL
77 * @param boolean $no_check Don't check if the server hadn't been found
78 * @return int gserver id
80 public static function getID(string $url, bool $no_check = false)
86 $url = self::cleanURL($url);
88 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
89 if (DBA::isResult($gserver)) {
90 Logger::info('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
91 return $gserver['id'];
94 if ($no_check || !self::check($url)) {
98 return self::getID($url, true);
102 * Checks if the given server is reachable
104 * @param string $profile URL of the given profile
105 * @param string $server URL of the given server (If empty, taken from profile)
106 * @param string $network Network value that is used, when detection failed
107 * @param boolean $force Force an update.
109 * @return boolean 'true' if server seems vital
111 public static function reachable(string $profile, string $server = '', string $network = '', bool $force = false)
114 $contact = Contact::getByURL($profile, null, ['baseurl']);
115 if (!empty($contact['baseurl'])) {
116 $server = $contact['baseurl'];
124 return self::check($server, $network, $force);
128 * Decides if a server needs to be updated, based upon several date fields
130 * @param date $created Creation date of that server entry
131 * @param date $updated When had the server entry be updated
132 * @param date $last_failure Last failure when contacting that server
133 * @param date $last_contact Last time the server had been contacted
135 * @return boolean Does the server record needs an update?
137 public static function updateNeeded($created, $updated, $last_failure, $last_contact)
139 $now = strtotime(DateTimeFormat::utcNow());
141 if ($updated > $last_contact) {
142 $contact_time = strtotime($updated);
144 $contact_time = strtotime($last_contact);
147 $failure_time = strtotime($last_failure);
148 $created_time = strtotime($created);
150 // If there is no "created" time then use the current time
151 if ($created_time <= 0) {
152 $created_time = $now;
155 // If the last contact was less than 24 hours then don't update
156 if (($now - $contact_time) < (60 * 60 * 24)) {
160 // If the last failure was less than 24 hours then don't update
161 if (($now - $failure_time) < (60 * 60 * 24)) {
165 // If the last contact was less than a week ago and the last failure is older than a week then don't update
166 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) && ($contact_time > $failure_time))
169 // If the last contact time was more than a week ago and the contact was created more than a week ago, then only try once a week
170 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) && (($now - $created_time) > (60 * 60 * 24 * 7)) && (($now - $failure_time) < (60 * 60 * 24 * 7))) {
174 // If the last contact time was more than a month ago and the contact was created more than a month ago, then only try once a month
175 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) && (($now - $created_time) > (60 * 60 * 24 * 30)) && (($now - $failure_time) < (60 * 60 * 24 * 30))) {
183 * Checks the state of the given server.
185 * @param string $server_url URL of the given server
186 * @param string $network Network value that is used, when detection failed
187 * @param boolean $force Force an update.
188 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
190 * @return boolean 'true' if server seems vital
192 public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false)
194 $server_url = self::cleanURL($server_url);
196 if ($server_url == '') {
200 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
201 if (DBA::isResult($gserver)) {
202 if ($gserver['created'] <= DBA::NULL_DATETIME) {
203 $fields = ['created' => DateTimeFormat::utcNow()];
204 $condition = ['nurl' => Strings::normaliseLink($server_url)];
205 DBA::update('gserver', $fields, $condition);
208 $last_contact = $gserver['last_contact'];
209 $last_failure = $gserver['last_failure'];
211 // See discussion under https://forum.friendi.ca/display/0b6b25a8135aabc37a5a0f5684081633
212 // It can happen that a zero date is in the database, but storing it again is forbidden.
213 if ($last_contact < DBA::NULL_DATETIME) {
214 $last_contact = DBA::NULL_DATETIME;
217 if ($last_failure < DBA::NULL_DATETIME) {
218 $last_failure = DBA::NULL_DATETIME;
221 if (!$force && !self::updateNeeded($gserver['created'], '', $last_failure, $last_contact)) {
222 Logger::info('No update needed', ['server' => $server_url]);
223 return ($last_contact >= $last_failure);
225 Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force, 'Created' => $gserver['created'], 'Failure' => $last_failure, 'Contact' => $last_contact]);
227 Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
230 return self::detect($server_url, $network, $only_nodeinfo);
234 * Set failed server status
238 private static function setFailure(string $url)
240 if (DBA::exists('gserver', ['nurl' => Strings::normaliseLink($url)])) {
241 DBA::update('gserver', ['failed' => true, 'last_failure' => DateTimeFormat::utcNow(), '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 DBA::update('gserver', ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()],
310 ['nurl' => Strings::normaliseLink($original_url)]);
313 // When a nodeinfo is present, we don't need to dig further
314 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
315 $curlResult = DI::httpRequest()->get($url . '/.well-known/nodeinfo', ['timeout' => $xrd_timeout]);
316 if ($curlResult->isTimeout()) {
317 self::setFailure($url);
321 $nodeinfo = self::fetchNodeinfo($url, $curlResult);
322 if ($only_nodeinfo && empty($nodeinfo)) {
323 Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
324 self::setFailure($url);
328 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
329 if (empty($nodeinfo)) {
330 $nodeinfo = self::fetchStatistics($url);
333 // If that didn't work out well, we use some protocol specific endpoints
334 // For Friendica and Zot based networks we have to dive deeper to reveal more details
335 if (empty($nodeinfo['network']) || in_array($nodeinfo['network'], [Protocol::DFRN, Protocol::ZOT])) {
336 if (!empty($nodeinfo['detection-method'])) {
337 $serverdata['detection-method'] = $nodeinfo['detection-method'];
340 // Fetch the landing page, possibly it reveals some data
341 if (empty($nodeinfo['network'])) {
342 if ($baseurl == $url) {
343 $basedata = $serverdata;
345 $basedata = ['detection-method' => self::DETECT_MANUAL];
348 $curlResult = DI::httpRequest()->get($baseurl, ['timeout' => $xrd_timeout]);
349 if ($curlResult->isSuccess()) {
350 $basedata = self::analyseRootHeader($curlResult, $basedata);
351 $basedata = self::analyseRootBody($curlResult, $basedata, $baseurl);
354 if (!$curlResult->isSuccess() || empty($curlResult->getBody()) || self::invalidBody($curlResult->getBody())) {
355 self::setFailure($url);
359 if ($baseurl == $url) {
360 $serverdata = $basedata;
362 // When the base path doesn't seem to contain a social network we try the complete path.
363 // Most detectable system have to be installed in the root directory.
364 // We checked the base to avoid false positives.
365 $curlResult = DI::httpRequest()->get($url, ['timeout' => $xrd_timeout]);
366 if ($curlResult->isSuccess()) {
367 $urldata = self::analyseRootHeader($curlResult, $serverdata);
368 $urldata = self::analyseRootBody($curlResult, $urldata, $url);
370 $comparebase = $basedata;
371 unset($comparebase['info']);
372 unset($comparebase['site_name']);
373 $compareurl = $urldata;
374 unset($compareurl['info']);
375 unset($compareurl['site_name']);
377 // We assume that no one will install the identical system in the root and a subfolder
378 if (!empty(array_diff($comparebase, $compareurl))) {
379 $serverdata = $urldata;
385 if (empty($serverdata['network']) || ($serverdata['network'] == Protocol::ACTIVITYPUB)) {
386 $serverdata = self::detectMastodonAlikes($url, $serverdata);
389 // All following checks are done for systems that always have got a "host-meta" endpoint.
390 // With this check we don't have to waste time and ressources for dead systems.
391 // Also this hopefully prevents us from receiving abuse messages.
392 if (empty($serverdata['network']) && !self::validHostMeta($url)) {
393 self::setFailure($url);
397 if (empty($serverdata['network']) || in_array($serverdata['network'], [Protocol::DFRN, Protocol::ACTIVITYPUB])) {
398 $serverdata = self::detectFriendica($url, $serverdata);
401 // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
402 if (empty($serverdata['network']) || ($serverdata['network'] == Protocol::ZOT)) {
403 $serverdata = self::fetchSiteinfo($url, $serverdata);
406 // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations
407 if (empty($serverdata['network'])) {
408 $serverdata = self::detectHubzilla($url, $serverdata);
411 if (empty($serverdata['network'])) {
412 $serverdata = self::detectNextcloud($url, $serverdata);
415 if (empty($serverdata['network'])) {
416 $serverdata = self::detectGNUSocial($url, $serverdata);
419 $serverdata = array_merge($nodeinfo, $serverdata);
421 $serverdata = $nodeinfo;
424 // Detect the directory type
425 $serverdata['directory-type'] = self::DT_NONE;
426 $serverdata = self::checkPoCo($url, $serverdata);
427 $serverdata = self::checkMastodonDirectory($url, $serverdata);
429 // We can't detect the network type. Possibly it is some system that we don't know yet
430 if (empty($serverdata['network'])) {
431 $serverdata['network'] = Protocol::PHANTOM;
434 // When we hadn't been able to detect the network type, we use the hint from the parameter
435 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
436 $serverdata['network'] = $network;
439 $serverdata['url'] = $url;
440 $serverdata['nurl'] = Strings::normaliseLink($url);
442 // We take the highest number that we do find
443 $registeredUsers = $serverdata['registered-users'] ?? 0;
445 // On an active server there has to be at least a single user
446 if (($serverdata['network'] != Protocol::PHANTOM) && ($registeredUsers == 0)) {
447 $registeredUsers = 1;
450 if ($serverdata['network'] == Protocol::PHANTOM) {
451 $serverdata['registered-users'] = $registeredUsers;
452 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
455 $serverdata['last_contact'] = DateTimeFormat::utcNow();
456 $serverdata['failed'] = false;
458 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
459 if (!DBA::isResult($gserver)) {
460 $serverdata['created'] = DateTimeFormat::utcNow();
461 $ret = DBA::insert('gserver', $serverdata);
462 $id = DBA::lastInsertId();
464 // Don't override the network with 'unknown' when there had been a valid entry before
465 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($gserver['network'])) {
466 unset($serverdata['network']);
469 $ret = DBA::update('gserver', $serverdata, ['nurl' => $serverdata['nurl']]);
470 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
471 if (DBA::isResult($gserver)) {
472 $id = $gserver['id'];
476 if (!empty($serverdata['network']) && !empty($id) && ($serverdata['network'] != Protocol::PHANTOM)) {
477 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
478 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id]);
479 $max_users = max($apcontacts, $contacts, $registeredUsers);
480 if ($max_users > $registeredUsers) {
481 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
482 DBA::update('gserver', ['registered-users' => $max_users], ['id' => $id]);
486 if (!empty($serverdata['network']) && in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
487 self::discoverRelay($url);
494 * Fetch relay data from a given server url
496 * @param string $server_url address of the server
497 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
499 private static function discoverRelay(string $server_url)
501 Logger::info('Discover relay data', ['server' => $server_url]);
503 $curlResult = DI::httpRequest()->get($server_url . '/.well-known/x-social-relay');
504 if (!$curlResult->isSuccess()) {
508 $data = json_decode($curlResult->getBody(), true);
509 if (!is_array($data)) {
513 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
514 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
516 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
518 $data['subscribe'] = false;
522 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
523 if (!DBA::isResult($gserver)) {
527 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
528 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
529 DBA::update('gserver', $fields, ['id' => $gserver['id']]);
532 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
534 if ($data['scope'] == 'tags') {
537 foreach ($data['tags'] as $tag) {
538 $tag = mb_strtolower($tag);
539 if (strlen($tag) < 100) {
544 foreach ($tags as $tag) {
545 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
549 // Create or update the relay contact
551 if (isset($data['protocols'])) {
552 if (isset($data['protocols']['diaspora'])) {
553 $fields['network'] = Protocol::DIASPORA;
555 if (isset($data['protocols']['diaspora']['receive'])) {
556 $fields['batch'] = $data['protocols']['diaspora']['receive'];
557 } elseif (is_string($data['protocols']['diaspora'])) {
558 $fields['batch'] = $data['protocols']['diaspora'];
562 if (isset($data['protocols']['dfrn'])) {
563 $fields['network'] = Protocol::DFRN;
565 if (isset($data['protocols']['dfrn']['receive'])) {
566 $fields['batch'] = $data['protocols']['dfrn']['receive'];
567 } elseif (is_string($data['protocols']['dfrn'])) {
568 $fields['batch'] = $data['protocols']['dfrn'];
572 if (isset($data['protocols']['activitypub'])) {
573 $fields['network'] = Protocol::ACTIVITYPUB;
575 if (!empty($data['protocols']['activitypub']['actor'])) {
576 $fields['url'] = $data['protocols']['activitypub']['actor'];
578 if (!empty($data['protocols']['activitypub']['receive'])) {
579 $fields['batch'] = $data['protocols']['activitypub']['receive'];
584 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
586 Relay::updateContact($gserver, $fields);
590 * Fetch server data from '/statistics.json' on the given server
592 * @param string $url URL of the given server
594 * @return array server data
596 private static function fetchStatistics(string $url)
598 $curlResult = DI::httpRequest()->get($url . '/statistics.json');
599 if (!$curlResult->isSuccess()) {
603 $data = json_decode($curlResult->getBody(), true);
608 $serverdata = ['detection-method' => self::DETECT_STATISTICS_JSON];
610 if (!empty($data['version'])) {
611 $serverdata['version'] = $data['version'];
612 // Version numbers on statistics.json are presented with additional info, e.g.:
613 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
614 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
617 if (!empty($data['name'])) {
618 $serverdata['site_name'] = $data['name'];
621 if (!empty($data['network'])) {
622 $serverdata['platform'] = strtolower($data['network']);
624 if ($serverdata['platform'] == 'diaspora') {
625 $serverdata['network'] = Protocol::DIASPORA;
626 } elseif ($serverdata['platform'] == 'friendica') {
627 $serverdata['network'] = Protocol::DFRN;
628 } elseif ($serverdata['platform'] == 'hubzilla') {
629 $serverdata['network'] = Protocol::ZOT;
630 } elseif ($serverdata['platform'] == 'redmatrix') {
631 $serverdata['network'] = Protocol::ZOT;
636 if (!empty($data['registrations_open'])) {
637 $serverdata['register_policy'] = Register::OPEN;
639 $serverdata['register_policy'] = Register::CLOSED;
646 * Detect server type by using the nodeinfo data
648 * @param string $url address of the server
649 * @param CurlResult $curlResult
650 * @return array Server data
651 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
653 private static function fetchNodeinfo(string $url, CurlResult $curlResult)
655 if (!$curlResult->isSuccess()) {
659 $nodeinfo = json_decode($curlResult->getBody(), true);
661 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
668 foreach ($nodeinfo['links'] as $link) {
669 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
670 Logger::info('Invalid nodeinfo format', ['url' => $url]);
673 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
674 $nodeinfo1_url = $link['href'];
675 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
676 $nodeinfo2_url = $link['href'];
680 if ($nodeinfo1_url . $nodeinfo2_url == '') {
686 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
687 if (!empty($nodeinfo2_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
688 $server = self::parseNodeinfo2($nodeinfo2_url);
691 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
692 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
693 $server = self::parseNodeinfo1($nodeinfo1_url);
702 * @param string $nodeinfo_url address of the nodeinfo path
703 * @return array Server data
704 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
706 private static function parseNodeinfo1(string $nodeinfo_url)
708 $curlResult = DI::httpRequest()->get($nodeinfo_url);
710 if (!$curlResult->isSuccess()) {
714 $nodeinfo = json_decode($curlResult->getBody(), true);
716 if (!is_array($nodeinfo)) {
720 $server = ['detection-method' => self::DETECT_NODEINFO_1,
721 'register_policy' => Register::CLOSED];
723 if (!empty($nodeinfo['openRegistrations'])) {
724 $server['register_policy'] = Register::OPEN;
727 if (is_array($nodeinfo['software'])) {
728 if (!empty($nodeinfo['software']['name'])) {
729 $server['platform'] = strtolower($nodeinfo['software']['name']);
732 if (!empty($nodeinfo['software']['version'])) {
733 $server['version'] = $nodeinfo['software']['version'];
734 // Version numbers on Nodeinfo are presented with additional info, e.g.:
735 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
736 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
740 if (!empty($nodeinfo['metadata']['nodeName'])) {
741 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
744 if (!empty($nodeinfo['usage']['users']['total'])) {
745 $server['registered-users'] = $nodeinfo['usage']['users']['total'];
748 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
750 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
751 $protocols[$protocol] = true;
754 if (!empty($protocols['friendica'])) {
755 $server['network'] = Protocol::DFRN;
756 } elseif (!empty($protocols['activitypub'])) {
757 $server['network'] = Protocol::ACTIVITYPUB;
758 } elseif (!empty($protocols['diaspora'])) {
759 $server['network'] = Protocol::DIASPORA;
760 } elseif (!empty($protocols['ostatus'])) {
761 $server['network'] = Protocol::OSTATUS;
762 } elseif (!empty($protocols['gnusocial'])) {
763 $server['network'] = Protocol::OSTATUS;
764 } elseif (!empty($protocols['zot'])) {
765 $server['network'] = Protocol::ZOT;
769 if (empty($server)) {
779 * @param string $nodeinfo_url address of the nodeinfo path
780 * @return array Server data
781 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
783 private static function parseNodeinfo2(string $nodeinfo_url)
785 $curlResult = DI::httpRequest()->get($nodeinfo_url);
786 if (!$curlResult->isSuccess()) {
790 $nodeinfo = json_decode($curlResult->getBody(), true);
792 if (!is_array($nodeinfo)) {
796 $server = ['detection-method' => self::DETECT_NODEINFO_2,
797 'register_policy' => Register::CLOSED];
799 if (!empty($nodeinfo['openRegistrations'])) {
800 $server['register_policy'] = Register::OPEN;
803 if (is_array($nodeinfo['software'])) {
804 if (!empty($nodeinfo['software']['name'])) {
805 $server['platform'] = strtolower($nodeinfo['software']['name']);
808 if (!empty($nodeinfo['software']['version'])) {
809 $server['version'] = $nodeinfo['software']['version'];
810 // Version numbers on Nodeinfo are presented with additional info, e.g.:
811 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
812 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
816 if (!empty($nodeinfo['metadata']['nodeName'])) {
817 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
820 if (!empty($nodeinfo['usage']['users']['total'])) {
821 $server['registered-users'] = $nodeinfo['usage']['users']['total'];
824 if (!empty($nodeinfo['protocols'])) {
826 foreach ($nodeinfo['protocols'] as $protocol) {
827 $protocols[$protocol] = true;
830 if (!empty($protocols['dfrn'])) {
831 $server['network'] = Protocol::DFRN;
832 } elseif (!empty($protocols['activitypub'])) {
833 $server['network'] = Protocol::ACTIVITYPUB;
834 } elseif (!empty($protocols['diaspora'])) {
835 $server['network'] = Protocol::DIASPORA;
836 } elseif (!empty($protocols['ostatus'])) {
837 $server['network'] = Protocol::OSTATUS;
838 } elseif (!empty($protocols['gnusocial'])) {
839 $server['network'] = Protocol::OSTATUS;
840 } elseif (!empty($protocols['zot'])) {
841 $server['network'] = Protocol::ZOT;
845 if (empty($server)) {
853 * Fetch server information from a 'siteinfo.json' file on the given server
855 * @param string $url URL of the given server
856 * @param array $serverdata array with server data
858 * @return array server data
860 private static function fetchSiteinfo(string $url, array $serverdata)
862 $curlResult = DI::httpRequest()->get($url . '/siteinfo.json');
863 if (!$curlResult->isSuccess()) {
867 $data = json_decode($curlResult->getBody(), true);
872 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
873 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
876 if (!empty($data['url'])) {
877 $serverdata['platform'] = strtolower($data['platform']);
878 $serverdata['version'] = $data['version'];
881 if (!empty($data['plugins'])) {
882 if (in_array('pubcrawl', $data['plugins'])) {
883 $serverdata['network'] = Protocol::ACTIVITYPUB;
884 } elseif (in_array('diaspora', $data['plugins'])) {
885 $serverdata['network'] = Protocol::DIASPORA;
886 } elseif (in_array('gnusoc', $data['plugins'])) {
887 $serverdata['network'] = Protocol::OSTATUS;
889 $serverdata['network'] = Protocol::ZOT;
893 if (!empty($data['site_name'])) {
894 $serverdata['site_name'] = $data['site_name'];
897 if (!empty($data['channels_total'])) {
898 $serverdata['registered-users'] = $data['channels_total'];
901 if (!empty($data['register_policy'])) {
902 switch ($data['register_policy']) {
903 case 'REGISTER_OPEN':
904 $serverdata['register_policy'] = Register::OPEN;
907 case 'REGISTER_APPROVE':
908 $serverdata['register_policy'] = Register::APPROVE;
911 case 'REGISTER_CLOSED':
913 $serverdata['register_policy'] = Register::CLOSED;
922 * Checks if the server contains a valid host meta file
924 * @param string $url URL of the given server
926 * @return boolean 'true' if the server seems to be vital
928 private static function validHostMeta(string $url)
930 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
931 $curlResult = DI::httpRequest()->get($url . '/.well-known/host-meta', ['timeout' => $xrd_timeout]);
932 if (!$curlResult->isSuccess()) {
936 $xrd = XML::parseString($curlResult->getBody());
937 if (!is_object($xrd)) {
941 $elements = XML::elementToArray($xrd);
942 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
947 foreach ($elements['xrd']['link'] as $link) {
948 // When there is more than a single "link" element, the array looks slightly different
949 if (!empty($link['@attributes'])) {
950 $link = $link['@attributes'];
953 if (empty($link['rel']) || empty($link['template'])) {
957 if ($link['rel'] == 'lrdd') {
958 // When the webfinger host is the same like the system host, it should be ok.
959 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
967 * Detect the network of the given server via their known contacts
969 * @param string $url URL of the given server
970 * @param array $serverdata array with server data
972 * @return array server data
974 private static function detectNetworkViaContacts(string $url, array $serverdata)
978 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $serverdata['nurl']]]);
979 while ($apcontact = DBA::fetch($apcontacts)) {
980 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
982 DBA::close($apcontacts);
984 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $serverdata['nurl']]]);
985 while ($pcontact = DBA::fetch($pcontacts)) {
986 $contacts[$pcontact['nurl']] = $pcontact['url'];
988 DBA::close($pcontacts);
990 if (empty($contacts)) {
994 foreach ($contacts as $contact) {
995 $probed = Contact::getByURL($contact);
996 if (!empty($probed) && in_array($probed['network'], Protocol::FEDERATED)) {
997 $serverdata['network'] = $probed['network'];
1002 $serverdata['registered-users'] = max($serverdata['registered-users'], count($contacts));
1008 * Checks if the given server does have a '/poco' endpoint.
1009 * This is used for the 'PortableContact' functionality,
1010 * which is used by both Friendica and Hubzilla.
1012 * @param string $url URL of the given server
1013 * @param array $serverdata array with server data
1015 * @return array server data
1017 private static function checkPoCo(string $url, array $serverdata)
1019 $serverdata['poco'] = '';
1021 $curlResult = DI::httpRequest()->get($url . '/poco');
1022 if (!$curlResult->isSuccess()) {
1026 $data = json_decode($curlResult->getBody(), true);
1031 if (!empty($data['totalResults'])) {
1032 $registeredUsers = $serverdata['registered-users'] ?? 0;
1033 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers);
1034 $serverdata['directory-type'] = self::DT_POCO;
1035 $serverdata['poco'] = $url . '/poco';
1042 * Checks if the given server does have a Mastodon style directory endpoint.
1044 * @param string $url URL of the given server
1045 * @param array $serverdata array with server data
1047 * @return array server data
1049 public static function checkMastodonDirectory(string $url, array $serverdata)
1051 $curlResult = DI::httpRequest()->get($url . '/api/v1/directory?limit=1');
1052 if (!$curlResult->isSuccess()) {
1056 $data = json_decode($curlResult->getBody(), true);
1061 if (count($data) == 1) {
1062 $serverdata['directory-type'] = self::DT_MASTODON;
1069 * Detects the version number of a given server when it was a NextCloud installation
1071 * @param string $url URL of the given server
1072 * @param array $serverdata array with server data
1074 * @return array server data
1076 private static function detectNextcloud(string $url, array $serverdata)
1078 $curlResult = DI::httpRequest()->get($url . '/status.php');
1080 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1084 $data = json_decode($curlResult->getBody(), true);
1089 if (!empty($data['version'])) {
1090 $serverdata['platform'] = 'nextcloud';
1091 $serverdata['version'] = $data['version'];
1092 $serverdata['network'] = Protocol::ACTIVITYPUB;
1094 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1095 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1103 * Detects data from a given server url if it was a mastodon alike system
1105 * @param string $url URL of the given server
1106 * @param array $serverdata array with server data
1108 * @return array server data
1110 private static function detectMastodonAlikes(string $url, array $serverdata)
1112 $curlResult = DI::httpRequest()->get($url . '/api/v1/instance');
1114 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1118 $data = json_decode($curlResult->getBody(), true);
1123 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1124 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1127 if (!empty($data['version'])) {
1128 $serverdata['platform'] = 'mastodon';
1129 $serverdata['version'] = $data['version'] ?? '';
1130 $serverdata['network'] = Protocol::ACTIVITYPUB;
1133 if (!empty($data['title'])) {
1134 $serverdata['site_name'] = $data['title'];
1137 if (!empty($data['title']) && empty($serverdata['platform']) && empty($serverdata['network'])) {
1138 $serverdata['platform'] = 'mastodon';
1139 $serverdata['network'] = Protocol::ACTIVITYPUB;
1142 if (!empty($data['description'])) {
1143 $serverdata['info'] = trim($data['description']);
1146 if (!empty($data['stats']['user_count'])) {
1147 $serverdata['registered-users'] = $data['stats']['user_count'];
1150 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1151 $serverdata['platform'] = strtolower($matches[1]);
1152 $serverdata['version'] = $matches[2];
1155 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1156 $serverdata['platform'] = 'pleroma';
1157 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1160 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1161 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1162 $serverdata['platform'] = 'pleroma';
1169 * Detects data from typical Hubzilla endpoints
1171 * @param string $url URL of the given server
1172 * @param array $serverdata array with server data
1174 * @return array server data
1176 private static function detectHubzilla(string $url, array $serverdata)
1178 $curlResult = DI::httpRequest()->get($url . '/api/statusnet/config.json');
1179 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1183 $data = json_decode($curlResult->getBody(), true);
1184 if (empty($data) || empty($data['site'])) {
1188 if (!empty($data['site']['name'])) {
1189 $serverdata['site_name'] = $data['site']['name'];
1192 if (!empty($data['site']['platform'])) {
1193 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1194 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1195 $serverdata['network'] = Protocol::ZOT;
1198 if (!empty($data['site']['hubzilla'])) {
1199 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1200 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1201 $serverdata['network'] = Protocol::ZOT;
1204 if (!empty($data['site']['redmatrix'])) {
1205 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1206 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1207 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1208 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1211 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1212 $serverdata['network'] = Protocol::ZOT;
1216 $inviteonly = false;
1219 if (!empty($data['site']['closed'])) {
1220 $closed = self::toBoolean($data['site']['closed']);
1223 if (!empty($data['site']['private'])) {
1224 $private = self::toBoolean($data['site']['private']);
1227 if (!empty($data['site']['inviteonly'])) {
1228 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1231 if (!$closed && !$private and $inviteonly) {
1232 $serverdata['register_policy'] = Register::APPROVE;
1233 } elseif (!$closed && !$private) {
1234 $serverdata['register_policy'] = Register::OPEN;
1236 $serverdata['register_policy'] = Register::CLOSED;
1239 if (!empty($serverdata['network']) && in_array($serverdata['detection-method'],
1240 [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1241 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1248 * Converts input value to a boolean value
1250 * @param string|integer $val
1254 private static function toBoolean($val)
1256 if (($val == 'true') || ($val == 1)) {
1258 } elseif (($val == 'false') || ($val == 0)) {
1266 * Detect if the URL belongs to a GNU Social server
1268 * @param string $url URL of the given server
1269 * @param array $serverdata array with server data
1271 * @return array server data
1273 private static function detectGNUSocial(string $url, array $serverdata)
1275 // Test for GNU Social
1276 $curlResult = DI::httpRequest()->get($url . '/api/gnusocial/version.json');
1277 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1278 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1279 $serverdata['platform'] = 'gnusocial';
1280 // Remove junk that some GNU Social servers return
1281 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1282 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1283 $serverdata['version'] = trim($serverdata['version'], '"');
1284 $serverdata['network'] = Protocol::OSTATUS;
1286 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1287 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1293 // Test for Statusnet
1294 $curlResult = DI::httpRequest()->get($url . '/api/statusnet/version.json');
1295 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1296 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1298 // Remove junk that some GNU Social servers return
1299 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1300 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1301 $serverdata['version'] = trim($serverdata['version'], '"');
1303 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1304 $serverdata['platform'] = 'pleroma';
1305 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1306 $serverdata['network'] = Protocol::ACTIVITYPUB;
1308 $serverdata['platform'] = 'statusnet';
1309 $serverdata['network'] = Protocol::OSTATUS;
1312 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1313 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1321 * Detect if the URL belongs to a Friendica server
1323 * @param string $url URL of the given server
1324 * @param array $serverdata array with server data
1326 * @return array server data
1328 private static function detectFriendica(string $url, array $serverdata)
1330 $curlResult = DI::httpRequest()->get($url . '/friendica/json');
1331 if (!$curlResult->isSuccess()) {
1332 $curlResult = DI::httpRequest()->get($url . '/friendika/json');
1334 $platform = 'Friendika';
1337 $platform = 'Friendica';
1340 if (!$curlResult->isSuccess()) {
1344 $data = json_decode($curlResult->getBody(), true);
1345 if (empty($data) || empty($data['version'])) {
1349 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1350 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1353 $serverdata['network'] = Protocol::DFRN;
1354 $serverdata['version'] = $data['version'];
1356 if (!empty($data['no_scrape_url'])) {
1357 $serverdata['noscrape'] = $data['no_scrape_url'];
1360 if (!empty($data['site_name'])) {
1361 $serverdata['site_name'] = $data['site_name'];
1364 if (!empty($data['info'])) {
1365 $serverdata['info'] = trim($data['info']);
1368 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1369 switch ($register_policy) {
1370 case 'REGISTER_OPEN':
1371 $serverdata['register_policy'] = Register::OPEN;
1374 case 'REGISTER_APPROVE':
1375 $serverdata['register_policy'] = Register::APPROVE;
1378 case 'REGISTER_CLOSED':
1379 case 'REGISTER_INVITATION':
1380 $serverdata['register_policy'] = Register::CLOSED;
1383 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
1384 $serverdata['register_policy'] = Register::CLOSED;
1388 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
1394 * Analyses the landing page of a given server for hints about type and system of that server
1396 * @param object $curlResult result of curl execution
1397 * @param array $serverdata array with server data
1398 * @param string $url Server URL
1400 * @return array server data
1402 private static function analyseRootBody($curlResult, array $serverdata, string $url)
1404 $doc = new DOMDocument();
1405 @$doc->loadHTML($curlResult->getBody());
1406 $xpath = new DOMXPath($doc);
1408 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
1409 if (!empty($title)) {
1410 $serverdata['site_name'] = $title;
1413 $list = $xpath->query('//meta[@name]');
1415 foreach ($list as $node) {
1417 if ($node->attributes->length) {
1418 foreach ($node->attributes as $attribute) {
1419 $value = trim($attribute->value);
1420 if (empty($value)) {
1424 $attr[$attribute->name] = $value;
1427 if (empty($attr['name']) || empty($attr['content'])) {
1432 if ($attr['name'] == 'description') {
1433 $serverdata['info'] = $attr['content'];
1436 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
1437 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad'])) {
1438 $serverdata['platform'] = strtolower($attr['content']);
1439 if (in_array($attr['content'], ['Misskey', 'Write.as'])) {
1440 $serverdata['network'] = Protocol::ACTIVITYPUB;
1443 if (($attr['name'] == 'generator') && (empty($serverdata['platform']) || (substr(strtolower($attr['content']), 0, 9) == 'wordpress'))) {
1444 $serverdata['platform'] = strtolower($attr['content']);
1445 $version_part = explode(' ', $attr['content']);
1447 if (count($version_part) == 2) {
1448 if (in_array($version_part[0], ['WordPress'])) {
1449 $serverdata['platform'] = strtolower($version_part[0]);
1450 $serverdata['version'] = $version_part[1];
1452 // We still do need a reliable test if some AP plugin is activated
1453 if (DBA::exists('apcontact', ['baseurl' => $url])) {
1454 $serverdata['network'] = Protocol::ACTIVITYPUB;
1456 $serverdata['network'] = Protocol::FEED;
1459 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1460 $serverdata['detection-method'] = self::DETECT_BODY;
1463 if (in_array($version_part[0], ['Friendika', 'Friendica'])) {
1464 $serverdata['platform'] = strtolower($version_part[0]);
1465 $serverdata['version'] = $version_part[1];
1466 $serverdata['network'] = Protocol::DFRN;
1472 $list = $xpath->query('//meta[@property]');
1474 foreach ($list as $node) {
1476 if ($node->attributes->length) {
1477 foreach ($node->attributes as $attribute) {
1478 $value = trim($attribute->value);
1479 if (empty($value)) {
1483 $attr[$attribute->name] = $value;
1486 if (empty($attr['property']) || empty($attr['content'])) {
1491 if ($attr['property'] == 'og:site_name') {
1492 $serverdata['site_name'] = $attr['content'];
1495 if ($attr['property'] == 'og:description') {
1496 $serverdata['info'] = $attr['content'];
1499 if ($attr['property'] == 'og:platform') {
1500 $serverdata['platform'] = strtolower($attr['content']);
1502 if (in_array($attr['content'], ['PeerTube'])) {
1503 $serverdata['network'] = Protocol::ACTIVITYPUB;
1507 if ($attr['property'] == 'generator') {
1508 $serverdata['platform'] = strtolower($attr['content']);
1510 if (in_array($attr['content'], ['hubzilla'])) {
1511 // We later check which compatible protocol modules are loaded.
1512 $serverdata['network'] = Protocol::ZOT;
1517 if (!empty($serverdata['network']) && ($serverdata['detection-method'] == self::DETECT_MANUAL)) {
1518 $serverdata['detection-method'] = self::DETECT_BODY;
1525 * Analyses the header data of a given server for hints about type and system of that server
1527 * @param object $curlResult result of curl execution
1528 * @param array $serverdata array with server data
1530 * @return array server data
1532 private static function analyseRootHeader($curlResult, array $serverdata)
1534 if ($curlResult->getHeader('server') == 'Mastodon') {
1535 $serverdata['platform'] = 'mastodon';
1536 $serverdata['network'] = Protocol::ACTIVITYPUB;
1537 } elseif ($curlResult->inHeader('x-diaspora-version')) {
1538 $serverdata['platform'] = 'diaspora';
1539 $serverdata['network'] = Protocol::DIASPORA;
1540 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version');
1541 } elseif ($curlResult->inHeader('x-friendica-version')) {
1542 $serverdata['platform'] = 'friendica';
1543 $serverdata['network'] = Protocol::DFRN;
1544 $serverdata['version'] = $curlResult->getHeader('x-friendica-version');
1549 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1550 $serverdata['detection-method'] = self::DETECT_HEADER;
1557 * Test if the body contains valid content
1559 * @param string $body
1562 private static function invalidBody(string $body)
1564 // Currently we only test for a HTML element.
1565 // Possibly we enhance this in the future.
1566 return !strpos($body, '>');
1570 * Update GServer entries
1572 public static function discover()
1574 // Update the server list
1575 self::discoverFederation();
1579 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
1581 if ($requery_days == 0) {
1585 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
1587 $gservers = DBA::p("SELECT `id`, `url`, `nurl`, `network`, `poco`, `directory-type`
1590 AND `directory-type` != ?
1591 AND `last_poco_query` < ?
1592 ORDER BY RAND()", self::DT_NONE, $last_update
1595 while ($gserver = DBA::fetch($gservers)) {
1596 if (!GServer::check($gserver['url'], $gserver['network'])) {
1597 // The server is not reachable? Okay, then we will try it later
1598 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1599 DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);
1603 Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1604 Worker::add(PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
1606 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1607 Worker::add(PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
1609 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1610 DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);
1612 if (--$no_of_queries == 0) {
1617 DBA::close($gservers);
1621 * Discover federated servers
1623 private static function discoverFederation()
1625 $last = DI::config()->get('poco', 'last_federation_discovery');
1628 $next = $last + (24 * 60 * 60);
1630 if ($next > time()) {
1635 // Discover federated servers
1636 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
1637 foreach ($protocols as $protocol) {
1638 $query = '{nodes(protocol:"' . $protocol . '"){host}}';
1639 $curlResult = DI::httpRequest()->fetch('https://the-federation.info/graphql?query=' . urlencode($query));
1640 if (!empty($curlResult)) {
1641 $data = json_decode($curlResult, true);
1642 if (!empty($data['data']['nodes'])) {
1643 foreach ($data['data']['nodes'] as $server) {
1644 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
1645 Worker::add(PRIORITY_LOW, 'UpdateGServer', 'https://' . $server['host'], true);
1651 // Disvover Mastodon servers
1652 $accesstoken = DI::config()->get('system', 'instances_social_key');
1654 if (!empty($accesstoken)) {
1655 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1656 $header = ['Authorization: Bearer '.$accesstoken];
1657 $curlResult = DI::httpRequest()->get($api, ['header' => $header]);
1659 if ($curlResult->isSuccess()) {
1660 $servers = json_decode($curlResult->getBody(), true);
1662 foreach ($servers['instances'] as $server) {
1663 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
1664 Worker::add(PRIORITY_LOW, 'UpdateGServer', $url);
1669 DI::config()->set('poco', 'last_federation_discovery', time());