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\Protocol;
27 use Friendica\Core\Worker;
28 use Friendica\Database\DBA;
30 use Friendica\Module\Register;
31 use Friendica\Network\CurlResult;
32 use Friendica\Util\Network;
33 use Friendica\Util\DateTimeFormat;
34 use Friendica\Util\Strings;
35 use Friendica\Util\XML;
36 use Friendica\Core\Logger;
37 use Friendica\Core\System;
38 use Friendica\Protocol\PortableContact;
39 use Friendica\Protocol\Diaspora;
40 use Friendica\Network\Probe;
43 * This class handles GServer related functions
50 const DT_MASTODON = 2;
52 // Methods to detect server types
54 // Non endpoint specific methods
55 const DETECT_MANUAL = 0;
56 const DETECT_HEADER = 1;
57 const DETECT_BODY = 2;
59 // Implementation specific endpoints
60 const DETECT_FRIENDIKA = 10;
61 const DETECT_FRIENDICA = 11;
62 const DETECT_STATUSNET = 12;
63 const DETECT_GNUSOCIAL = 13;
64 const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix
65 const DETECT_SITEINFO_JSON = 15; // Newer Hubzilla
66 const DETECT_MASTODON_API = 16;
67 const DETECT_STATUS_PHP = 17; // Nextcloud
69 // Standardized endpoints
70 const DETECT_STATISTICS_JSON = 100;
71 const DETECT_NODEINFO_1 = 101;
72 const DETECT_NODEINFO_2 = 102;
75 * Get the ID for the given server URL
78 * @param boolean $no_check Don't check if the server hadn't been found
79 * @return int gserver id
81 public static function getID(string $url, bool $no_check = false)
87 $url = self::cleanURL($url);
89 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
90 if (DBA::isResult($gserver)) {
91 Logger::info('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
92 return $gserver['id'];
95 if ($no_check || !self::check($url)) {
99 return self::getID($url, true);
103 * Checks if the given server is reachable
105 * @param string $profile URL of the given profile
106 * @param string $server URL of the given server (If empty, taken from profile)
107 * @param string $network Network value that is used, when detection failed
108 * @param boolean $force Force an update.
110 * @return boolean 'true' if server seems vital
112 public static function reachable(string $profile, string $server = '', string $network = '', bool $force = false)
115 $server = GContact::getBasepath($profile);
122 return self::check($server, $network, $force);
126 * Decides if a server needs to be updated, based upon several date fields
128 * @param date $created Creation date of that server entry
129 * @param date $updated When had the server entry be updated
130 * @param date $last_failure Last failure when contacting that server
131 * @param date $last_contact Last time the server had been contacted
133 * @return boolean Does the server record needs an update?
135 public static function updateNeeded($created, $updated, $last_failure, $last_contact)
137 $now = strtotime(DateTimeFormat::utcNow());
139 if ($updated > $last_contact) {
140 $contact_time = strtotime($updated);
142 $contact_time = strtotime($last_contact);
145 $failure_time = strtotime($last_failure);
146 $created_time = strtotime($created);
148 // If there is no "created" time then use the current time
149 if ($created_time <= 0) {
150 $created_time = $now;
153 // If the last contact was less than 24 hours then don't update
154 if (($now - $contact_time) < (60 * 60 * 24)) {
158 // If the last failure was less than 24 hours then don't update
159 if (($now - $failure_time) < (60 * 60 * 24)) {
163 // If the last contact was less than a week ago and the last failure is older than a week then don't update
164 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) && ($contact_time > $failure_time))
167 // 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
168 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) && (($now - $created_time) > (60 * 60 * 24 * 7)) && (($now - $failure_time) < (60 * 60 * 24 * 7))) {
172 // 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
173 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) && (($now - $created_time) > (60 * 60 * 24 * 30)) && (($now - $failure_time) < (60 * 60 * 24 * 30))) {
181 * Checks the state of the given server.
183 * @param string $server_url URL of the given server
184 * @param string $network Network value that is used, when detection failed
185 * @param boolean $force Force an update.
186 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
188 * @return boolean 'true' if server seems vital
190 public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false)
192 $server_url = self::cleanURL($server_url);
194 if ($server_url == '') {
198 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
199 if (DBA::isResult($gserver)) {
200 if ($gserver['created'] <= DBA::NULL_DATETIME) {
201 $fields = ['created' => DateTimeFormat::utcNow()];
202 $condition = ['nurl' => Strings::normaliseLink($server_url)];
203 DBA::update('gserver', $fields, $condition);
206 $last_contact = $gserver['last_contact'];
207 $last_failure = $gserver['last_failure'];
209 // See discussion under https://forum.friendi.ca/display/0b6b25a8135aabc37a5a0f5684081633
210 // It can happen that a zero date is in the database, but storing it again is forbidden.
211 if ($last_contact < DBA::NULL_DATETIME) {
212 $last_contact = DBA::NULL_DATETIME;
215 if ($last_failure < DBA::NULL_DATETIME) {
216 $last_failure = DBA::NULL_DATETIME;
219 if (!$force && !self::updateNeeded($gserver['created'], '', $last_failure, $last_contact)) {
220 Logger::info('No update needed', ['server' => $server_url]);
221 return ($last_contact >= $last_failure);
223 Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force, 'Created' => $gserver['created'], 'Failure' => $last_failure, 'Contact' => $last_contact]);
225 Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
228 return self::detect($server_url, $network, $only_nodeinfo);
232 * Set failed server status
236 private static function setFailure(string $url)
238 if (DBA::exists('gserver', ['nurl' => Strings::normaliseLink($url)])) {
239 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow(), 'detection-method' => null],
240 ['nurl' => Strings::normaliseLink($url)]);
241 Logger::info('Set failed status for existing server', ['url' => $url]);
244 DBA::insert('gserver', ['url' => $url, 'nurl' => Strings::normaliseLink($url),
245 'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
246 'last_failure' => DateTimeFormat::utcNow()]);
247 Logger::info('Set failed status for new server', ['url' => $url]);
250 public static function cleanURL(string $url)
252 $url = trim($url, '/');
253 $url = str_replace('/index.php', '', $url);
255 $urlparts = parse_url($url);
256 unset($urlparts['user']);
257 unset($urlparts['pass']);
258 unset($urlparts['query']);
259 unset($urlparts['fragment']);
260 return Network::unparseURL($urlparts);
263 private static function getBaseURL(string $url)
265 $urlparts = parse_url($url);
266 unset($urlparts['user']);
267 unset($urlparts['pass']);
268 unset($urlparts['query']);
269 unset($urlparts['fragment']);
270 unset($urlparts['path']);
271 return Network::unparseURL($urlparts);
275 * Detect server data (type, protocol, version number, ...)
276 * The detected data is then updated or inserted in the gserver table.
278 * @param string $url URL of the given server
279 * @param string $network Network value that is used, when detection failed
280 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
282 * @return boolean 'true' if server could be detected
284 public static function detect(string $url, string $network = '', bool $only_nodeinfo = false)
286 Logger::info('Detect server type', ['server' => $url]);
287 $serverdata = ['detection-method' => self::DETECT_MANUAL];
289 $original_url = $url;
291 // Remove URL content that is not supposed to exist for a server url
292 $url = self::cleanURL($url);
295 $baseurl = self::getBaseURL($url);
297 // If the URL missmatches, then we mark the old entry as failure
298 if ($url != $original_url) {
299 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => Strings::normaliseLink($original_url)]);
302 // When a nodeinfo is present, we don't need to dig further
303 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
304 $curlResult = Network::curl($url . '/.well-known/nodeinfo', false, ['timeout' => $xrd_timeout]);
305 if ($curlResult->isTimeout()) {
306 self::setFailure($url);
310 $nodeinfo = self::fetchNodeinfo($url, $curlResult);
311 if ($only_nodeinfo && empty($nodeinfo)) {
312 Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
313 self::setFailure($url);
317 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
318 if (empty($nodeinfo)) {
319 $nodeinfo = self::fetchStatistics($url);
322 // If that didn't work out well, we use some protocol specific endpoints
323 // For Friendica and Zot based networks we have to dive deeper to reveal more details
324 if (empty($nodeinfo['network']) || in_array($nodeinfo['network'], [Protocol::DFRN, Protocol::ZOT])) {
325 if (!empty($nodeinfo['detection-method'])) {
326 $serverdata['detection-method'] = $nodeinfo['detection-method'];
329 // Fetch the landing page, possibly it reveals some data
330 if (empty($nodeinfo['network'])) {
331 if ($baseurl == $url) {
332 $basedata = $serverdata;
334 $basedata = ['detection-method' => self::DETECT_MANUAL];
337 $curlResult = Network::curl($baseurl, false, ['timeout' => $xrd_timeout]);
338 if ($curlResult->isSuccess()) {
339 $basedata = self::analyseRootHeader($curlResult, $basedata);
340 $basedata = self::analyseRootBody($curlResult, $basedata, $baseurl);
343 if (!$curlResult->isSuccess() || empty($curlResult->getBody()) || self::invalidBody($curlResult->getBody())) {
344 self::setFailure($url);
348 if ($baseurl == $url) {
349 $serverdata = $basedata;
351 // When the base path doesn't seem to contain a social network we try the complete path.
352 // Most detectable system have to be installed in the root directory.
353 // We checked the base to avoid false positives.
354 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout]);
355 if ($curlResult->isSuccess()) {
356 $urldata = self::analyseRootHeader($curlResult, $serverdata);
357 $urldata = self::analyseRootBody($curlResult, $urldata, $url);
359 $comparebase = $basedata;
360 unset($comparebase['info']);
361 unset($comparebase['site_name']);
362 $compareurl = $urldata;
363 unset($compareurl['info']);
364 unset($compareurl['site_name']);
366 // We assume that no one will install the identical system in the root and a subfolder
367 if (!empty(array_diff($comparebase, $compareurl))) {
368 $serverdata = $urldata;
374 if (empty($serverdata['network']) || ($serverdata['network'] == Protocol::ACTIVITYPUB)) {
375 $serverdata = self::detectMastodonAlikes($url, $serverdata);
378 // All following checks are done for systems that always have got a "host-meta" endpoint.
379 // With this check we don't have to waste time and ressources for dead systems.
380 // Also this hopefully prevents us from receiving abuse messages.
381 if (empty($serverdata['network']) && !self::validHostMeta($url)) {
382 self::setFailure($url);
386 if (empty($serverdata['network']) || in_array($serverdata['network'], [Protocol::DFRN, Protocol::ACTIVITYPUB])) {
387 $serverdata = self::detectFriendica($url, $serverdata);
390 // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
391 if (empty($serverdata['network']) || ($serverdata['network'] == Protocol::ZOT)) {
392 $serverdata = self::fetchSiteinfo($url, $serverdata);
395 // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations
396 if (empty($serverdata['network'])) {
397 $serverdata = self::detectHubzilla($url, $serverdata);
400 if (empty($serverdata['network'])) {
401 $serverdata = self::detectNextcloud($url, $serverdata);
404 if (empty($serverdata['network'])) {
405 $serverdata = self::detectGNUSocial($url, $serverdata);
408 $serverdata = array_merge($nodeinfo, $serverdata);
410 $serverdata = $nodeinfo;
413 // Detect the directory type
414 $serverdata['directory-type'] = self::DT_NONE;
415 $serverdata = self::checkPoCo($url, $serverdata);
416 $serverdata = self::checkMastodonDirectory($url, $serverdata);
418 // We can't detect the network type. Possibly it is some system that we don't know yet
419 if (empty($serverdata['network'])) {
420 $serverdata['network'] = Protocol::PHANTOM;
423 // When we hadn't been able to detect the network type, we use the hint from the parameter
424 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
425 $serverdata['network'] = $network;
428 $serverdata['url'] = $url;
429 $serverdata['nurl'] = Strings::normaliseLink($url);
431 // We take the highest number that we do find
432 $registeredUsers = $serverdata['registered-users'] ?? 0;
434 // On an active server there has to be at least a single user
435 if (($serverdata['network'] != Protocol::PHANTOM) && ($registeredUsers == 0)) {
436 $registeredUsers = 1;
439 if ($serverdata['network'] == Protocol::PHANTOM) {
440 $serverdata['registered-users'] = $registeredUsers;
441 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
444 $serverdata['last_contact'] = DateTimeFormat::utcNow();
446 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
447 if (!DBA::isResult($gserver)) {
448 $serverdata['created'] = DateTimeFormat::utcNow();
449 $ret = DBA::insert('gserver', $serverdata);
450 $id = DBA::lastInsertId();
452 // Don't override the network with 'unknown' when there had been a valid entry before
453 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($gserver['network'])) {
454 unset($serverdata['network']);
457 $ret = DBA::update('gserver', $serverdata, ['nurl' => $serverdata['nurl']]);
458 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
459 if (DBA::isResult($gserver)) {
460 $id = $gserver['id'];
464 if (!empty($id) && ($serverdata['network'] != Protocol::PHANTOM)) {
465 $gcontacts = DBA::count('gcontact', ['gsid' => $id]);
466 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
467 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id]);
468 $max_users = max($gcontacts, $apcontacts, $contacts, $registeredUsers);
469 if ($max_users > $registeredUsers) {
470 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
471 DBA::update('gserver', ['registered-users' => $max_users], ['id' => $id]);
475 if (!empty($serverdata['network']) && in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
476 self::discoverRelay($url);
483 * Fetch relay data from a given server url
485 * @param string $server_url address of the server
486 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
488 private static function discoverRelay(string $server_url)
490 Logger::info('Discover relay data', ['server' => $server_url]);
492 $curlResult = Network::curl($server_url . '/.well-known/x-social-relay');
493 if (!$curlResult->isSuccess()) {
497 $data = json_decode($curlResult->getBody(), true);
498 if (!is_array($data)) {
502 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
503 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
505 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
507 $data['subscribe'] = false;
511 $gserver = DBA::selectFirst('gserver', ['id', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
512 if (!DBA::isResult($gserver)) {
516 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
517 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
518 DBA::update('gserver', $fields, ['id' => $gserver['id']]);
521 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
523 if ($data['scope'] == 'tags') {
526 foreach ($data['tags'] as $tag) {
527 $tag = mb_strtolower($tag);
528 if (strlen($tag) < 100) {
533 foreach ($tags as $tag) {
534 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], true);
538 // Create or update the relay contact
540 if (isset($data['protocols'])) {
541 if (isset($data['protocols']['diaspora'])) {
542 $fields['network'] = Protocol::DIASPORA;
544 if (isset($data['protocols']['diaspora']['receive'])) {
545 $fields['batch'] = $data['protocols']['diaspora']['receive'];
546 } elseif (is_string($data['protocols']['diaspora'])) {
547 $fields['batch'] = $data['protocols']['diaspora'];
551 if (isset($data['protocols']['dfrn'])) {
552 $fields['network'] = Protocol::DFRN;
554 if (isset($data['protocols']['dfrn']['receive'])) {
555 $fields['batch'] = $data['protocols']['dfrn']['receive'];
556 } elseif (is_string($data['protocols']['dfrn'])) {
557 $fields['batch'] = $data['protocols']['dfrn'];
561 Diaspora::setRelayContact($server_url, $fields);
565 * Fetch server data from '/statistics.json' on the given server
567 * @param string $url URL of the given server
569 * @return array server data
571 private static function fetchStatistics(string $url)
573 $curlResult = Network::curl($url . '/statistics.json');
574 if (!$curlResult->isSuccess()) {
578 $data = json_decode($curlResult->getBody(), true);
583 $serverdata = ['detection-method' => self::DETECT_STATISTICS_JSON];
585 if (!empty($data['version'])) {
586 $serverdata['version'] = $data['version'];
587 // Version numbers on statistics.json are presented with additional info, e.g.:
588 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
589 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
592 if (!empty($data['name'])) {
593 $serverdata['site_name'] = $data['name'];
596 if (!empty($data['network'])) {
597 $serverdata['platform'] = strtolower($data['network']);
599 if ($serverdata['platform'] == 'diaspora') {
600 $serverdata['network'] = Protocol::DIASPORA;
601 } elseif ($serverdata['platform'] == 'friendica') {
602 $serverdata['network'] = Protocol::DFRN;
603 } elseif ($serverdata['platform'] == 'hubzilla') {
604 $serverdata['network'] = Protocol::ZOT;
605 } elseif ($serverdata['platform'] == 'redmatrix') {
606 $serverdata['network'] = Protocol::ZOT;
611 if (!empty($data['registrations_open'])) {
612 $serverdata['register_policy'] = Register::OPEN;
614 $serverdata['register_policy'] = Register::CLOSED;
621 * Detect server type by using the nodeinfo data
623 * @param string $url address of the server
624 * @param CurlResult $curlResult
625 * @return array Server data
626 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
628 private static function fetchNodeinfo(string $url, CurlResult $curlResult)
630 if (!$curlResult->isSuccess()) {
634 $nodeinfo = json_decode($curlResult->getBody(), true);
636 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
643 foreach ($nodeinfo['links'] as $link) {
644 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
645 Logger::info('Invalid nodeinfo format', ['url' => $url]);
648 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
649 $nodeinfo1_url = $link['href'];
650 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
651 $nodeinfo2_url = $link['href'];
655 if ($nodeinfo1_url . $nodeinfo2_url == '') {
661 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
662 if (!empty($nodeinfo2_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
663 $server = self::parseNodeinfo2($nodeinfo2_url);
666 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
667 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
668 $server = self::parseNodeinfo1($nodeinfo1_url);
677 * @param string $nodeinfo_url address of the nodeinfo path
678 * @return array Server data
679 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
681 private static function parseNodeinfo1(string $nodeinfo_url)
683 $curlResult = Network::curl($nodeinfo_url);
684 if (!$curlResult->isSuccess()) {
688 $nodeinfo = json_decode($curlResult->getBody(), true);
690 if (!is_array($nodeinfo)) {
694 $server = ['detection-method' => self::DETECT_NODEINFO_1,
695 'register_policy' => Register::CLOSED];
697 if (!empty($nodeinfo['openRegistrations'])) {
698 $server['register_policy'] = Register::OPEN;
701 if (is_array($nodeinfo['software'])) {
702 if (!empty($nodeinfo['software']['name'])) {
703 $server['platform'] = strtolower($nodeinfo['software']['name']);
706 if (!empty($nodeinfo['software']['version'])) {
707 $server['version'] = $nodeinfo['software']['version'];
708 // Version numbers on Nodeinfo are presented with additional info, e.g.:
709 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
710 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
714 if (!empty($nodeinfo['metadata']['nodeName'])) {
715 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
718 if (!empty($nodeinfo['usage']['users']['total'])) {
719 $server['registered-users'] = $nodeinfo['usage']['users']['total'];
722 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
724 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
725 $protocols[$protocol] = true;
728 if (!empty($protocols['friendica'])) {
729 $server['network'] = Protocol::DFRN;
730 } elseif (!empty($protocols['activitypub'])) {
731 $server['network'] = Protocol::ACTIVITYPUB;
732 } elseif (!empty($protocols['diaspora'])) {
733 $server['network'] = Protocol::DIASPORA;
734 } elseif (!empty($protocols['ostatus'])) {
735 $server['network'] = Protocol::OSTATUS;
736 } elseif (!empty($protocols['gnusocial'])) {
737 $server['network'] = Protocol::OSTATUS;
738 } elseif (!empty($protocols['zot'])) {
739 $server['network'] = Protocol::ZOT;
743 if (empty($server)) {
753 * @param string $nodeinfo_url address of the nodeinfo path
754 * @return array Server data
755 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
757 private static function parseNodeinfo2(string $nodeinfo_url)
759 $curlResult = Network::curl($nodeinfo_url);
760 if (!$curlResult->isSuccess()) {
764 $nodeinfo = json_decode($curlResult->getBody(), true);
766 if (!is_array($nodeinfo)) {
770 $server = ['detection-method' => self::DETECT_NODEINFO_2,
771 'register_policy' => Register::CLOSED];
773 if (!empty($nodeinfo['openRegistrations'])) {
774 $server['register_policy'] = Register::OPEN;
777 if (is_array($nodeinfo['software'])) {
778 if (!empty($nodeinfo['software']['name'])) {
779 $server['platform'] = strtolower($nodeinfo['software']['name']);
782 if (!empty($nodeinfo['software']['version'])) {
783 $server['version'] = $nodeinfo['software']['version'];
784 // Version numbers on Nodeinfo are presented with additional info, e.g.:
785 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
786 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
790 if (!empty($nodeinfo['metadata']['nodeName'])) {
791 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
794 if (!empty($nodeinfo['usage']['users']['total'])) {
795 $server['registered-users'] = $nodeinfo['usage']['users']['total'];
798 if (!empty($nodeinfo['protocols'])) {
800 foreach ($nodeinfo['protocols'] as $protocol) {
801 $protocols[$protocol] = true;
804 if (!empty($protocols['dfrn'])) {
805 $server['network'] = Protocol::DFRN;
806 } elseif (!empty($protocols['activitypub'])) {
807 $server['network'] = Protocol::ACTIVITYPUB;
808 } elseif (!empty($protocols['diaspora'])) {
809 $server['network'] = Protocol::DIASPORA;
810 } elseif (!empty($protocols['ostatus'])) {
811 $server['network'] = Protocol::OSTATUS;
812 } elseif (!empty($protocols['gnusocial'])) {
813 $server['network'] = Protocol::OSTATUS;
814 } elseif (!empty($protocols['zot'])) {
815 $server['network'] = Protocol::ZOT;
819 if (empty($server)) {
827 * Fetch server information from a 'siteinfo.json' file on the given server
829 * @param string $url URL of the given server
830 * @param array $serverdata array with server data
832 * @return array server data
834 private static function fetchSiteinfo(string $url, array $serverdata)
836 $curlResult = Network::curl($url . '/siteinfo.json');
837 if (!$curlResult->isSuccess()) {
841 $data = json_decode($curlResult->getBody(), true);
846 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
847 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
850 if (!empty($data['url'])) {
851 $serverdata['platform'] = strtolower($data['platform']);
852 $serverdata['version'] = $data['version'];
855 if (!empty($data['plugins'])) {
856 if (in_array('pubcrawl', $data['plugins'])) {
857 $serverdata['network'] = Protocol::ACTIVITYPUB;
858 } elseif (in_array('diaspora', $data['plugins'])) {
859 $serverdata['network'] = Protocol::DIASPORA;
860 } elseif (in_array('gnusoc', $data['plugins'])) {
861 $serverdata['network'] = Protocol::OSTATUS;
863 $serverdata['network'] = Protocol::ZOT;
867 if (!empty($data['site_name'])) {
868 $serverdata['site_name'] = $data['site_name'];
871 if (!empty($data['channels_total'])) {
872 $serverdata['registered-users'] = $data['channels_total'];
875 if (!empty($data['register_policy'])) {
876 switch ($data['register_policy']) {
877 case 'REGISTER_OPEN':
878 $serverdata['register_policy'] = Register::OPEN;
881 case 'REGISTER_APPROVE':
882 $serverdata['register_policy'] = Register::APPROVE;
885 case 'REGISTER_CLOSED':
887 $serverdata['register_policy'] = Register::CLOSED;
896 * Checks if the server contains a valid host meta file
898 * @param string $url URL of the given server
900 * @return boolean 'true' if the server seems to be vital
902 private static function validHostMeta(string $url)
904 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
905 $curlResult = Network::curl($url . '/.well-known/host-meta', false, ['timeout' => $xrd_timeout]);
906 if (!$curlResult->isSuccess()) {
910 $xrd = XML::parseString($curlResult->getBody());
911 if (!is_object($xrd)) {
915 $elements = XML::elementToArray($xrd);
916 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
921 foreach ($elements['xrd']['link'] as $link) {
922 // When there is more than a single "link" element, the array looks slightly different
923 if (!empty($link['@attributes'])) {
924 $link = $link['@attributes'];
927 if (empty($link['rel']) || empty($link['template'])) {
931 if ($link['rel'] == 'lrdd') {
932 // When the webfinger host is the same like the system host, it should be ok.
933 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
941 * Detect the network of the given server via their known contacts
943 * @param string $url URL of the given server
944 * @param array $serverdata array with server data
946 * @return array server data
948 private static function detectNetworkViaContacts(string $url, array $serverdata)
952 $gcontacts = DBA::select('gcontact', ['url', 'nurl'], ['server_url' => [$url, $serverdata['nurl']]]);
953 while ($gcontact = DBA::fetch($gcontacts)) {
954 $contacts[$gcontact['nurl']] = $gcontact['url'];
956 DBA::close($gcontacts);
958 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $serverdata['nurl']]]);
959 while ($apcontact = DBA::fetch($apcontacts)) {
960 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
962 DBA::close($apcontacts);
964 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $serverdata['nurl']]]);
965 while ($pcontact = DBA::fetch($pcontacts)) {
966 $contacts[$pcontact['nurl']] = $pcontact['url'];
968 DBA::close($pcontacts);
970 if (empty($contacts)) {
974 foreach ($contacts as $contact) {
975 $probed = Probe::uri($contact);
976 if (in_array($probed['network'], Protocol::FEDERATED)) {
977 $serverdata['network'] = $probed['network'];
982 $serverdata['registered-users'] = max($serverdata['registered-users'], count($contacts));
988 * Checks if the given server does have a '/poco' endpoint.
989 * This is used for the 'PortableContact' functionality,
990 * which is used by both Friendica and Hubzilla.
992 * @param string $url URL of the given server
993 * @param array $serverdata array with server data
995 * @return array server data
997 private static function checkPoCo(string $url, array $serverdata)
999 $serverdata['poco'] = '';
1001 $curlResult = Network::curl($url. '/poco');
1002 if (!$curlResult->isSuccess()) {
1006 $data = json_decode($curlResult->getBody(), true);
1011 if (!empty($data['totalResults'])) {
1012 $registeredUsers = $serverdata['registered-users'] ?? 0;
1013 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers);
1014 $serverdata['directory-type'] = self::DT_POCO;
1015 $serverdata['poco'] = $url . '/poco';
1022 * Checks if the given server does have a Mastodon style directory endpoint.
1024 * @param string $url URL of the given server
1025 * @param array $serverdata array with server data
1027 * @return array server data
1029 public static function checkMastodonDirectory(string $url, array $serverdata)
1031 $curlResult = Network::curl($url . '/api/v1/directory?limit=1');
1032 if (!$curlResult->isSuccess()) {
1036 $data = json_decode($curlResult->getBody(), true);
1041 if (count($data) == 1) {
1042 $serverdata['directory-type'] = self::DT_MASTODON;
1049 * Detects the version number of a given server when it was a NextCloud installation
1051 * @param string $url URL of the given server
1052 * @param array $serverdata array with server data
1054 * @return array server data
1056 private static function detectNextcloud(string $url, array $serverdata)
1058 $curlResult = Network::curl($url . '/status.php');
1059 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1063 $data = json_decode($curlResult->getBody(), true);
1068 if (!empty($data['version'])) {
1069 $serverdata['platform'] = 'nextcloud';
1070 $serverdata['version'] = $data['version'];
1071 $serverdata['network'] = Protocol::ACTIVITYPUB;
1073 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1074 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1082 * Detects data from a given server url if it was a mastodon alike system
1084 * @param string $url URL of the given server
1085 * @param array $serverdata array with server data
1087 * @return array server data
1089 private static function detectMastodonAlikes(string $url, array $serverdata)
1091 $curlResult = Network::curl($url . '/api/v1/instance');
1092 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1096 $data = json_decode($curlResult->getBody(), true);
1101 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1102 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1105 if (!empty($data['version'])) {
1106 $serverdata['platform'] = 'mastodon';
1107 $serverdata['version'] = $data['version'] ?? '';
1108 $serverdata['network'] = Protocol::ACTIVITYPUB;
1111 if (!empty($data['title'])) {
1112 $serverdata['site_name'] = $data['title'];
1115 if (!empty($data['title']) && empty($serverdata['platform']) && empty($serverdata['network'])) {
1116 $serverdata['platform'] = 'mastodon';
1117 $serverdata['network'] = Protocol::ACTIVITYPUB;
1120 if (!empty($data['description'])) {
1121 $serverdata['info'] = trim($data['description']);
1124 if (!empty($data['stats']['user_count'])) {
1125 $serverdata['registered-users'] = $data['stats']['user_count'];
1128 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1129 $serverdata['platform'] = strtolower($matches[1]);
1130 $serverdata['version'] = $matches[2];
1133 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1134 $serverdata['platform'] = 'pleroma';
1135 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1138 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1139 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1140 $serverdata['platform'] = 'pleroma';
1147 * Detects data from typical Hubzilla endpoints
1149 * @param string $url URL of the given server
1150 * @param array $serverdata array with server data
1152 * @return array server data
1154 private static function detectHubzilla(string $url, array $serverdata)
1156 $curlResult = Network::curl($url . '/api/statusnet/config.json');
1157 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1161 $data = json_decode($curlResult->getBody(), true);
1162 if (empty($data) || empty($data['site'])) {
1166 if (!empty($data['site']['name'])) {
1167 $serverdata['site_name'] = $data['site']['name'];
1170 if (!empty($data['site']['platform'])) {
1171 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1172 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1173 $serverdata['network'] = Protocol::ZOT;
1176 if (!empty($data['site']['hubzilla'])) {
1177 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1178 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1179 $serverdata['network'] = Protocol::ZOT;
1182 if (!empty($data['site']['redmatrix'])) {
1183 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1184 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1185 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1186 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1189 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1190 $serverdata['network'] = Protocol::ZOT;
1194 $inviteonly = false;
1197 if (!empty($data['site']['closed'])) {
1198 $closed = self::toBoolean($data['site']['closed']);
1201 if (!empty($data['site']['private'])) {
1202 $private = self::toBoolean($data['site']['private']);
1205 if (!empty($data['site']['inviteonly'])) {
1206 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1209 if (!$closed && !$private and $inviteonly) {
1210 $serverdata['register_policy'] = Register::APPROVE;
1211 } elseif (!$closed && !$private) {
1212 $serverdata['register_policy'] = Register::OPEN;
1214 $serverdata['register_policy'] = Register::CLOSED;
1217 if (!empty($serverdata['network']) && in_array($serverdata['detection-method'],
1218 [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1219 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1226 * Converts input value to a boolean value
1228 * @param string|integer $val
1232 private static function toBoolean($val)
1234 if (($val == 'true') || ($val == 1)) {
1236 } elseif (($val == 'false') || ($val == 0)) {
1244 * Detect if the URL belongs to a GNU Social server
1246 * @param string $url URL of the given server
1247 * @param array $serverdata array with server data
1249 * @return array server data
1251 private static function detectGNUSocial(string $url, array $serverdata)
1253 // Test for GNU Social
1254 $curlResult = Network::curl($url . '/api/gnusocial/version.json');
1255 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1256 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1257 $serverdata['platform'] = 'gnusocial';
1258 // Remove junk that some GNU Social servers return
1259 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1260 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1261 $serverdata['version'] = trim($serverdata['version'], '"');
1262 $serverdata['network'] = Protocol::OSTATUS;
1264 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1265 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1271 // Test for Statusnet
1272 $curlResult = Network::curl($url . '/api/statusnet/version.json');
1273 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1274 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1276 // Remove junk that some GNU Social servers return
1277 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1278 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1279 $serverdata['version'] = trim($serverdata['version'], '"');
1281 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1282 $serverdata['platform'] = 'pleroma';
1283 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1284 $serverdata['network'] = Protocol::ACTIVITYPUB;
1286 $serverdata['platform'] = 'statusnet';
1287 $serverdata['network'] = Protocol::OSTATUS;
1290 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1291 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1299 * Detect if the URL belongs to a Friendica server
1301 * @param string $url URL of the given server
1302 * @param array $serverdata array with server data
1304 * @return array server data
1306 private static function detectFriendica(string $url, array $serverdata)
1308 $curlResult = Network::curl($url . '/friendica/json');
1309 if (!$curlResult->isSuccess()) {
1310 $curlResult = Network::curl($url . '/friendika/json');
1312 $platform = 'Friendika';
1315 $platform = 'Friendica';
1318 if (!$curlResult->isSuccess()) {
1322 $data = json_decode($curlResult->getBody(), true);
1323 if (empty($data) || empty($data['version'])) {
1327 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1328 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1331 $serverdata['network'] = Protocol::DFRN;
1332 $serverdata['version'] = $data['version'];
1334 if (!empty($data['no_scrape_url'])) {
1335 $serverdata['noscrape'] = $data['no_scrape_url'];
1338 if (!empty($data['site_name'])) {
1339 $serverdata['site_name'] = $data['site_name'];
1342 if (!empty($data['info'])) {
1343 $serverdata['info'] = trim($data['info']);
1346 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1347 switch ($register_policy) {
1348 case 'REGISTER_OPEN':
1349 $serverdata['register_policy'] = Register::OPEN;
1352 case 'REGISTER_APPROVE':
1353 $serverdata['register_policy'] = Register::APPROVE;
1356 case 'REGISTER_CLOSED':
1357 case 'REGISTER_INVITATION':
1358 $serverdata['register_policy'] = Register::CLOSED;
1361 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
1362 $serverdata['register_policy'] = Register::CLOSED;
1366 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
1372 * Analyses the landing page of a given server for hints about type and system of that server
1374 * @param object $curlResult result of curl execution
1375 * @param array $serverdata array with server data
1376 * @param string $url Server URL
1378 * @return array server data
1380 private static function analyseRootBody($curlResult, array $serverdata, string $url)
1382 $doc = new DOMDocument();
1383 @$doc->loadHTML($curlResult->getBody());
1384 $xpath = new DOMXPath($doc);
1386 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
1387 if (!empty($title)) {
1388 $serverdata['site_name'] = $title;
1391 $list = $xpath->query('//meta[@name]');
1393 foreach ($list as $node) {
1395 if ($node->attributes->length) {
1396 foreach ($node->attributes as $attribute) {
1397 $value = trim($attribute->value);
1398 if (empty($value)) {
1402 $attr[$attribute->name] = $value;
1405 if (empty($attr['name']) || empty($attr['content'])) {
1410 if ($attr['name'] == 'description') {
1411 $serverdata['info'] = $attr['content'];
1414 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
1415 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad'])) {
1416 $serverdata['platform'] = strtolower($attr['content']);
1417 if (in_array($attr['content'], ['Misskey', 'Write.as'])) {
1418 $serverdata['network'] = Protocol::ACTIVITYPUB;
1421 if (($attr['name'] == 'generator') && (empty($serverdata['platform']) || (substr(strtolower($attr['content']), 0, 9) == 'wordpress'))) {
1422 $serverdata['platform'] = strtolower($attr['content']);
1423 $version_part = explode(' ', $attr['content']);
1425 if (count($version_part) == 2) {
1426 if (in_array($version_part[0], ['WordPress'])) {
1427 $serverdata['platform'] = strtolower($version_part[0]);
1428 $serverdata['version'] = $version_part[1];
1430 // We still do need a reliable test if some AP plugin is activated
1431 if (DBA::exists('apcontact', ['baseurl' => $url])) {
1432 $serverdata['network'] = Protocol::ACTIVITYPUB;
1434 $serverdata['network'] = Protocol::FEED;
1437 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1438 $serverdata['detection-method'] = self::DETECT_BODY;
1441 if (in_array($version_part[0], ['Friendika', 'Friendica'])) {
1442 $serverdata['platform'] = strtolower($version_part[0]);
1443 $serverdata['version'] = $version_part[1];
1444 $serverdata['network'] = Protocol::DFRN;
1450 $list = $xpath->query('//meta[@property]');
1452 foreach ($list as $node) {
1454 if ($node->attributes->length) {
1455 foreach ($node->attributes as $attribute) {
1456 $value = trim($attribute->value);
1457 if (empty($value)) {
1461 $attr[$attribute->name] = $value;
1464 if (empty($attr['property']) || empty($attr['content'])) {
1469 if ($attr['property'] == 'og:site_name') {
1470 $serverdata['site_name'] = $attr['content'];
1473 if ($attr['property'] == 'og:description') {
1474 $serverdata['info'] = $attr['content'];
1477 if ($attr['property'] == 'og:platform') {
1478 $serverdata['platform'] = strtolower($attr['content']);
1480 if (in_array($attr['content'], ['PeerTube'])) {
1481 $serverdata['network'] = Protocol::ACTIVITYPUB;
1485 if ($attr['property'] == 'generator') {
1486 $serverdata['platform'] = strtolower($attr['content']);
1488 if (in_array($attr['content'], ['hubzilla'])) {
1489 // We later check which compatible protocol modules are loaded.
1490 $serverdata['network'] = Protocol::ZOT;
1495 if (!empty($serverdata['network']) && ($serverdata['detection-method'] == self::DETECT_MANUAL)) {
1496 $serverdata['detection-method'] = self::DETECT_BODY;
1503 * Analyses the header data of a given server for hints about type and system of that server
1505 * @param object $curlResult result of curl execution
1506 * @param array $serverdata array with server data
1508 * @return array server data
1510 private static function analyseRootHeader($curlResult, array $serverdata)
1512 if ($curlResult->getHeader('server') == 'Mastodon') {
1513 $serverdata['platform'] = 'mastodon';
1514 $serverdata['network'] = Protocol::ACTIVITYPUB;
1515 } elseif ($curlResult->inHeader('x-diaspora-version')) {
1516 $serverdata['platform'] = 'diaspora';
1517 $serverdata['network'] = Protocol::DIASPORA;
1518 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version');
1519 } elseif ($curlResult->inHeader('x-friendica-version')) {
1520 $serverdata['platform'] = 'friendica';
1521 $serverdata['network'] = Protocol::DFRN;
1522 $serverdata['version'] = $curlResult->getHeader('x-friendica-version');
1527 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1528 $serverdata['detection-method'] = self::DETECT_HEADER;
1535 * Test if the body contains valid content
1537 * @param string $body
1540 private static function invalidBody(string $body)
1542 // Currently we only test for a HTML element.
1543 // Possibly we enhance this in the future.
1544 return !strpos($body, '>');
1548 * Update the user directory of a given gserver record
1550 * @param array $gserver gserver record
1552 public static function updateDirectory(array $gserver)
1554 /// @todo Add Mastodon API directory
1556 if (!empty($gserver['poco'])) {
1557 PortableContact::discoverSingleServer($gserver['id']);
1562 * Update GServer entries
1564 public static function discover()
1566 // Update the server list
1567 self::discoverFederation();
1571 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
1573 if ($requery_days == 0) {
1577 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
1579 $gservers = DBA::p("SELECT `id`, `url`, `nurl`, `network`, `poco`
1581 WHERE `last_contact` >= `last_failure`
1583 AND `last_poco_query` < ?
1584 ORDER BY RAND()", $last_update
1587 while ($gserver = DBA::fetch($gservers)) {
1588 if (!GServer::check($gserver['url'], $gserver['network'])) {
1589 // The server is not reachable? Okay, then we will try it later
1590 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1591 DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);
1595 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1596 Worker::add(PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
1598 if (--$no_of_queries == 0) {
1603 DBA::close($gservers);
1607 * Discover federated servers
1609 private static function discoverFederation()
1611 $last = DI::config()->get('poco', 'last_federation_discovery');
1614 $next = $last + (24 * 60 * 60);
1616 if ($next > time()) {
1621 // Discover federated servers
1622 $curlResult = Network::fetchUrl("http://the-federation.info/pods.json");
1624 if (!empty($curlResult)) {
1625 $servers = json_decode($curlResult, true);
1627 if (!empty($servers['pods'])) {
1628 foreach ($servers['pods'] as $server) {
1629 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
1630 Worker::add(PRIORITY_LOW, 'UpdateGServer', 'https://' . $server['host'], true);
1635 // Disvover Mastodon servers
1636 $accesstoken = DI::config()->get('system', 'instances_social_key');
1638 if (!empty($accesstoken)) {
1639 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1640 $header = ['Authorization: Bearer '.$accesstoken];
1641 $curlResult = Network::curl($api, false, ['headers' => $header]);
1642 if ($curlResult->isSuccess()) {
1643 $servers = json_decode($curlResult->getBody(), true);
1645 foreach ($servers['instances'] as $server) {
1646 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
1647 Worker::add(PRIORITY_LOW, 'UpdateGServer', $url);
1652 DI::config()->set('poco', 'last_federation_discovery', time());