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\DBA;
32 use Friendica\Module\Register;
33 use Friendica\Network\CurlResult;
34 use Friendica\Protocol\Relay;
35 use Friendica\Util\DateTimeFormat;
36 use Friendica\Util\Network;
37 use Friendica\Util\Strings;
38 use Friendica\Util\XML;
41 * This class handles GServer related functions
48 const DT_MASTODON = 2;
50 // Methods to detect server types
52 // Non endpoint specific methods
53 const DETECT_MANUAL = 0;
54 const DETECT_HEADER = 1;
55 const DETECT_BODY = 2;
57 // Implementation specific endpoints
58 const DETECT_FRIENDIKA = 10;
59 const DETECT_FRIENDICA = 11;
60 const DETECT_STATUSNET = 12;
61 const DETECT_GNUSOCIAL = 13;
62 const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix
63 const DETECT_SITEINFO_JSON = 15; // Newer Hubzilla
64 const DETECT_MASTODON_API = 16;
65 const DETECT_STATUS_PHP = 17; // Nextcloud
67 // Standardized endpoints
68 const DETECT_STATISTICS_JSON = 100;
69 const DETECT_NODEINFO_1 = 101;
70 const DETECT_NODEINFO_2 = 102;
73 * Get the ID for the given server URL
76 * @param boolean $no_check Don't check if the server hadn't been found
77 * @return int gserver id
79 public static function getID(string $url, bool $no_check = false)
85 $url = self::cleanURL($url);
87 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
88 if (DBA::isResult($gserver)) {
89 Logger::info('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
90 return $gserver['id'];
93 if ($no_check || !self::check($url)) {
97 return self::getID($url, true);
101 * Checks if the given server is reachable
103 * @param string $profile URL of the given profile
104 * @param string $server URL of the given server (If empty, taken from profile)
105 * @param string $network Network value that is used, when detection failed
106 * @param boolean $force Force an update.
108 * @return boolean 'true' if server seems vital
110 public static function reachable(string $profile, string $server = '', string $network = '', bool $force = false)
113 $contact = Contact::getByURL($profile, null, ['baseurl']);
114 if (!empty($contact['baseurl'])) {
115 $server = $contact['baseurl'];
123 return self::check($server, $network, $force);
127 * Decides if a server needs to be updated, based upon several date fields
129 * @param date $created Creation date of that server entry
130 * @param date $updated When had the server entry be updated
131 * @param date $last_failure Last failure when contacting that server
132 * @param date $last_contact Last time the server had been contacted
134 * @return boolean Does the server record needs an update?
136 public static function updateNeeded($created, $updated, $last_failure, $last_contact)
138 $now = strtotime(DateTimeFormat::utcNow());
140 if ($updated > $last_contact) {
141 $contact_time = strtotime($updated);
143 $contact_time = strtotime($last_contact);
146 $failure_time = strtotime($last_failure);
147 $created_time = strtotime($created);
149 // If there is no "created" time then use the current time
150 if ($created_time <= 0) {
151 $created_time = $now;
154 // If the last contact was less than 24 hours then don't update
155 if (($now - $contact_time) < (60 * 60 * 24)) {
159 // If the last failure was less than 24 hours then don't update
160 if (($now - $failure_time) < (60 * 60 * 24)) {
164 // If the last contact was less than a week ago and the last failure is older than a week then don't update
165 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) && ($contact_time > $failure_time))
168 // 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
169 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) && (($now - $created_time) > (60 * 60 * 24 * 7)) && (($now - $failure_time) < (60 * 60 * 24 * 7))) {
173 // 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
174 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) && (($now - $created_time) > (60 * 60 * 24 * 30)) && (($now - $failure_time) < (60 * 60 * 24 * 30))) {
182 * Checks the state of the given server.
184 * @param string $server_url URL of the given server
185 * @param string $network Network value that is used, when detection failed
186 * @param boolean $force Force an update.
187 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
189 * @return boolean 'true' if server seems vital
191 public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false)
193 $server_url = self::cleanURL($server_url);
195 if ($server_url == '') {
199 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
200 if (DBA::isResult($gserver)) {
201 if ($gserver['created'] <= DBA::NULL_DATETIME) {
202 $fields = ['created' => DateTimeFormat::utcNow()];
203 $condition = ['nurl' => Strings::normaliseLink($server_url)];
204 DBA::update('gserver', $fields, $condition);
207 $last_contact = $gserver['last_contact'];
208 $last_failure = $gserver['last_failure'];
210 // See discussion under https://forum.friendi.ca/display/0b6b25a8135aabc37a5a0f5684081633
211 // It can happen that a zero date is in the database, but storing it again is forbidden.
212 if ($last_contact < DBA::NULL_DATETIME) {
213 $last_contact = DBA::NULL_DATETIME;
216 if ($last_failure < DBA::NULL_DATETIME) {
217 $last_failure = DBA::NULL_DATETIME;
220 if (!$force && !self::updateNeeded($gserver['created'], '', $last_failure, $last_contact)) {
221 Logger::info('No update needed', ['server' => $server_url]);
222 return ($last_contact >= $last_failure);
224 Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force, 'Created' => $gserver['created'], 'Failure' => $last_failure, 'Contact' => $last_contact]);
226 Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
229 return self::detect($server_url, $network, $only_nodeinfo);
233 * Set failed server status
237 private static function setFailure(string $url)
239 if (DBA::exists('gserver', ['nurl' => Strings::normaliseLink($url)])) {
240 DBA::update('gserver', ['failed' => true, 'last_failure' => DateTimeFormat::utcNow(), 'detection-method' => null],
241 ['nurl' => Strings::normaliseLink($url)]);
242 Logger::info('Set failed status for existing server', ['url' => $url]);
245 DBA::insert('gserver', ['url' => $url, 'nurl' => Strings::normaliseLink($url),
246 'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
247 'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
248 Logger::info('Set failed status for new server', ['url' => $url]);
252 * Remove unwanted content from the given URL
255 * @return string cleaned URL
257 public static function cleanURL(string $url)
259 $url = trim($url, '/');
260 $url = str_replace('/index.php', '', $url);
262 $urlparts = parse_url($url);
263 unset($urlparts['user']);
264 unset($urlparts['pass']);
265 unset($urlparts['query']);
266 unset($urlparts['fragment']);
267 return Network::unparseURL($urlparts);
271 * Return the base URL
274 * @return string base URL
276 private static function getBaseURL(string $url)
278 $urlparts = parse_url(self::cleanURL($url));
279 unset($urlparts['path']);
280 return Network::unparseURL($urlparts);
284 * Detect server data (type, protocol, version number, ...)
285 * The detected data is then updated or inserted in the gserver table.
287 * @param string $url URL of the given server
288 * @param string $network Network value that is used, when detection failed
289 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
291 * @return boolean 'true' if server could be detected
293 public static function detect(string $url, string $network = '', bool $only_nodeinfo = false)
295 Logger::info('Detect server type', ['server' => $url]);
296 $serverdata = ['detection-method' => self::DETECT_MANUAL];
298 $original_url = $url;
300 // Remove URL content that is not supposed to exist for a server url
301 $url = self::cleanURL($url);
304 $baseurl = self::getBaseURL($url);
306 // If the URL missmatches, then we mark the old entry as failure
307 if ($url != $original_url) {
308 DBA::update('gserver', ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()],
309 ['nurl' => Strings::normaliseLink($original_url)]);
312 // When a nodeinfo is present, we don't need to dig further
313 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
314 $curlResult = DI::httpRequest()->get($url . '/.well-known/nodeinfo', ['timeout' => $xrd_timeout]);
315 if ($curlResult->isTimeout()) {
316 self::setFailure($url);
320 $nodeinfo = self::fetchNodeinfo($url, $curlResult);
321 if ($only_nodeinfo && empty($nodeinfo)) {
322 Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
323 self::setFailure($url);
327 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
328 if (empty($nodeinfo)) {
329 $nodeinfo = self::fetchStatistics($url);
332 // If that didn't work out well, we use some protocol specific endpoints
333 // For Friendica and Zot based networks we have to dive deeper to reveal more details
334 if (empty($nodeinfo['network']) || in_array($nodeinfo['network'], [Protocol::DFRN, Protocol::ZOT])) {
335 if (!empty($nodeinfo['detection-method'])) {
336 $serverdata['detection-method'] = $nodeinfo['detection-method'];
339 // Fetch the landing page, possibly it reveals some data
340 if (empty($nodeinfo['network'])) {
341 if ($baseurl == $url) {
342 $basedata = $serverdata;
344 $basedata = ['detection-method' => self::DETECT_MANUAL];
347 $curlResult = DI::httpRequest()->get($baseurl, ['timeout' => $xrd_timeout]);
348 if ($curlResult->isSuccess()) {
349 $basedata = self::analyseRootHeader($curlResult, $basedata);
350 $basedata = self::analyseRootBody($curlResult, $basedata, $baseurl);
353 if (!$curlResult->isSuccess() || empty($curlResult->getBody()) || self::invalidBody($curlResult->getBody())) {
354 self::setFailure($url);
358 if ($baseurl == $url) {
359 $serverdata = $basedata;
361 // When the base path doesn't seem to contain a social network we try the complete path.
362 // Most detectable system have to be installed in the root directory.
363 // We checked the base to avoid false positives.
364 $curlResult = DI::httpRequest()->get($url, ['timeout' => $xrd_timeout]);
365 if ($curlResult->isSuccess()) {
366 $urldata = self::analyseRootHeader($curlResult, $serverdata);
367 $urldata = self::analyseRootBody($curlResult, $urldata, $url);
369 $comparebase = $basedata;
370 unset($comparebase['info']);
371 unset($comparebase['site_name']);
372 $compareurl = $urldata;
373 unset($compareurl['info']);
374 unset($compareurl['site_name']);
376 // We assume that no one will install the identical system in the root and a subfolder
377 if (!empty(array_diff($comparebase, $compareurl))) {
378 $serverdata = $urldata;
384 if (empty($serverdata['network']) || ($serverdata['network'] == Protocol::ACTIVITYPUB)) {
385 $serverdata = self::detectMastodonAlikes($url, $serverdata);
388 // All following checks are done for systems that always have got a "host-meta" endpoint.
389 // With this check we don't have to waste time and ressources for dead systems.
390 // Also this hopefully prevents us from receiving abuse messages.
391 if (empty($serverdata['network']) && !self::validHostMeta($url)) {
392 self::setFailure($url);
396 if (empty($serverdata['network']) || in_array($serverdata['network'], [Protocol::DFRN, Protocol::ACTIVITYPUB])) {
397 $serverdata = self::detectFriendica($url, $serverdata);
400 // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
401 if (empty($serverdata['network']) || ($serverdata['network'] == Protocol::ZOT)) {
402 $serverdata = self::fetchSiteinfo($url, $serverdata);
405 // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations
406 if (empty($serverdata['network'])) {
407 $serverdata = self::detectHubzilla($url, $serverdata);
410 if (empty($serverdata['network'])) {
411 $serverdata = self::detectNextcloud($url, $serverdata);
414 if (empty($serverdata['network'])) {
415 $serverdata = self::detectGNUSocial($url, $serverdata);
418 $serverdata = array_merge($nodeinfo, $serverdata);
420 $serverdata = $nodeinfo;
423 // Detect the directory type
424 $serverdata['directory-type'] = self::DT_NONE;
425 $serverdata = self::checkPoCo($url, $serverdata);
426 $serverdata = self::checkMastodonDirectory($url, $serverdata);
428 // We can't detect the network type. Possibly it is some system that we don't know yet
429 if (empty($serverdata['network'])) {
430 $serverdata['network'] = Protocol::PHANTOM;
433 // When we hadn't been able to detect the network type, we use the hint from the parameter
434 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
435 $serverdata['network'] = $network;
438 $serverdata['url'] = $url;
439 $serverdata['nurl'] = Strings::normaliseLink($url);
441 // We take the highest number that we do find
442 $registeredUsers = $serverdata['registered-users'] ?? 0;
444 // On an active server there has to be at least a single user
445 if (($serverdata['network'] != Protocol::PHANTOM) && ($registeredUsers == 0)) {
446 $registeredUsers = 1;
449 if ($serverdata['network'] == Protocol::PHANTOM) {
450 $serverdata['registered-users'] = $registeredUsers;
451 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
454 $serverdata['last_contact'] = DateTimeFormat::utcNow();
455 $serverdata['failed'] = false;
457 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
458 if (!DBA::isResult($gserver)) {
459 $serverdata['created'] = DateTimeFormat::utcNow();
460 $ret = DBA::insert('gserver', $serverdata);
461 $id = DBA::lastInsertId();
463 // Don't override the network with 'unknown' when there had been a valid entry before
464 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($gserver['network'])) {
465 unset($serverdata['network']);
468 $ret = DBA::update('gserver', $serverdata, ['nurl' => $serverdata['nurl']]);
469 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
470 if (DBA::isResult($gserver)) {
471 $id = $gserver['id'];
475 if (!empty($serverdata['network']) && !empty($id) && ($serverdata['network'] != Protocol::PHANTOM)) {
476 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
477 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id]);
478 $max_users = max($apcontacts, $contacts, $registeredUsers);
479 if ($max_users > $registeredUsers) {
480 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
481 DBA::update('gserver', ['registered-users' => $max_users], ['id' => $id]);
485 if (!empty($serverdata['network']) && in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
486 self::discoverRelay($url);
493 * Fetch relay data from a given server url
495 * @param string $server_url address of the server
496 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
498 private static function discoverRelay(string $server_url)
500 Logger::info('Discover relay data', ['server' => $server_url]);
502 $curlResult = DI::httpRequest()->get($server_url . '/.well-known/x-social-relay');
503 if (!$curlResult->isSuccess()) {
507 $data = json_decode($curlResult->getBody(), true);
508 if (!is_array($data)) {
512 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
513 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
515 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
517 $data['subscribe'] = false;
521 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
522 if (!DBA::isResult($gserver)) {
526 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
527 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
528 DBA::update('gserver', $fields, ['id' => $gserver['id']]);
531 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
533 if ($data['scope'] == 'tags') {
536 foreach ($data['tags'] as $tag) {
537 $tag = mb_strtolower($tag);
538 if (strlen($tag) < 100) {
543 foreach ($tags as $tag) {
544 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], true);
548 // Create or update the relay contact
550 if (isset($data['protocols'])) {
551 if (isset($data['protocols']['diaspora'])) {
552 $fields['network'] = Protocol::DIASPORA;
554 if (isset($data['protocols']['diaspora']['receive'])) {
555 $fields['batch'] = $data['protocols']['diaspora']['receive'];
556 } elseif (is_string($data['protocols']['diaspora'])) {
557 $fields['batch'] = $data['protocols']['diaspora'];
561 if (isset($data['protocols']['dfrn'])) {
562 $fields['network'] = Protocol::DFRN;
564 if (isset($data['protocols']['dfrn']['receive'])) {
565 $fields['batch'] = $data['protocols']['dfrn']['receive'];
566 } elseif (is_string($data['protocols']['dfrn'])) {
567 $fields['batch'] = $data['protocols']['dfrn'];
571 if (isset($data['protocols']['activitypub'])) {
572 $fields['network'] = Protocol::ACTIVITYPUB;
574 if (!empty($data['protocols']['activitypub']['actor'])) {
575 $fields['url'] = $data['protocols']['activitypub']['actor'];
577 if (!empty($data['protocols']['activitypub']['receive'])) {
578 $fields['batch'] = $data['protocols']['activitypub']['receive'];
583 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
585 Relay::updateContact($gserver, $fields);
589 * Fetch server data from '/statistics.json' on the given server
591 * @param string $url URL of the given server
593 * @return array server data
595 private static function fetchStatistics(string $url)
597 $curlResult = DI::httpRequest()->get($url . '/statistics.json');
598 if (!$curlResult->isSuccess()) {
602 $data = json_decode($curlResult->getBody(), true);
607 $serverdata = ['detection-method' => self::DETECT_STATISTICS_JSON];
609 if (!empty($data['version'])) {
610 $serverdata['version'] = $data['version'];
611 // Version numbers on statistics.json are presented with additional info, e.g.:
612 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
613 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
616 if (!empty($data['name'])) {
617 $serverdata['site_name'] = $data['name'];
620 if (!empty($data['network'])) {
621 $serverdata['platform'] = strtolower($data['network']);
623 if ($serverdata['platform'] == 'diaspora') {
624 $serverdata['network'] = Protocol::DIASPORA;
625 } elseif ($serverdata['platform'] == 'friendica') {
626 $serverdata['network'] = Protocol::DFRN;
627 } elseif ($serverdata['platform'] == 'hubzilla') {
628 $serverdata['network'] = Protocol::ZOT;
629 } elseif ($serverdata['platform'] == 'redmatrix') {
630 $serverdata['network'] = Protocol::ZOT;
635 if (!empty($data['registrations_open'])) {
636 $serverdata['register_policy'] = Register::OPEN;
638 $serverdata['register_policy'] = Register::CLOSED;
645 * Detect server type by using the nodeinfo data
647 * @param string $url address of the server
648 * @param CurlResult $curlResult
649 * @return array Server data
650 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
652 private static function fetchNodeinfo(string $url, CurlResult $curlResult)
654 if (!$curlResult->isSuccess()) {
658 $nodeinfo = json_decode($curlResult->getBody(), true);
660 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
667 foreach ($nodeinfo['links'] as $link) {
668 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
669 Logger::info('Invalid nodeinfo format', ['url' => $url]);
672 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
673 $nodeinfo1_url = $link['href'];
674 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
675 $nodeinfo2_url = $link['href'];
679 if ($nodeinfo1_url . $nodeinfo2_url == '') {
685 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
686 if (!empty($nodeinfo2_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
687 $server = self::parseNodeinfo2($nodeinfo2_url);
690 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
691 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
692 $server = self::parseNodeinfo1($nodeinfo1_url);
701 * @param string $nodeinfo_url address of the nodeinfo path
702 * @return array Server data
703 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
705 private static function parseNodeinfo1(string $nodeinfo_url)
707 $curlResult = DI::httpRequest()->get($nodeinfo_url);
709 if (!$curlResult->isSuccess()) {
713 $nodeinfo = json_decode($curlResult->getBody(), true);
715 if (!is_array($nodeinfo)) {
719 $server = ['detection-method' => self::DETECT_NODEINFO_1,
720 'register_policy' => Register::CLOSED];
722 if (!empty($nodeinfo['openRegistrations'])) {
723 $server['register_policy'] = Register::OPEN;
726 if (is_array($nodeinfo['software'])) {
727 if (!empty($nodeinfo['software']['name'])) {
728 $server['platform'] = strtolower($nodeinfo['software']['name']);
731 if (!empty($nodeinfo['software']['version'])) {
732 $server['version'] = $nodeinfo['software']['version'];
733 // Version numbers on Nodeinfo are presented with additional info, e.g.:
734 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
735 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
739 if (!empty($nodeinfo['metadata']['nodeName'])) {
740 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
743 if (!empty($nodeinfo['usage']['users']['total'])) {
744 $server['registered-users'] = $nodeinfo['usage']['users']['total'];
747 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
749 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
750 $protocols[$protocol] = true;
753 if (!empty($protocols['friendica'])) {
754 $server['network'] = Protocol::DFRN;
755 } elseif (!empty($protocols['activitypub'])) {
756 $server['network'] = Protocol::ACTIVITYPUB;
757 } elseif (!empty($protocols['diaspora'])) {
758 $server['network'] = Protocol::DIASPORA;
759 } elseif (!empty($protocols['ostatus'])) {
760 $server['network'] = Protocol::OSTATUS;
761 } elseif (!empty($protocols['gnusocial'])) {
762 $server['network'] = Protocol::OSTATUS;
763 } elseif (!empty($protocols['zot'])) {
764 $server['network'] = Protocol::ZOT;
768 if (empty($server)) {
778 * @param string $nodeinfo_url address of the nodeinfo path
779 * @return array Server data
780 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
782 private static function parseNodeinfo2(string $nodeinfo_url)
784 $curlResult = DI::httpRequest()->get($nodeinfo_url);
785 if (!$curlResult->isSuccess()) {
789 $nodeinfo = json_decode($curlResult->getBody(), true);
791 if (!is_array($nodeinfo)) {
795 $server = ['detection-method' => self::DETECT_NODEINFO_2,
796 'register_policy' => Register::CLOSED];
798 if (!empty($nodeinfo['openRegistrations'])) {
799 $server['register_policy'] = Register::OPEN;
802 if (is_array($nodeinfo['software'])) {
803 if (!empty($nodeinfo['software']['name'])) {
804 $server['platform'] = strtolower($nodeinfo['software']['name']);
807 if (!empty($nodeinfo['software']['version'])) {
808 $server['version'] = $nodeinfo['software']['version'];
809 // Version numbers on Nodeinfo are presented with additional info, e.g.:
810 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
811 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
815 if (!empty($nodeinfo['metadata']['nodeName'])) {
816 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
819 if (!empty($nodeinfo['usage']['users']['total'])) {
820 $server['registered-users'] = $nodeinfo['usage']['users']['total'];
823 if (!empty($nodeinfo['protocols'])) {
825 foreach ($nodeinfo['protocols'] as $protocol) {
826 $protocols[$protocol] = true;
829 if (!empty($protocols['dfrn'])) {
830 $server['network'] = Protocol::DFRN;
831 } elseif (!empty($protocols['activitypub'])) {
832 $server['network'] = Protocol::ACTIVITYPUB;
833 } elseif (!empty($protocols['diaspora'])) {
834 $server['network'] = Protocol::DIASPORA;
835 } elseif (!empty($protocols['ostatus'])) {
836 $server['network'] = Protocol::OSTATUS;
837 } elseif (!empty($protocols['gnusocial'])) {
838 $server['network'] = Protocol::OSTATUS;
839 } elseif (!empty($protocols['zot'])) {
840 $server['network'] = Protocol::ZOT;
844 if (empty($server)) {
852 * Fetch server information from a 'siteinfo.json' file on the given server
854 * @param string $url URL of the given server
855 * @param array $serverdata array with server data
857 * @return array server data
859 private static function fetchSiteinfo(string $url, array $serverdata)
861 $curlResult = DI::httpRequest()->get($url . '/siteinfo.json');
862 if (!$curlResult->isSuccess()) {
866 $data = json_decode($curlResult->getBody(), true);
871 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
872 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
875 if (!empty($data['url'])) {
876 $serverdata['platform'] = strtolower($data['platform']);
877 $serverdata['version'] = $data['version'];
880 if (!empty($data['plugins'])) {
881 if (in_array('pubcrawl', $data['plugins'])) {
882 $serverdata['network'] = Protocol::ACTIVITYPUB;
883 } elseif (in_array('diaspora', $data['plugins'])) {
884 $serverdata['network'] = Protocol::DIASPORA;
885 } elseif (in_array('gnusoc', $data['plugins'])) {
886 $serverdata['network'] = Protocol::OSTATUS;
888 $serverdata['network'] = Protocol::ZOT;
892 if (!empty($data['site_name'])) {
893 $serverdata['site_name'] = $data['site_name'];
896 if (!empty($data['channels_total'])) {
897 $serverdata['registered-users'] = $data['channels_total'];
900 if (!empty($data['register_policy'])) {
901 switch ($data['register_policy']) {
902 case 'REGISTER_OPEN':
903 $serverdata['register_policy'] = Register::OPEN;
906 case 'REGISTER_APPROVE':
907 $serverdata['register_policy'] = Register::APPROVE;
910 case 'REGISTER_CLOSED':
912 $serverdata['register_policy'] = Register::CLOSED;
921 * Checks if the server contains a valid host meta file
923 * @param string $url URL of the given server
925 * @return boolean 'true' if the server seems to be vital
927 private static function validHostMeta(string $url)
929 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
930 $curlResult = DI::httpRequest()->get($url . '/.well-known/host-meta', ['timeout' => $xrd_timeout]);
931 if (!$curlResult->isSuccess()) {
935 $xrd = XML::parseString($curlResult->getBody());
936 if (!is_object($xrd)) {
940 $elements = XML::elementToArray($xrd);
941 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
946 foreach ($elements['xrd']['link'] as $link) {
947 // When there is more than a single "link" element, the array looks slightly different
948 if (!empty($link['@attributes'])) {
949 $link = $link['@attributes'];
952 if (empty($link['rel']) || empty($link['template'])) {
956 if ($link['rel'] == 'lrdd') {
957 // When the webfinger host is the same like the system host, it should be ok.
958 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
966 * Detect the network of the given server via their known contacts
968 * @param string $url URL of the given server
969 * @param array $serverdata array with server data
971 * @return array server data
973 private static function detectNetworkViaContacts(string $url, array $serverdata)
977 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $serverdata['nurl']]]);
978 while ($apcontact = DBA::fetch($apcontacts)) {
979 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
981 DBA::close($apcontacts);
983 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $serverdata['nurl']]]);
984 while ($pcontact = DBA::fetch($pcontacts)) {
985 $contacts[$pcontact['nurl']] = $pcontact['url'];
987 DBA::close($pcontacts);
989 if (empty($contacts)) {
993 foreach ($contacts as $contact) {
994 $probed = Contact::getByURL($contact);
995 if (!empty($probed) && in_array($probed['network'], Protocol::FEDERATED)) {
996 $serverdata['network'] = $probed['network'];
1001 $serverdata['registered-users'] = max($serverdata['registered-users'], count($contacts));
1007 * Checks if the given server does have a '/poco' endpoint.
1008 * This is used for the 'PortableContact' functionality,
1009 * which is used by both Friendica and Hubzilla.
1011 * @param string $url URL of the given server
1012 * @param array $serverdata array with server data
1014 * @return array server data
1016 private static function checkPoCo(string $url, array $serverdata)
1018 $serverdata['poco'] = '';
1020 $curlResult = DI::httpRequest()->get($url . '/poco');
1021 if (!$curlResult->isSuccess()) {
1025 $data = json_decode($curlResult->getBody(), true);
1030 if (!empty($data['totalResults'])) {
1031 $registeredUsers = $serverdata['registered-users'] ?? 0;
1032 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers);
1033 $serverdata['directory-type'] = self::DT_POCO;
1034 $serverdata['poco'] = $url . '/poco';
1041 * Checks if the given server does have a Mastodon style directory endpoint.
1043 * @param string $url URL of the given server
1044 * @param array $serverdata array with server data
1046 * @return array server data
1048 public static function checkMastodonDirectory(string $url, array $serverdata)
1050 $curlResult = DI::httpRequest()->get($url . '/api/v1/directory?limit=1');
1051 if (!$curlResult->isSuccess()) {
1055 $data = json_decode($curlResult->getBody(), true);
1060 if (count($data) == 1) {
1061 $serverdata['directory-type'] = self::DT_MASTODON;
1068 * Detects the version number of a given server when it was a NextCloud installation
1070 * @param string $url URL of the given server
1071 * @param array $serverdata array with server data
1073 * @return array server data
1075 private static function detectNextcloud(string $url, array $serverdata)
1077 $curlResult = DI::httpRequest()->get($url . '/status.php');
1079 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1083 $data = json_decode($curlResult->getBody(), true);
1088 if (!empty($data['version'])) {
1089 $serverdata['platform'] = 'nextcloud';
1090 $serverdata['version'] = $data['version'];
1091 $serverdata['network'] = Protocol::ACTIVITYPUB;
1093 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1094 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1102 * Detects data from a given server url if it was a mastodon alike system
1104 * @param string $url URL of the given server
1105 * @param array $serverdata array with server data
1107 * @return array server data
1109 private static function detectMastodonAlikes(string $url, array $serverdata)
1111 $curlResult = DI::httpRequest()->get($url . '/api/v1/instance');
1113 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1117 $data = json_decode($curlResult->getBody(), true);
1122 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1123 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1126 if (!empty($data['version'])) {
1127 $serverdata['platform'] = 'mastodon';
1128 $serverdata['version'] = $data['version'] ?? '';
1129 $serverdata['network'] = Protocol::ACTIVITYPUB;
1132 if (!empty($data['title'])) {
1133 $serverdata['site_name'] = $data['title'];
1136 if (!empty($data['title']) && empty($serverdata['platform']) && empty($serverdata['network'])) {
1137 $serverdata['platform'] = 'mastodon';
1138 $serverdata['network'] = Protocol::ACTIVITYPUB;
1141 if (!empty($data['description'])) {
1142 $serverdata['info'] = trim($data['description']);
1145 if (!empty($data['stats']['user_count'])) {
1146 $serverdata['registered-users'] = $data['stats']['user_count'];
1149 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1150 $serverdata['platform'] = strtolower($matches[1]);
1151 $serverdata['version'] = $matches[2];
1154 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1155 $serverdata['platform'] = 'pleroma';
1156 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1159 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1160 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1161 $serverdata['platform'] = 'pleroma';
1168 * Detects data from typical Hubzilla endpoints
1170 * @param string $url URL of the given server
1171 * @param array $serverdata array with server data
1173 * @return array server data
1175 private static function detectHubzilla(string $url, array $serverdata)
1177 $curlResult = DI::httpRequest()->get($url . '/api/statusnet/config.json');
1178 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1182 $data = json_decode($curlResult->getBody(), true);
1183 if (empty($data) || empty($data['site'])) {
1187 if (!empty($data['site']['name'])) {
1188 $serverdata['site_name'] = $data['site']['name'];
1191 if (!empty($data['site']['platform'])) {
1192 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1193 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1194 $serverdata['network'] = Protocol::ZOT;
1197 if (!empty($data['site']['hubzilla'])) {
1198 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1199 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1200 $serverdata['network'] = Protocol::ZOT;
1203 if (!empty($data['site']['redmatrix'])) {
1204 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1205 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1206 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1207 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1210 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1211 $serverdata['network'] = Protocol::ZOT;
1215 $inviteonly = false;
1218 if (!empty($data['site']['closed'])) {
1219 $closed = self::toBoolean($data['site']['closed']);
1222 if (!empty($data['site']['private'])) {
1223 $private = self::toBoolean($data['site']['private']);
1226 if (!empty($data['site']['inviteonly'])) {
1227 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1230 if (!$closed && !$private and $inviteonly) {
1231 $serverdata['register_policy'] = Register::APPROVE;
1232 } elseif (!$closed && !$private) {
1233 $serverdata['register_policy'] = Register::OPEN;
1235 $serverdata['register_policy'] = Register::CLOSED;
1238 if (!empty($serverdata['network']) && in_array($serverdata['detection-method'],
1239 [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1240 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1247 * Converts input value to a boolean value
1249 * @param string|integer $val
1253 private static function toBoolean($val)
1255 if (($val == 'true') || ($val == 1)) {
1257 } elseif (($val == 'false') || ($val == 0)) {
1265 * Detect if the URL belongs to a GNU Social server
1267 * @param string $url URL of the given server
1268 * @param array $serverdata array with server data
1270 * @return array server data
1272 private static function detectGNUSocial(string $url, array $serverdata)
1274 // Test for GNU Social
1275 $curlResult = DI::httpRequest()->get($url . '/api/gnusocial/version.json');
1276 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1277 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1278 $serverdata['platform'] = 'gnusocial';
1279 // Remove junk that some GNU Social servers return
1280 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1281 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1282 $serverdata['version'] = trim($serverdata['version'], '"');
1283 $serverdata['network'] = Protocol::OSTATUS;
1285 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1286 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1292 // Test for Statusnet
1293 $curlResult = DI::httpRequest()->get($url . '/api/statusnet/version.json');
1294 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1295 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1297 // Remove junk that some GNU Social servers return
1298 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1299 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1300 $serverdata['version'] = trim($serverdata['version'], '"');
1302 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1303 $serverdata['platform'] = 'pleroma';
1304 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1305 $serverdata['network'] = Protocol::ACTIVITYPUB;
1307 $serverdata['platform'] = 'statusnet';
1308 $serverdata['network'] = Protocol::OSTATUS;
1311 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1312 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1320 * Detect if the URL belongs to a Friendica server
1322 * @param string $url URL of the given server
1323 * @param array $serverdata array with server data
1325 * @return array server data
1327 private static function detectFriendica(string $url, array $serverdata)
1329 $curlResult = DI::httpRequest()->get($url . '/friendica/json');
1330 if (!$curlResult->isSuccess()) {
1331 $curlResult = DI::httpRequest()->get($url . '/friendika/json');
1333 $platform = 'Friendika';
1336 $platform = 'Friendica';
1339 if (!$curlResult->isSuccess()) {
1343 $data = json_decode($curlResult->getBody(), true);
1344 if (empty($data) || empty($data['version'])) {
1348 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1349 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1352 $serverdata['network'] = Protocol::DFRN;
1353 $serverdata['version'] = $data['version'];
1355 if (!empty($data['no_scrape_url'])) {
1356 $serverdata['noscrape'] = $data['no_scrape_url'];
1359 if (!empty($data['site_name'])) {
1360 $serverdata['site_name'] = $data['site_name'];
1363 if (!empty($data['info'])) {
1364 $serverdata['info'] = trim($data['info']);
1367 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1368 switch ($register_policy) {
1369 case 'REGISTER_OPEN':
1370 $serverdata['register_policy'] = Register::OPEN;
1373 case 'REGISTER_APPROVE':
1374 $serverdata['register_policy'] = Register::APPROVE;
1377 case 'REGISTER_CLOSED':
1378 case 'REGISTER_INVITATION':
1379 $serverdata['register_policy'] = Register::CLOSED;
1382 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
1383 $serverdata['register_policy'] = Register::CLOSED;
1387 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
1393 * Analyses the landing page of a given server for hints about type and system of that server
1395 * @param object $curlResult result of curl execution
1396 * @param array $serverdata array with server data
1397 * @param string $url Server URL
1399 * @return array server data
1401 private static function analyseRootBody($curlResult, array $serverdata, string $url)
1403 $doc = new DOMDocument();
1404 @$doc->loadHTML($curlResult->getBody());
1405 $xpath = new DOMXPath($doc);
1407 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
1408 if (!empty($title)) {
1409 $serverdata['site_name'] = $title;
1412 $list = $xpath->query('//meta[@name]');
1414 foreach ($list as $node) {
1416 if ($node->attributes->length) {
1417 foreach ($node->attributes as $attribute) {
1418 $value = trim($attribute->value);
1419 if (empty($value)) {
1423 $attr[$attribute->name] = $value;
1426 if (empty($attr['name']) || empty($attr['content'])) {
1431 if ($attr['name'] == 'description') {
1432 $serverdata['info'] = $attr['content'];
1435 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
1436 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad'])) {
1437 $serverdata['platform'] = strtolower($attr['content']);
1438 if (in_array($attr['content'], ['Misskey', 'Write.as'])) {
1439 $serverdata['network'] = Protocol::ACTIVITYPUB;
1442 if (($attr['name'] == 'generator') && (empty($serverdata['platform']) || (substr(strtolower($attr['content']), 0, 9) == 'wordpress'))) {
1443 $serverdata['platform'] = strtolower($attr['content']);
1444 $version_part = explode(' ', $attr['content']);
1446 if (count($version_part) == 2) {
1447 if (in_array($version_part[0], ['WordPress'])) {
1448 $serverdata['platform'] = strtolower($version_part[0]);
1449 $serverdata['version'] = $version_part[1];
1451 // We still do need a reliable test if some AP plugin is activated
1452 if (DBA::exists('apcontact', ['baseurl' => $url])) {
1453 $serverdata['network'] = Protocol::ACTIVITYPUB;
1455 $serverdata['network'] = Protocol::FEED;
1458 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1459 $serverdata['detection-method'] = self::DETECT_BODY;
1462 if (in_array($version_part[0], ['Friendika', 'Friendica'])) {
1463 $serverdata['platform'] = strtolower($version_part[0]);
1464 $serverdata['version'] = $version_part[1];
1465 $serverdata['network'] = Protocol::DFRN;
1471 $list = $xpath->query('//meta[@property]');
1473 foreach ($list as $node) {
1475 if ($node->attributes->length) {
1476 foreach ($node->attributes as $attribute) {
1477 $value = trim($attribute->value);
1478 if (empty($value)) {
1482 $attr[$attribute->name] = $value;
1485 if (empty($attr['property']) || empty($attr['content'])) {
1490 if ($attr['property'] == 'og:site_name') {
1491 $serverdata['site_name'] = $attr['content'];
1494 if ($attr['property'] == 'og:description') {
1495 $serverdata['info'] = $attr['content'];
1498 if ($attr['property'] == 'og:platform') {
1499 $serverdata['platform'] = strtolower($attr['content']);
1501 if (in_array($attr['content'], ['PeerTube'])) {
1502 $serverdata['network'] = Protocol::ACTIVITYPUB;
1506 if ($attr['property'] == 'generator') {
1507 $serverdata['platform'] = strtolower($attr['content']);
1509 if (in_array($attr['content'], ['hubzilla'])) {
1510 // We later check which compatible protocol modules are loaded.
1511 $serverdata['network'] = Protocol::ZOT;
1516 if (!empty($serverdata['network']) && ($serverdata['detection-method'] == self::DETECT_MANUAL)) {
1517 $serverdata['detection-method'] = self::DETECT_BODY;
1524 * Analyses the header data of a given server for hints about type and system of that server
1526 * @param object $curlResult result of curl execution
1527 * @param array $serverdata array with server data
1529 * @return array server data
1531 private static function analyseRootHeader($curlResult, array $serverdata)
1533 if ($curlResult->getHeader('server') == 'Mastodon') {
1534 $serverdata['platform'] = 'mastodon';
1535 $serverdata['network'] = Protocol::ACTIVITYPUB;
1536 } elseif ($curlResult->inHeader('x-diaspora-version')) {
1537 $serverdata['platform'] = 'diaspora';
1538 $serverdata['network'] = Protocol::DIASPORA;
1539 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version');
1540 } elseif ($curlResult->inHeader('x-friendica-version')) {
1541 $serverdata['platform'] = 'friendica';
1542 $serverdata['network'] = Protocol::DFRN;
1543 $serverdata['version'] = $curlResult->getHeader('x-friendica-version');
1548 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1549 $serverdata['detection-method'] = self::DETECT_HEADER;
1556 * Test if the body contains valid content
1558 * @param string $body
1561 private static function invalidBody(string $body)
1563 // Currently we only test for a HTML element.
1564 // Possibly we enhance this in the future.
1565 return !strpos($body, '>');
1569 * Update GServer entries
1571 public static function discover()
1573 // Update the server list
1574 self::discoverFederation();
1578 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
1580 if ($requery_days == 0) {
1584 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
1586 $gservers = DBA::p("SELECT `id`, `url`, `nurl`, `network`, `poco`, `directory-type`
1589 AND `directory-type` != ?
1590 AND `last_poco_query` < ?
1591 ORDER BY RAND()", self::DT_NONE, $last_update
1594 while ($gserver = DBA::fetch($gservers)) {
1595 if (!GServer::check($gserver['url'], $gserver['network'])) {
1596 // The server is not reachable? Okay, then we will try it later
1597 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1598 DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);
1602 Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1603 Worker::add(PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
1605 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1606 Worker::add(PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
1608 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1609 DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);
1611 if (--$no_of_queries == 0) {
1616 DBA::close($gservers);
1620 * Discover federated servers
1622 private static function discoverFederation()
1624 $last = DI::config()->get('poco', 'last_federation_discovery');
1627 $next = $last + (24 * 60 * 60);
1629 if ($next > time()) {
1634 // Discover federated servers
1635 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
1636 foreach ($protocols as $protocol) {
1637 $query = '{nodes(protocol:"' . $protocol . '"){host}}';
1638 $curlResult = DI::httpRequest()->fetch('https://the-federation.info/graphql?query=' . urlencode($query));
1639 if (!empty($curlResult)) {
1640 $data = json_decode($curlResult, true);
1641 if (!empty($data['data']['nodes'])) {
1642 foreach ($data['data']['nodes'] as $server) {
1643 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
1644 Worker::add(PRIORITY_LOW, 'UpdateGServer', 'https://' . $server['host'], true);
1650 // Disvover Mastodon servers
1651 $accesstoken = DI::config()->get('system', 'instances_social_key');
1653 if (!empty($accesstoken)) {
1654 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1655 $header = ['Authorization: Bearer '.$accesstoken];
1656 $curlResult = DI::httpRequest()->get($api, ['header' => $header]);
1658 if ($curlResult->isSuccess()) {
1659 $servers = json_decode($curlResult->getBody(), true);
1661 foreach ($servers['instances'] as $server) {
1662 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
1663 Worker::add(PRIORITY_LOW, 'UpdateGServer', $url);
1668 DI::config()->set('poco', 'last_federation_discovery', time());