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 * Check for the existance of a server and adds it in the background if not existant
77 * @param boolean $only_nodeinfo
80 public static function add(string $url, bool $only_nodeinfo = false)
82 if (self::getID($url, false)) {
86 Worker::add(PRIORITY_LOW, 'UpdateGServer', $url, $only_nodeinfo);
90 * Get the ID for the given server URL
93 * @param boolean $no_check Don't check if the server hadn't been found
94 * @return int gserver id
96 public static function getID(string $url, bool $no_check = false)
102 $url = self::cleanURL($url);
104 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
105 if (DBA::isResult($gserver)) {
106 Logger::info('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
107 return $gserver['id'];
110 if ($no_check || !self::check($url)) {
114 return self::getID($url, true);
118 * Checks if the given server is reachable
120 * @param string $profile URL of the given profile
121 * @param string $server URL of the given server (If empty, taken from profile)
122 * @param string $network Network value that is used, when detection failed
123 * @param boolean $force Force an update.
125 * @return boolean 'true' if server seems vital
127 public static function reachable(string $profile, string $server = '', string $network = '', bool $force = false)
130 $contact = Contact::getByURL($profile, null, ['baseurl']);
131 if (!empty($contact['baseurl'])) {
132 $server = $contact['baseurl'];
140 return self::check($server, $network, $force);
143 public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '')
145 // On successful contact process check again next week
147 return DateTimeFormat::utc('now +7 day');
150 $now = strtotime(DateTimeFormat::utcNow());
152 if ($created > $last_contact) {
153 $contact_time = strtotime($created);
155 $contact_time = strtotime($last_contact);
158 // If the last contact was less than 6 hours before then try again in 6 hours
159 if (($now - $contact_time) < (60 * 60 * 6)) {
160 return DateTimeFormat::utc('now +6 hour');
163 // If the last contact was less than 12 hours before then try again in 12 hours
164 if (($now - $contact_time) < (60 * 60 * 12)) {
165 return DateTimeFormat::utc('now +12 hour');
168 // If the last contact was less than 24 hours before then try tomorrow again
169 if (($now - $contact_time) < (60 * 60 * 24)) {
170 return DateTimeFormat::utc('now +1 day');
173 // If the last contact was less than a week before then try again in a week
174 if (($now - $contact_time) < (60 * 60 * 24 * 7)) {
175 return DateTimeFormat::utc('now +1 week');
178 // If the last contact was less than two weeks before then try again in two week
179 if (($now - $contact_time) < (60 * 60 * 24 * 14)) {
180 return DateTimeFormat::utc('now +2 week');
183 // If the last contact was less than a month before then try again in a month
184 if (($now - $contact_time) < (60 * 60 * 24 * 30)) {
185 return DateTimeFormat::utc('now +1 month');
188 // The system hadn't been successul contacted for more than a month, so try again in three months
189 return DateTimeFormat::utc('now +3 month');
193 * Checks the state of the given server.
195 * @param string $server_url URL of the given server
196 * @param string $network Network value that is used, when detection failed
197 * @param boolean $force Force an update.
198 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
200 * @return boolean 'true' if server seems vital
202 public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false)
204 $server_url = self::cleanURL($server_url);
205 if ($server_url == '') {
209 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
210 if (DBA::isResult($gserver)) {
211 if ($gserver['created'] <= DBA::NULL_DATETIME) {
212 $fields = ['created' => DateTimeFormat::utcNow()];
213 $condition = ['nurl' => Strings::normaliseLink($server_url)];
214 DBA::update('gserver', $fields, $condition);
217 if (!$force && (strtotime($gserver['next_contact']) > time())) {
218 Logger::info('No update needed', ['server' => $server_url]);
219 return (!$gserver['failed']);
221 Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]);
223 Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
226 return self::detect($server_url, $network, $only_nodeinfo);
230 * Set failed server status
234 public static function setFailure(string $url)
236 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($url)]);
237 if (DBA::isResult($gserver)) {
238 $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
239 DBA::update('gserver', ['failed' => true, 'last_failure' => DateTimeFormat::utcNow(),
240 'next_contact' => $next_update, '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 /// @todo What to do with "next_contact" here?
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'] = max($registeredUsers, 1);
452 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
455 $serverdata['next_contact'] = self::getNextUpdateDate(true);
457 $serverdata['last_contact'] = DateTimeFormat::utcNow();
458 $serverdata['failed'] = false;
460 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
461 if (!DBA::isResult($gserver)) {
462 $serverdata['created'] = DateTimeFormat::utcNow();
463 $ret = DBA::insert('gserver', $serverdata);
464 $id = DBA::lastInsertId();
466 // Don't override the network with 'unknown' when there had been a valid entry before
467 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($gserver['network'])) {
468 unset($serverdata['network']);
471 $ret = DBA::update('gserver', $serverdata, ['nurl' => $serverdata['nurl']]);
472 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
473 if (DBA::isResult($gserver)) {
474 $id = $gserver['id'];
478 if (!empty($serverdata['network']) && !empty($id) && ($serverdata['network'] != Protocol::PHANTOM)) {
479 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
480 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id]);
481 $max_users = max($apcontacts, $contacts, $registeredUsers, 1);
482 if ($max_users > $registeredUsers) {
483 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
484 DBA::update('gserver', ['registered-users' => $max_users], ['id' => $id]);
488 if (!empty($serverdata['network']) && in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
489 self::discoverRelay($url);
496 * Fetch relay data from a given server url
498 * @param string $server_url address of the server
499 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
501 private static function discoverRelay(string $server_url)
503 Logger::info('Discover relay data', ['server' => $server_url]);
505 $curlResult = DI::httpRequest()->get($server_url . '/.well-known/x-social-relay');
506 if (!$curlResult->isSuccess()) {
510 $data = json_decode($curlResult->getBody(), true);
511 if (!is_array($data)) {
515 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
516 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
518 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
520 $data['subscribe'] = false;
524 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
525 if (!DBA::isResult($gserver)) {
529 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
530 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
531 DBA::update('gserver', $fields, ['id' => $gserver['id']]);
534 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
536 if ($data['scope'] == 'tags') {
539 foreach ($data['tags'] as $tag) {
540 $tag = mb_strtolower($tag);
541 if (strlen($tag) < 100) {
546 foreach ($tags as $tag) {
547 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
551 // Create or update the relay contact
553 if (isset($data['protocols'])) {
554 if (isset($data['protocols']['diaspora'])) {
555 $fields['network'] = Protocol::DIASPORA;
557 if (isset($data['protocols']['diaspora']['receive'])) {
558 $fields['batch'] = $data['protocols']['diaspora']['receive'];
559 } elseif (is_string($data['protocols']['diaspora'])) {
560 $fields['batch'] = $data['protocols']['diaspora'];
564 if (isset($data['protocols']['dfrn'])) {
565 $fields['network'] = Protocol::DFRN;
567 if (isset($data['protocols']['dfrn']['receive'])) {
568 $fields['batch'] = $data['protocols']['dfrn']['receive'];
569 } elseif (is_string($data['protocols']['dfrn'])) {
570 $fields['batch'] = $data['protocols']['dfrn'];
574 if (isset($data['protocols']['activitypub'])) {
575 $fields['network'] = Protocol::ACTIVITYPUB;
577 if (!empty($data['protocols']['activitypub']['actor'])) {
578 $fields['url'] = $data['protocols']['activitypub']['actor'];
580 if (!empty($data['protocols']['activitypub']['receive'])) {
581 $fields['batch'] = $data['protocols']['activitypub']['receive'];
586 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
588 Relay::updateContact($gserver, $fields);
592 * Fetch server data from '/statistics.json' on the given server
594 * @param string $url URL of the given server
596 * @return array server data
598 private static function fetchStatistics(string $url)
600 $curlResult = DI::httpRequest()->get($url . '/statistics.json');
601 if (!$curlResult->isSuccess()) {
605 $data = json_decode($curlResult->getBody(), true);
610 $serverdata = ['detection-method' => self::DETECT_STATISTICS_JSON];
612 if (!empty($data['version'])) {
613 $serverdata['version'] = $data['version'];
614 // Version numbers on statistics.json are presented with additional info, e.g.:
615 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
616 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
619 if (!empty($data['name'])) {
620 $serverdata['site_name'] = $data['name'];
623 if (!empty($data['network'])) {
624 $serverdata['platform'] = strtolower($data['network']);
626 if ($serverdata['platform'] == 'diaspora') {
627 $serverdata['network'] = Protocol::DIASPORA;
628 } elseif ($serverdata['platform'] == 'friendica') {
629 $serverdata['network'] = Protocol::DFRN;
630 } elseif ($serverdata['platform'] == 'hubzilla') {
631 $serverdata['network'] = Protocol::ZOT;
632 } elseif ($serverdata['platform'] == 'redmatrix') {
633 $serverdata['network'] = Protocol::ZOT;
638 if (!empty($data['registrations_open'])) {
639 $serverdata['register_policy'] = Register::OPEN;
641 $serverdata['register_policy'] = Register::CLOSED;
648 * Detect server type by using the nodeinfo data
650 * @param string $url address of the server
651 * @param CurlResult $curlResult
652 * @return array Server data
653 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
655 private static function fetchNodeinfo(string $url, CurlResult $curlResult)
657 if (!$curlResult->isSuccess()) {
661 $nodeinfo = json_decode($curlResult->getBody(), true);
663 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
670 foreach ($nodeinfo['links'] as $link) {
671 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
672 Logger::info('Invalid nodeinfo format', ['url' => $url]);
675 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
676 $nodeinfo1_url = $link['href'];
677 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
678 $nodeinfo2_url = $link['href'];
682 if ($nodeinfo1_url . $nodeinfo2_url == '') {
688 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
689 if (!empty($nodeinfo2_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
690 $server = self::parseNodeinfo2($nodeinfo2_url);
693 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
694 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
695 $server = self::parseNodeinfo1($nodeinfo1_url);
704 * @param string $nodeinfo_url address of the nodeinfo path
705 * @return array Server data
706 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
708 private static function parseNodeinfo1(string $nodeinfo_url)
710 $curlResult = DI::httpRequest()->get($nodeinfo_url);
712 if (!$curlResult->isSuccess()) {
716 $nodeinfo = json_decode($curlResult->getBody(), true);
718 if (!is_array($nodeinfo)) {
722 $server = ['detection-method' => self::DETECT_NODEINFO_1,
723 'register_policy' => Register::CLOSED];
725 if (!empty($nodeinfo['openRegistrations'])) {
726 $server['register_policy'] = Register::OPEN;
729 if (is_array($nodeinfo['software'])) {
730 if (!empty($nodeinfo['software']['name'])) {
731 $server['platform'] = strtolower($nodeinfo['software']['name']);
734 if (!empty($nodeinfo['software']['version'])) {
735 $server['version'] = $nodeinfo['software']['version'];
736 // Version numbers on Nodeinfo are presented with additional info, e.g.:
737 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
738 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
742 if (!empty($nodeinfo['metadata']['nodeName'])) {
743 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
746 if (!empty($nodeinfo['usage']['users']['total'])) {
747 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
750 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
752 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
753 $protocols[$protocol] = true;
756 if (!empty($protocols['friendica'])) {
757 $server['network'] = Protocol::DFRN;
758 } elseif (!empty($protocols['activitypub'])) {
759 $server['network'] = Protocol::ACTIVITYPUB;
760 } elseif (!empty($protocols['diaspora'])) {
761 $server['network'] = Protocol::DIASPORA;
762 } elseif (!empty($protocols['ostatus'])) {
763 $server['network'] = Protocol::OSTATUS;
764 } elseif (!empty($protocols['gnusocial'])) {
765 $server['network'] = Protocol::OSTATUS;
766 } elseif (!empty($protocols['zot'])) {
767 $server['network'] = Protocol::ZOT;
771 if (empty($server)) {
781 * @param string $nodeinfo_url address of the nodeinfo path
782 * @return array Server data
783 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
785 private static function parseNodeinfo2(string $nodeinfo_url)
787 $curlResult = DI::httpRequest()->get($nodeinfo_url);
788 if (!$curlResult->isSuccess()) {
792 $nodeinfo = json_decode($curlResult->getBody(), true);
794 if (!is_array($nodeinfo)) {
798 $server = ['detection-method' => self::DETECT_NODEINFO_2,
799 'register_policy' => Register::CLOSED];
801 if (!empty($nodeinfo['openRegistrations'])) {
802 $server['register_policy'] = Register::OPEN;
805 if (is_array($nodeinfo['software'])) {
806 if (!empty($nodeinfo['software']['name'])) {
807 $server['platform'] = strtolower($nodeinfo['software']['name']);
810 if (!empty($nodeinfo['software']['version'])) {
811 $server['version'] = $nodeinfo['software']['version'];
812 // Version numbers on Nodeinfo are presented with additional info, e.g.:
813 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
814 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
818 if (!empty($nodeinfo['metadata']['nodeName'])) {
819 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
822 if (!empty($nodeinfo['usage']['users']['total'])) {
823 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
826 if (!empty($nodeinfo['protocols'])) {
828 foreach ($nodeinfo['protocols'] as $protocol) {
829 $protocols[$protocol] = true;
832 if (!empty($protocols['dfrn'])) {
833 $server['network'] = Protocol::DFRN;
834 } elseif (!empty($protocols['activitypub'])) {
835 $server['network'] = Protocol::ACTIVITYPUB;
836 } elseif (!empty($protocols['diaspora'])) {
837 $server['network'] = Protocol::DIASPORA;
838 } elseif (!empty($protocols['ostatus'])) {
839 $server['network'] = Protocol::OSTATUS;
840 } elseif (!empty($protocols['gnusocial'])) {
841 $server['network'] = Protocol::OSTATUS;
842 } elseif (!empty($protocols['zot'])) {
843 $server['network'] = Protocol::ZOT;
847 if (empty($server)) {
855 * Fetch server information from a 'siteinfo.json' file on the given server
857 * @param string $url URL of the given server
858 * @param array $serverdata array with server data
860 * @return array server data
862 private static function fetchSiteinfo(string $url, array $serverdata)
864 $curlResult = DI::httpRequest()->get($url . '/siteinfo.json');
865 if (!$curlResult->isSuccess()) {
869 $data = json_decode($curlResult->getBody(), true);
874 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
875 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
878 if (!empty($data['url'])) {
879 $serverdata['platform'] = strtolower($data['platform']);
880 $serverdata['version'] = $data['version'];
883 if (!empty($data['plugins'])) {
884 if (in_array('pubcrawl', $data['plugins'])) {
885 $serverdata['network'] = Protocol::ACTIVITYPUB;
886 } elseif (in_array('diaspora', $data['plugins'])) {
887 $serverdata['network'] = Protocol::DIASPORA;
888 } elseif (in_array('gnusoc', $data['plugins'])) {
889 $serverdata['network'] = Protocol::OSTATUS;
891 $serverdata['network'] = Protocol::ZOT;
895 if (!empty($data['site_name'])) {
896 $serverdata['site_name'] = $data['site_name'];
899 if (!empty($data['channels_total'])) {
900 $serverdata['registered-users'] = max($data['channels_total'], 1);
903 if (!empty($data['register_policy'])) {
904 switch ($data['register_policy']) {
905 case 'REGISTER_OPEN':
906 $serverdata['register_policy'] = Register::OPEN;
909 case 'REGISTER_APPROVE':
910 $serverdata['register_policy'] = Register::APPROVE;
913 case 'REGISTER_CLOSED':
915 $serverdata['register_policy'] = Register::CLOSED;
924 * Checks if the server contains a valid host meta file
926 * @param string $url URL of the given server
928 * @return boolean 'true' if the server seems to be vital
930 private static function validHostMeta(string $url)
932 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
933 $curlResult = DI::httpRequest()->get($url . '/.well-known/host-meta', ['timeout' => $xrd_timeout]);
934 if (!$curlResult->isSuccess()) {
938 $xrd = XML::parseString($curlResult->getBody());
939 if (!is_object($xrd)) {
943 $elements = XML::elementToArray($xrd);
944 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
949 foreach ($elements['xrd']['link'] as $link) {
950 // When there is more than a single "link" element, the array looks slightly different
951 if (!empty($link['@attributes'])) {
952 $link = $link['@attributes'];
955 if (empty($link['rel']) || empty($link['template'])) {
959 if ($link['rel'] == 'lrdd') {
960 // When the webfinger host is the same like the system host, it should be ok.
961 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
969 * Detect the network of the given server via their known contacts
971 * @param string $url URL of the given server
972 * @param array $serverdata array with server data
974 * @return array server data
976 private static function detectNetworkViaContacts(string $url, array $serverdata)
980 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $serverdata['nurl']]]);
981 while ($apcontact = DBA::fetch($apcontacts)) {
982 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
984 DBA::close($apcontacts);
986 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $serverdata['nurl']]]);
987 while ($pcontact = DBA::fetch($pcontacts)) {
988 $contacts[$pcontact['nurl']] = $pcontact['url'];
990 DBA::close($pcontacts);
992 if (empty($contacts)) {
996 foreach ($contacts as $contact) {
997 $probed = Contact::getByURL($contact);
998 if (!empty($probed) && in_array($probed['network'], Protocol::FEDERATED)) {
999 $serverdata['network'] = $probed['network'];
1004 $serverdata['registered-users'] = max($serverdata['registered-users'], count($contacts), 1);
1010 * Checks if the given server does have a '/poco' endpoint.
1011 * This is used for the 'PortableContact' functionality,
1012 * which is used by both Friendica and Hubzilla.
1014 * @param string $url URL of the given server
1015 * @param array $serverdata array with server data
1017 * @return array server data
1019 private static function checkPoCo(string $url, array $serverdata)
1021 $serverdata['poco'] = '';
1023 $curlResult = DI::httpRequest()->get($url . '/poco');
1024 if (!$curlResult->isSuccess()) {
1028 $data = json_decode($curlResult->getBody(), true);
1033 if (!empty($data['totalResults'])) {
1034 $registeredUsers = $serverdata['registered-users'] ?? 0;
1035 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1036 $serverdata['directory-type'] = self::DT_POCO;
1037 $serverdata['poco'] = $url . '/poco';
1044 * Checks if the given server does have a Mastodon style directory endpoint.
1046 * @param string $url URL of the given server
1047 * @param array $serverdata array with server data
1049 * @return array server data
1051 public static function checkMastodonDirectory(string $url, array $serverdata)
1053 $curlResult = DI::httpRequest()->get($url . '/api/v1/directory?limit=1');
1054 if (!$curlResult->isSuccess()) {
1058 $data = json_decode($curlResult->getBody(), true);
1063 if (count($data) == 1) {
1064 $serverdata['directory-type'] = self::DT_MASTODON;
1071 * Detects the version number of a given server when it was a NextCloud installation
1073 * @param string $url URL of the given server
1074 * @param array $serverdata array with server data
1076 * @return array server data
1078 private static function detectNextcloud(string $url, array $serverdata)
1080 $curlResult = DI::httpRequest()->get($url . '/status.php');
1082 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1086 $data = json_decode($curlResult->getBody(), true);
1091 if (!empty($data['version'])) {
1092 $serverdata['platform'] = 'nextcloud';
1093 $serverdata['version'] = $data['version'];
1094 $serverdata['network'] = Protocol::ACTIVITYPUB;
1096 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1097 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1105 * Detects data from a given server url if it was a mastodon alike system
1107 * @param string $url URL of the given server
1108 * @param array $serverdata array with server data
1110 * @return array server data
1112 private static function detectMastodonAlikes(string $url, array $serverdata)
1114 $curlResult = DI::httpRequest()->get($url . '/api/v1/instance');
1116 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1120 $data = json_decode($curlResult->getBody(), true);
1125 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1126 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1129 if (!empty($data['version'])) {
1130 $serverdata['platform'] = 'mastodon';
1131 $serverdata['version'] = $data['version'] ?? '';
1132 $serverdata['network'] = Protocol::ACTIVITYPUB;
1135 if (!empty($data['title'])) {
1136 $serverdata['site_name'] = $data['title'];
1139 if (!empty($data['title']) && empty($serverdata['platform']) && empty($serverdata['network'])) {
1140 $serverdata['platform'] = 'mastodon';
1141 $serverdata['network'] = Protocol::ACTIVITYPUB;
1144 if (!empty($data['description'])) {
1145 $serverdata['info'] = trim($data['description']);
1148 if (!empty($data['stats']['user_count'])) {
1149 $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1152 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1153 $serverdata['platform'] = strtolower($matches[1]);
1154 $serverdata['version'] = $matches[2];
1157 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1158 $serverdata['platform'] = 'pleroma';
1159 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1162 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1163 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1164 $serverdata['platform'] = 'pleroma';
1171 * Detects data from typical Hubzilla endpoints
1173 * @param string $url URL of the given server
1174 * @param array $serverdata array with server data
1176 * @return array server data
1178 private static function detectHubzilla(string $url, array $serverdata)
1180 $curlResult = DI::httpRequest()->get($url . '/api/statusnet/config.json');
1181 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1185 $data = json_decode($curlResult->getBody(), true);
1186 if (empty($data) || empty($data['site'])) {
1190 if (!empty($data['site']['name'])) {
1191 $serverdata['site_name'] = $data['site']['name'];
1194 if (!empty($data['site']['platform'])) {
1195 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1196 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1197 $serverdata['network'] = Protocol::ZOT;
1200 if (!empty($data['site']['hubzilla'])) {
1201 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1202 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1203 $serverdata['network'] = Protocol::ZOT;
1206 if (!empty($data['site']['redmatrix'])) {
1207 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1208 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1209 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1210 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1213 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1214 $serverdata['network'] = Protocol::ZOT;
1218 $inviteonly = false;
1221 if (!empty($data['site']['closed'])) {
1222 $closed = self::toBoolean($data['site']['closed']);
1225 if (!empty($data['site']['private'])) {
1226 $private = self::toBoolean($data['site']['private']);
1229 if (!empty($data['site']['inviteonly'])) {
1230 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1233 if (!$closed && !$private and $inviteonly) {
1234 $serverdata['register_policy'] = Register::APPROVE;
1235 } elseif (!$closed && !$private) {
1236 $serverdata['register_policy'] = Register::OPEN;
1238 $serverdata['register_policy'] = Register::CLOSED;
1241 if (!empty($serverdata['network']) && in_array($serverdata['detection-method'],
1242 [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1243 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1250 * Converts input value to a boolean value
1252 * @param string|integer $val
1256 private static function toBoolean($val)
1258 if (($val == 'true') || ($val == 1)) {
1260 } elseif (($val == 'false') || ($val == 0)) {
1268 * Detect if the URL belongs to a GNU Social server
1270 * @param string $url URL of the given server
1271 * @param array $serverdata array with server data
1273 * @return array server data
1275 private static function detectGNUSocial(string $url, array $serverdata)
1277 // Test for GNU Social
1278 $curlResult = DI::httpRequest()->get($url . '/api/gnusocial/version.json');
1279 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1280 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1281 $serverdata['platform'] = 'gnusocial';
1282 // Remove junk that some GNU Social servers return
1283 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1284 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1285 $serverdata['version'] = trim($serverdata['version'], '"');
1286 $serverdata['network'] = Protocol::OSTATUS;
1288 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1289 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1295 // Test for Statusnet
1296 $curlResult = DI::httpRequest()->get($url . '/api/statusnet/version.json');
1297 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1298 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1300 // Remove junk that some GNU Social servers return
1301 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1302 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1303 $serverdata['version'] = trim($serverdata['version'], '"');
1305 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1306 $serverdata['platform'] = 'pleroma';
1307 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1308 $serverdata['network'] = Protocol::ACTIVITYPUB;
1310 $serverdata['platform'] = 'statusnet';
1311 $serverdata['network'] = Protocol::OSTATUS;
1314 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1315 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1323 * Detect if the URL belongs to a Friendica server
1325 * @param string $url URL of the given server
1326 * @param array $serverdata array with server data
1328 * @return array server data
1330 private static function detectFriendica(string $url, array $serverdata)
1332 $curlResult = DI::httpRequest()->get($url . '/friendica/json');
1333 if (!$curlResult->isSuccess()) {
1334 $curlResult = DI::httpRequest()->get($url . '/friendika/json');
1336 $platform = 'Friendika';
1339 $platform = 'Friendica';
1342 if (!$curlResult->isSuccess()) {
1346 $data = json_decode($curlResult->getBody(), true);
1347 if (empty($data) || empty($data['version'])) {
1351 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1352 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1355 $serverdata['network'] = Protocol::DFRN;
1356 $serverdata['version'] = $data['version'];
1358 if (!empty($data['no_scrape_url'])) {
1359 $serverdata['noscrape'] = $data['no_scrape_url'];
1362 if (!empty($data['site_name'])) {
1363 $serverdata['site_name'] = $data['site_name'];
1366 if (!empty($data['info'])) {
1367 $serverdata['info'] = trim($data['info']);
1370 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1371 switch ($register_policy) {
1372 case 'REGISTER_OPEN':
1373 $serverdata['register_policy'] = Register::OPEN;
1376 case 'REGISTER_APPROVE':
1377 $serverdata['register_policy'] = Register::APPROVE;
1380 case 'REGISTER_CLOSED':
1381 case 'REGISTER_INVITATION':
1382 $serverdata['register_policy'] = Register::CLOSED;
1385 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
1386 $serverdata['register_policy'] = Register::CLOSED;
1390 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
1396 * Analyses the landing page of a given server for hints about type and system of that server
1398 * @param object $curlResult result of curl execution
1399 * @param array $serverdata array with server data
1400 * @param string $url Server URL
1402 * @return array server data
1404 private static function analyseRootBody($curlResult, array $serverdata, string $url)
1406 $doc = new DOMDocument();
1407 @$doc->loadHTML($curlResult->getBody());
1408 $xpath = new DOMXPath($doc);
1410 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
1411 if (!empty($title)) {
1412 $serverdata['site_name'] = $title;
1415 $list = $xpath->query('//meta[@name]');
1417 foreach ($list as $node) {
1419 if ($node->attributes->length) {
1420 foreach ($node->attributes as $attribute) {
1421 $value = trim($attribute->value);
1422 if (empty($value)) {
1426 $attr[$attribute->name] = $value;
1429 if (empty($attr['name']) || empty($attr['content'])) {
1434 if ($attr['name'] == 'description') {
1435 $serverdata['info'] = $attr['content'];
1438 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
1439 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad'])) {
1440 $serverdata['platform'] = strtolower($attr['content']);
1441 if (in_array($attr['content'], ['Misskey', 'Write.as'])) {
1442 $serverdata['network'] = Protocol::ACTIVITYPUB;
1445 if (($attr['name'] == 'generator') && (empty($serverdata['platform']) || (substr(strtolower($attr['content']), 0, 9) == 'wordpress'))) {
1446 $serverdata['platform'] = strtolower($attr['content']);
1447 $version_part = explode(' ', $attr['content']);
1449 if (count($version_part) == 2) {
1450 if (in_array($version_part[0], ['WordPress'])) {
1451 $serverdata['platform'] = strtolower($version_part[0]);
1452 $serverdata['version'] = $version_part[1];
1454 // We still do need a reliable test if some AP plugin is activated
1455 if (DBA::exists('apcontact', ['baseurl' => $url])) {
1456 $serverdata['network'] = Protocol::ACTIVITYPUB;
1458 $serverdata['network'] = Protocol::FEED;
1461 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1462 $serverdata['detection-method'] = self::DETECT_BODY;
1465 if (in_array($version_part[0], ['Friendika', 'Friendica'])) {
1466 $serverdata['platform'] = strtolower($version_part[0]);
1467 $serverdata['version'] = $version_part[1];
1468 $serverdata['network'] = Protocol::DFRN;
1474 $list = $xpath->query('//meta[@property]');
1476 foreach ($list as $node) {
1478 if ($node->attributes->length) {
1479 foreach ($node->attributes as $attribute) {
1480 $value = trim($attribute->value);
1481 if (empty($value)) {
1485 $attr[$attribute->name] = $value;
1488 if (empty($attr['property']) || empty($attr['content'])) {
1493 if ($attr['property'] == 'og:site_name') {
1494 $serverdata['site_name'] = $attr['content'];
1497 if ($attr['property'] == 'og:description') {
1498 $serverdata['info'] = $attr['content'];
1501 if ($attr['property'] == 'og:platform') {
1502 $serverdata['platform'] = strtolower($attr['content']);
1504 if (in_array($attr['content'], ['PeerTube'])) {
1505 $serverdata['network'] = Protocol::ACTIVITYPUB;
1509 if ($attr['property'] == 'generator') {
1510 $serverdata['platform'] = strtolower($attr['content']);
1512 if (in_array($attr['content'], ['hubzilla'])) {
1513 // We later check which compatible protocol modules are loaded.
1514 $serverdata['network'] = Protocol::ZOT;
1519 if (!empty($serverdata['network']) && ($serverdata['detection-method'] == self::DETECT_MANUAL)) {
1520 $serverdata['detection-method'] = self::DETECT_BODY;
1527 * Analyses the header data of a given server for hints about type and system of that server
1529 * @param object $curlResult result of curl execution
1530 * @param array $serverdata array with server data
1532 * @return array server data
1534 private static function analyseRootHeader($curlResult, array $serverdata)
1536 if ($curlResult->getHeader('server') == 'Mastodon') {
1537 $serverdata['platform'] = 'mastodon';
1538 $serverdata['network'] = Protocol::ACTIVITYPUB;
1539 } elseif ($curlResult->inHeader('x-diaspora-version')) {
1540 $serverdata['platform'] = 'diaspora';
1541 $serverdata['network'] = Protocol::DIASPORA;
1542 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version');
1543 } elseif ($curlResult->inHeader('x-friendica-version')) {
1544 $serverdata['platform'] = 'friendica';
1545 $serverdata['network'] = Protocol::DFRN;
1546 $serverdata['version'] = $curlResult->getHeader('x-friendica-version');
1551 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1552 $serverdata['detection-method'] = self::DETECT_HEADER;
1559 * Test if the body contains valid content
1561 * @param string $body
1564 private static function invalidBody(string $body)
1566 // Currently we only test for a HTML element.
1567 // Possibly we enhance this in the future.
1568 return !strpos($body, '>');
1572 * Update GServer entries
1574 public static function discover()
1576 // Update the server list
1577 self::discoverFederation();
1581 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
1583 if ($requery_days == 0) {
1587 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
1589 $gservers = DBA::p("SELECT `id`, `url`, `nurl`, `network`, `poco`, `directory-type`
1592 AND `directory-type` != ?
1593 AND `last_poco_query` < ?
1594 ORDER BY RAND()", self::DT_NONE, $last_update
1597 while ($gserver = DBA::fetch($gservers)) {
1598 Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1599 Worker::add(PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
1601 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1602 Worker::add(PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
1604 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1605 DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);
1607 if (--$no_of_queries == 0) {
1612 DBA::close($gservers);
1616 * Discover federated servers
1618 private static function discoverFederation()
1620 $last = DI::config()->get('poco', 'last_federation_discovery');
1623 $next = $last + (24 * 60 * 60);
1625 if ($next > time()) {
1630 // Discover federated servers
1631 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
1632 foreach ($protocols as $protocol) {
1633 $query = '{nodes(protocol:"' . $protocol . '"){host}}';
1634 $curlResult = DI::httpRequest()->fetch('https://the-federation.info/graphql?query=' . urlencode($query));
1635 if (!empty($curlResult)) {
1636 $data = json_decode($curlResult, true);
1637 if (!empty($data['data']['nodes'])) {
1638 foreach ($data['data']['nodes'] as $server) {
1639 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
1640 self::add('https://' . $server['host'], true);
1646 // Disvover Mastodon servers
1647 $accesstoken = DI::config()->get('system', 'instances_social_key');
1649 if (!empty($accesstoken)) {
1650 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1651 $header = ['Authorization: Bearer '.$accesstoken];
1652 $curlResult = DI::httpRequest()->get($api, ['header' => $header]);
1654 if ($curlResult->isSuccess()) {
1655 $servers = json_decode($curlResult->getBody(), true);
1657 foreach ($servers['instances'] as $server) {
1658 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
1664 DI::config()->set('poco', 'last_federation_discovery', time());