3 * @copyright Copyright (C) 2010-2021, the Friendica project
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;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\System;
30 use Friendica\Core\Worker;
31 use Friendica\Database\Database;
32 use Friendica\Database\DBA;
34 use Friendica\Module\Register;
35 use Friendica\Network\HTTPClientOptions;
36 use Friendica\Network\IHTTPResult;
37 use Friendica\Protocol\Relay;
38 use Friendica\Util\DateTimeFormat;
39 use Friendica\Util\Network;
40 use Friendica\Util\Strings;
41 use Friendica\Util\XML;
44 * This class handles GServer related functions
51 const DT_MASTODON = 2;
53 // Methods to detect server types
55 // Non endpoint specific methods
56 const DETECT_MANUAL = 0;
57 const DETECT_HEADER = 1;
58 const DETECT_BODY = 2;
60 // Implementation specific endpoints
61 const DETECT_FRIENDIKA = 10;
62 const DETECT_FRIENDICA = 11;
63 const DETECT_STATUSNET = 12;
64 const DETECT_GNUSOCIAL = 13;
65 const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix
66 const DETECT_SITEINFO_JSON = 15; // Newer Hubzilla
67 const DETECT_MASTODON_API = 16;
68 const DETECT_STATUS_PHP = 17; // Nextcloud
69 const DETECT_V1_CONFIG = 18;
71 // Standardized endpoints
72 const DETECT_STATISTICS_JSON = 100;
73 const DETECT_NODEINFO_1 = 101;
74 const DETECT_NODEINFO_2 = 102;
77 * Check for the existance of a server and adds it in the background if not existant
80 * @param boolean $only_nodeinfo
83 public static function add(string $url, bool $only_nodeinfo = false)
85 if (self::getID($url, false)) {
89 Worker::add(PRIORITY_LOW, 'UpdateGServer', $url, $only_nodeinfo);
93 * Get the ID for the given server URL
96 * @param boolean $no_check Don't check if the server hadn't been found
97 * @return int gserver id
99 public static function getID(string $url, bool $no_check = false)
105 $url = self::cleanURL($url);
107 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
108 if (DBA::isResult($gserver)) {
109 Logger::info('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
110 return $gserver['id'];
113 if ($no_check || !self::check($url)) {
117 return self::getID($url, true);
121 * Checks if the given server is reachable
123 * @param string $profile URL of the given profile
124 * @param string $server URL of the given server (If empty, taken from profile)
125 * @param string $network Network value that is used, when detection failed
126 * @param boolean $force Force an update.
128 * @return boolean 'true' if server seems vital
130 public static function reachable(string $profile, string $server = '', string $network = '', bool $force = false)
133 $contact = Contact::getByURL($profile, null, ['baseurl']);
134 if (!empty($contact['baseurl'])) {
135 $server = $contact['baseurl'];
143 return self::check($server, $network, $force);
146 public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '')
148 // On successful contact process check again next week
150 return DateTimeFormat::utc('now +7 day');
153 $now = strtotime(DateTimeFormat::utcNow());
155 if ($created > $last_contact) {
156 $contact_time = strtotime($created);
158 $contact_time = strtotime($last_contact);
161 // If the last contact was less than 6 hours before then try again in 6 hours
162 if (($now - $contact_time) < (60 * 60 * 6)) {
163 return DateTimeFormat::utc('now +6 hour');
166 // If the last contact was less than 12 hours before then try again in 12 hours
167 if (($now - $contact_time) < (60 * 60 * 12)) {
168 return DateTimeFormat::utc('now +12 hour');
171 // If the last contact was less than 24 hours before then try tomorrow again
172 if (($now - $contact_time) < (60 * 60 * 24)) {
173 return DateTimeFormat::utc('now +1 day');
176 // If the last contact was less than a week before then try again in a week
177 if (($now - $contact_time) < (60 * 60 * 24 * 7)) {
178 return DateTimeFormat::utc('now +1 week');
181 // If the last contact was less than two weeks before then try again in two week
182 if (($now - $contact_time) < (60 * 60 * 24 * 14)) {
183 return DateTimeFormat::utc('now +2 week');
186 // If the last contact was less than a month before then try again in a month
187 if (($now - $contact_time) < (60 * 60 * 24 * 30)) {
188 return DateTimeFormat::utc('now +1 month');
191 // The system hadn't been successul contacted for more than a month, so try again in three months
192 return DateTimeFormat::utc('now +3 month');
196 * Checks the state of the given server.
198 * @param string $server_url URL of the given server
199 * @param string $network Network value that is used, when detection failed
200 * @param boolean $force Force an update.
201 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
203 * @return boolean 'true' if server seems vital
205 public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false)
207 $server_url = self::cleanURL($server_url);
208 if ($server_url == '') {
212 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
213 if (DBA::isResult($gserver)) {
214 if ($gserver['created'] <= DBA::NULL_DATETIME) {
215 $fields = ['created' => DateTimeFormat::utcNow()];
216 $condition = ['nurl' => Strings::normaliseLink($server_url)];
217 DBA::update('gserver', $fields, $condition);
220 if (!$force && (strtotime($gserver['next_contact']) > time())) {
221 Logger::info('No update needed', ['server' => $server_url]);
222 return (!$gserver['failed']);
224 Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]);
226 Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
229 return self::detect($server_url, $network, $only_nodeinfo);
233 * Set failed server status
237 public static function setFailure(string $url)
239 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($url)]);
240 if (DBA::isResult($gserver)) {
241 $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
242 DBA::update('gserver', ['failed' => true, 'last_failure' => DateTimeFormat::utcNow(),
243 'next_contact' => $next_update, 'detection-method' => null],
244 ['nurl' => Strings::normaliseLink($url)]);
245 Logger::info('Set failed status for existing server', ['url' => $url]);
248 DBA::insert('gserver', ['url' => $url, 'nurl' => Strings::normaliseLink($url),
249 'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
250 'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
251 Logger::info('Set failed status for new server', ['url' => $url]);
255 * Remove unwanted content from the given URL
258 * @return string cleaned URL
260 public static function cleanURL(string $url)
262 $url = trim($url, '/');
263 $url = str_replace('/index.php', '', $url);
265 $urlparts = parse_url($url);
266 unset($urlparts['user']);
267 unset($urlparts['pass']);
268 unset($urlparts['query']);
269 unset($urlparts['fragment']);
270 return Network::unparseURL($urlparts);
274 * Return the base URL
277 * @return string base URL
279 private static function getBaseURL(string $url)
281 $urlparts = parse_url(self::cleanURL($url));
282 unset($urlparts['path']);
283 return Network::unparseURL($urlparts);
287 * Detect server data (type, protocol, version number, ...)
288 * The detected data is then updated or inserted in the gserver table.
290 * @param string $url URL of the given server
291 * @param string $network Network value that is used, when detection failed
292 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
294 * @return boolean 'true' if server could be detected
296 public static function detect(string $url, string $network = '', bool $only_nodeinfo = false)
298 Logger::info('Detect server type', ['server' => $url]);
299 $serverdata = ['detection-method' => self::DETECT_MANUAL];
301 $original_url = $url;
303 // Remove URL content that is not supposed to exist for a server url
304 $url = self::cleanURL($url);
307 $baseurl = self::getBaseURL($url);
309 // If the URL missmatches, then we mark the old entry as failure
310 if ($url != $original_url) {
311 /// @todo What to do with "next_contact" here?
312 DBA::update('gserver', ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()],
313 ['nurl' => Strings::normaliseLink($original_url)]);
316 // When a nodeinfo is present, we don't need to dig further
317 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
318 $curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', [HTTPClientOptions::TIMEOUT => $xrd_timeout]);
319 if ($curlResult->isTimeout()) {
320 self::setFailure($url);
324 // On a redirect follow the new host but mark the old one as failure
325 if ($curlResult->isSuccess() && (parse_url($url, PHP_URL_HOST) != parse_url($curlResult->getRedirectUrl(), PHP_URL_HOST))) {
326 $curlResult = DI::httpClient()->get($url, [HTTPClientOptions::TIMEOUT => $xrd_timeout]);
327 if (parse_url($url, PHP_URL_HOST) != parse_url($curlResult->getRedirectUrl(), PHP_URL_HOST)) {
328 Logger::info('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $curlResult->getRedirectUrl()]);
329 self::setFailure($url);
330 self::detect($curlResult->getRedirectUrl(), $network, $only_nodeinfo);
335 $nodeinfo = self::fetchNodeinfo($url, $curlResult);
336 if ($only_nodeinfo && empty($nodeinfo)) {
337 Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
338 self::setFailure($url);
342 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
343 if (empty($nodeinfo)) {
344 $nodeinfo = self::fetchStatistics($url);
347 // If that didn't work out well, we use some protocol specific endpoints
348 // For Friendica and Zot based networks we have to dive deeper to reveal more details
349 if (empty($nodeinfo['network']) || in_array($nodeinfo['network'], [Protocol::DFRN, Protocol::ZOT])) {
350 if (!empty($nodeinfo['detection-method'])) {
351 $serverdata['detection-method'] = $nodeinfo['detection-method'];
354 // Fetch the landing page, possibly it reveals some data
355 if (empty($nodeinfo['network'])) {
356 if ($baseurl == $url) {
357 $basedata = $serverdata;
359 $basedata = ['detection-method' => self::DETECT_MANUAL];
362 $curlResult = DI::httpClient()->get($baseurl, [HTTPClientOptions::TIMEOUT => $xrd_timeout]);
363 if ($curlResult->isSuccess()) {
364 if ((parse_url($baseurl, PHP_URL_HOST) != parse_url($curlResult->getRedirectUrl(), PHP_URL_HOST))) {
365 Logger::info('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $curlResult->getRedirectUrl()]);
366 self::setFailure($url);
367 self::detect($curlResult->getRedirectUrl(), $network, $only_nodeinfo);
371 $basedata = self::analyseRootHeader($curlResult, $basedata);
372 $basedata = self::analyseRootBody($curlResult, $basedata, $baseurl);
375 if (!$curlResult->isSuccess() || empty($curlResult->getBody()) || self::invalidBody($curlResult->getBody())) {
376 self::setFailure($url);
380 if ($baseurl == $url) {
381 $serverdata = $basedata;
383 // When the base path doesn't seem to contain a social network we try the complete path.
384 // Most detectable system have to be installed in the root directory.
385 // We checked the base to avoid false positives.
386 $curlResult = DI::httpClient()->get($url, [HTTPClientOptions::TIMEOUT => $xrd_timeout]);
387 if ($curlResult->isSuccess()) {
388 $urldata = self::analyseRootHeader($curlResult, $serverdata);
389 $urldata = self::analyseRootBody($curlResult, $urldata, $url);
391 $comparebase = $basedata;
392 unset($comparebase['info']);
393 unset($comparebase['site_name']);
394 $compareurl = $urldata;
395 unset($compareurl['info']);
396 unset($compareurl['site_name']);
398 // We assume that no one will install the identical system in the root and a subfolder
399 if (!empty(array_diff($comparebase, $compareurl))) {
400 $serverdata = $urldata;
406 if (empty($serverdata['network']) || ($serverdata['network'] == Protocol::ACTIVITYPUB)) {
407 $serverdata = self::detectMastodonAlikes($url, $serverdata);
410 // All following checks are done for systems that always have got a "host-meta" endpoint.
411 // With this check we don't have to waste time and ressources for dead systems.
412 // Also this hopefully prevents us from receiving abuse messages.
413 if (empty($serverdata['network']) && !self::validHostMeta($url)) {
414 self::setFailure($url);
418 if (empty($serverdata['network']) || in_array($serverdata['network'], [Protocol::DFRN, Protocol::ACTIVITYPUB])) {
419 $serverdata = self::detectFriendica($url, $serverdata);
422 // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
423 if (empty($serverdata['network']) || ($serverdata['network'] == Protocol::ZOT)) {
424 $serverdata = self::fetchSiteinfo($url, $serverdata);
427 // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations
428 if (empty($serverdata['network'])) {
429 $serverdata = self::detectHubzilla($url, $serverdata);
432 if (empty($serverdata['network']) || in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_BODY])) {
433 $serverdata = self::detectPeertube($url, $serverdata);
436 if (empty($serverdata['network'])) {
437 $serverdata = self::detectNextcloud($url, $serverdata);
440 if (empty($serverdata['network'])) {
441 $serverdata = self::detectGNUSocial($url, $serverdata);
444 $serverdata = array_merge($nodeinfo, $serverdata);
446 $serverdata = $nodeinfo;
449 // Detect the directory type
450 $serverdata['directory-type'] = self::DT_NONE;
451 $serverdata = self::checkPoCo($url, $serverdata);
452 $serverdata = self::checkMastodonDirectory($url, $serverdata);
454 // We can't detect the network type. Possibly it is some system that we don't know yet
455 if (empty($serverdata['network'])) {
456 $serverdata['network'] = Protocol::PHANTOM;
459 // When we hadn't been able to detect the network type, we use the hint from the parameter
460 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
461 $serverdata['network'] = $network;
464 $serverdata['url'] = $url;
465 $serverdata['nurl'] = Strings::normaliseLink($url);
467 // We take the highest number that we do find
468 $registeredUsers = $serverdata['registered-users'] ?? 0;
470 // On an active server there has to be at least a single user
471 if (($serverdata['network'] != Protocol::PHANTOM) && ($registeredUsers == 0)) {
472 $registeredUsers = 1;
475 if ($serverdata['network'] == Protocol::PHANTOM) {
476 $serverdata['registered-users'] = max($registeredUsers, 1);
477 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
480 $serverdata['next_contact'] = self::getNextUpdateDate(true);
482 $serverdata['last_contact'] = DateTimeFormat::utcNow();
483 $serverdata['failed'] = false;
485 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
486 if (!DBA::isResult($gserver)) {
487 $serverdata['created'] = DateTimeFormat::utcNow();
488 $ret = DBA::insert('gserver', $serverdata);
489 $id = DBA::lastInsertId();
491 // Don't override the network with 'unknown' when there had been a valid entry before
492 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($gserver['network'])) {
493 unset($serverdata['network']);
496 $ret = DBA::update('gserver', $serverdata, ['nurl' => $serverdata['nurl']]);
497 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
498 if (DBA::isResult($gserver)) {
499 $id = $gserver['id'];
503 if (!empty($serverdata['network']) && !empty($id) && ($serverdata['network'] != Protocol::PHANTOM)) {
504 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
505 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id]);
506 $max_users = max($apcontacts, $contacts, $registeredUsers, 1);
507 if ($max_users > $registeredUsers) {
508 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
509 DBA::update('gserver', ['registered-users' => $max_users], ['id' => $id]);
513 if (!empty($serverdata['network']) && in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
514 self::discoverRelay($url);
521 * Fetch relay data from a given server url
523 * @param string $server_url address of the server
524 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
526 private static function discoverRelay(string $server_url)
528 Logger::info('Discover relay data', ['server' => $server_url]);
530 $curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay');
531 if (!$curlResult->isSuccess()) {
535 $data = json_decode($curlResult->getBody(), true);
536 if (!is_array($data)) {
540 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
541 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
543 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
545 $data['subscribe'] = false;
549 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
550 if (!DBA::isResult($gserver)) {
554 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
555 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
556 DBA::update('gserver', $fields, ['id' => $gserver['id']]);
559 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
561 if ($data['scope'] == 'tags') {
564 foreach ($data['tags'] as $tag) {
565 $tag = mb_strtolower($tag);
566 if (strlen($tag) < 100) {
571 foreach ($tags as $tag) {
572 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
576 // Create or update the relay contact
578 if (isset($data['protocols'])) {
579 if (isset($data['protocols']['diaspora'])) {
580 $fields['network'] = Protocol::DIASPORA;
582 if (isset($data['protocols']['diaspora']['receive'])) {
583 $fields['batch'] = $data['protocols']['diaspora']['receive'];
584 } elseif (is_string($data['protocols']['diaspora'])) {
585 $fields['batch'] = $data['protocols']['diaspora'];
589 if (isset($data['protocols']['dfrn'])) {
590 $fields['network'] = Protocol::DFRN;
592 if (isset($data['protocols']['dfrn']['receive'])) {
593 $fields['batch'] = $data['protocols']['dfrn']['receive'];
594 } elseif (is_string($data['protocols']['dfrn'])) {
595 $fields['batch'] = $data['protocols']['dfrn'];
599 if (isset($data['protocols']['activitypub'])) {
600 $fields['network'] = Protocol::ACTIVITYPUB;
602 if (!empty($data['protocols']['activitypub']['actor'])) {
603 $fields['url'] = $data['protocols']['activitypub']['actor'];
605 if (!empty($data['protocols']['activitypub']['receive'])) {
606 $fields['batch'] = $data['protocols']['activitypub']['receive'];
611 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
613 Relay::updateContact($gserver, $fields);
617 * Fetch server data from '/statistics.json' on the given server
619 * @param string $url URL of the given server
621 * @return array server data
623 private static function fetchStatistics(string $url)
625 $curlResult = DI::httpClient()->get($url . '/statistics.json');
626 if (!$curlResult->isSuccess()) {
630 $data = json_decode($curlResult->getBody(), true);
635 $serverdata = ['detection-method' => self::DETECT_STATISTICS_JSON];
637 if (!empty($data['version'])) {
638 $serverdata['version'] = $data['version'];
639 // Version numbers on statistics.json are presented with additional info, e.g.:
640 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
641 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
644 if (!empty($data['name'])) {
645 $serverdata['site_name'] = $data['name'];
648 if (!empty($data['network'])) {
649 $serverdata['platform'] = strtolower($data['network']);
651 if ($serverdata['platform'] == 'diaspora') {
652 $serverdata['network'] = Protocol::DIASPORA;
653 } elseif ($serverdata['platform'] == 'friendica') {
654 $serverdata['network'] = Protocol::DFRN;
655 } elseif ($serverdata['platform'] == 'hubzilla') {
656 $serverdata['network'] = Protocol::ZOT;
657 } elseif ($serverdata['platform'] == 'redmatrix') {
658 $serverdata['network'] = Protocol::ZOT;
663 if (!empty($data['registrations_open'])) {
664 $serverdata['register_policy'] = Register::OPEN;
666 $serverdata['register_policy'] = Register::CLOSED;
673 * Detect server type by using the nodeinfo data
675 * @param string $url address of the server
676 * @param IHTTPResult $httpResult
678 * @return array Server data
679 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
681 private static function fetchNodeinfo(string $url, IHTTPResult $httpResult)
683 if (!$httpResult->isSuccess()) {
687 $nodeinfo = json_decode($httpResult->getBody(), true);
689 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
696 foreach ($nodeinfo['links'] as $link) {
697 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
698 Logger::info('Invalid nodeinfo format', ['url' => $url]);
701 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
702 $nodeinfo1_url = $link['href'];
703 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
704 $nodeinfo2_url = $link['href'];
708 if ($nodeinfo1_url . $nodeinfo2_url == '') {
714 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
715 if (!empty($nodeinfo2_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
716 $server = self::parseNodeinfo2($nodeinfo2_url);
719 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
720 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
721 $server = self::parseNodeinfo1($nodeinfo1_url);
730 * @param string $nodeinfo_url address of the nodeinfo path
731 * @return array Server data
732 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
734 private static function parseNodeinfo1(string $nodeinfo_url)
736 $curlResult = DI::httpClient()->get($nodeinfo_url);
738 if (!$curlResult->isSuccess()) {
742 $nodeinfo = json_decode($curlResult->getBody(), true);
744 if (!is_array($nodeinfo)) {
748 $server = ['detection-method' => self::DETECT_NODEINFO_1,
749 'register_policy' => Register::CLOSED];
751 if (!empty($nodeinfo['openRegistrations'])) {
752 $server['register_policy'] = Register::OPEN;
755 if (is_array($nodeinfo['software'])) {
756 if (!empty($nodeinfo['software']['name'])) {
757 $server['platform'] = strtolower($nodeinfo['software']['name']);
760 if (!empty($nodeinfo['software']['version'])) {
761 $server['version'] = $nodeinfo['software']['version'];
762 // Version numbers on Nodeinfo are presented with additional info, e.g.:
763 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
764 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
768 if (!empty($nodeinfo['metadata']['nodeName'])) {
769 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
772 if (!empty($nodeinfo['usage']['users']['total'])) {
773 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
776 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
778 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
779 $protocols[$protocol] = true;
782 if (!empty($protocols['friendica'])) {
783 $server['network'] = Protocol::DFRN;
784 } elseif (!empty($protocols['activitypub'])) {
785 $server['network'] = Protocol::ACTIVITYPUB;
786 } elseif (!empty($protocols['diaspora'])) {
787 $server['network'] = Protocol::DIASPORA;
788 } elseif (!empty($protocols['ostatus'])) {
789 $server['network'] = Protocol::OSTATUS;
790 } elseif (!empty($protocols['gnusocial'])) {
791 $server['network'] = Protocol::OSTATUS;
792 } elseif (!empty($protocols['zot'])) {
793 $server['network'] = Protocol::ZOT;
797 if (empty($server)) {
807 * @see https://git.feneas.org/jaywink/nodeinfo2
808 * @param string $nodeinfo_url address of the nodeinfo path
809 * @return array Server data
810 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
812 private static function parseNodeinfo2(string $nodeinfo_url)
814 $curlResult = DI::httpClient()->get($nodeinfo_url);
815 if (!$curlResult->isSuccess()) {
819 $nodeinfo = json_decode($curlResult->getBody(), true);
821 if (!is_array($nodeinfo)) {
825 $server = ['detection-method' => self::DETECT_NODEINFO_2,
826 'register_policy' => Register::CLOSED];
828 if (!empty($nodeinfo['openRegistrations'])) {
829 $server['register_policy'] = Register::OPEN;
832 if (is_array($nodeinfo['software'])) {
833 if (!empty($nodeinfo['software']['name'])) {
834 $server['platform'] = strtolower($nodeinfo['software']['name']);
837 if (!empty($nodeinfo['software']['version'])) {
838 $server['version'] = $nodeinfo['software']['version'];
839 // Version numbers on Nodeinfo are presented with additional info, e.g.:
840 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
841 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
845 if (!empty($nodeinfo['metadata']['nodeName'])) {
846 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
849 if (!empty($nodeinfo['usage']['users']['total'])) {
850 $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
853 if (!empty($nodeinfo['protocols'])) {
855 foreach ($nodeinfo['protocols'] as $protocol) {
856 if (is_string($protocol)) {
857 $protocols[$protocol] = true;
861 if (!empty($protocols['dfrn'])) {
862 $server['network'] = Protocol::DFRN;
863 } elseif (!empty($protocols['activitypub'])) {
864 $server['network'] = Protocol::ACTIVITYPUB;
865 } elseif (!empty($protocols['diaspora'])) {
866 $server['network'] = Protocol::DIASPORA;
867 } elseif (!empty($protocols['ostatus'])) {
868 $server['network'] = Protocol::OSTATUS;
869 } elseif (!empty($protocols['gnusocial'])) {
870 $server['network'] = Protocol::OSTATUS;
871 } elseif (!empty($protocols['zot'])) {
872 $server['network'] = Protocol::ZOT;
876 if (empty($server)) {
884 * Fetch server information from a 'siteinfo.json' file on the given server
886 * @param string $url URL of the given server
887 * @param array $serverdata array with server data
889 * @return array server data
891 private static function fetchSiteinfo(string $url, array $serverdata)
893 $curlResult = DI::httpClient()->get($url . '/siteinfo.json');
894 if (!$curlResult->isSuccess()) {
898 $data = json_decode($curlResult->getBody(), true);
903 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
904 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
907 if (!empty($data['url'])) {
908 $serverdata['platform'] = strtolower($data['platform']);
909 $serverdata['version'] = $data['version'];
912 if (!empty($data['plugins'])) {
913 if (in_array('pubcrawl', $data['plugins'])) {
914 $serverdata['network'] = Protocol::ACTIVITYPUB;
915 } elseif (in_array('diaspora', $data['plugins'])) {
916 $serverdata['network'] = Protocol::DIASPORA;
917 } elseif (in_array('gnusoc', $data['plugins'])) {
918 $serverdata['network'] = Protocol::OSTATUS;
920 $serverdata['network'] = Protocol::ZOT;
924 if (!empty($data['site_name'])) {
925 $serverdata['site_name'] = $data['site_name'];
928 if (!empty($data['channels_total'])) {
929 $serverdata['registered-users'] = max($data['channels_total'], 1);
932 if (!empty($data['register_policy'])) {
933 switch ($data['register_policy']) {
934 case 'REGISTER_OPEN':
935 $serverdata['register_policy'] = Register::OPEN;
938 case 'REGISTER_APPROVE':
939 $serverdata['register_policy'] = Register::APPROVE;
942 case 'REGISTER_CLOSED':
944 $serverdata['register_policy'] = Register::CLOSED;
953 * Checks if the server contains a valid host meta file
955 * @param string $url URL of the given server
957 * @return boolean 'true' if the server seems to be vital
959 private static function validHostMeta(string $url)
961 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
962 $curlResult = DI::httpClient()->get($url . '/.well-known/host-meta', [HTTPClientOptions::TIMEOUT => $xrd_timeout]);
963 if (!$curlResult->isSuccess()) {
967 $xrd = XML::parseString($curlResult->getBody());
968 if (!is_object($xrd)) {
972 $elements = XML::elementToArray($xrd);
973 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
978 foreach ($elements['xrd']['link'] as $link) {
979 // When there is more than a single "link" element, the array looks slightly different
980 if (!empty($link['@attributes'])) {
981 $link = $link['@attributes'];
984 if (empty($link['rel']) || empty($link['template'])) {
988 if ($link['rel'] == 'lrdd') {
989 // When the webfinger host is the same like the system host, it should be ok.
990 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
998 * Detect the network of the given server via their known contacts
1000 * @param string $url URL of the given server
1001 * @param array $serverdata array with server data
1003 * @return array server data
1005 private static function detectNetworkViaContacts(string $url, array $serverdata)
1009 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $serverdata['nurl']]]);
1010 while ($apcontact = DBA::fetch($apcontacts)) {
1011 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1013 DBA::close($apcontacts);
1015 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $serverdata['nurl']]]);
1016 while ($pcontact = DBA::fetch($pcontacts)) {
1017 $contacts[$pcontact['nurl']] = $pcontact['url'];
1019 DBA::close($pcontacts);
1021 if (empty($contacts)) {
1025 foreach ($contacts as $contact) {
1026 $probed = Contact::getByURL($contact);
1027 if (!empty($probed) && in_array($probed['network'], Protocol::FEDERATED)) {
1028 $serverdata['network'] = $probed['network'];
1033 $serverdata['registered-users'] = max($serverdata['registered-users'], count($contacts), 1);
1039 * Checks if the given server does have a '/poco' endpoint.
1040 * This is used for the 'PortableContact' functionality,
1041 * which is used by both Friendica and Hubzilla.
1043 * @param string $url URL of the given server
1044 * @param array $serverdata array with server data
1046 * @return array server data
1048 private static function checkPoCo(string $url, array $serverdata)
1050 $serverdata['poco'] = '';
1052 $curlResult = DI::httpClient()->get($url . '/poco');
1053 if (!$curlResult->isSuccess()) {
1057 $data = json_decode($curlResult->getBody(), true);
1062 if (!empty($data['totalResults'])) {
1063 $registeredUsers = $serverdata['registered-users'] ?? 0;
1064 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1065 $serverdata['directory-type'] = self::DT_POCO;
1066 $serverdata['poco'] = $url . '/poco';
1073 * Checks if the given server does have a Mastodon style directory endpoint.
1075 * @param string $url URL of the given server
1076 * @param array $serverdata array with server data
1078 * @return array server data
1080 public static function checkMastodonDirectory(string $url, array $serverdata)
1082 $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1');
1083 if (!$curlResult->isSuccess()) {
1087 $data = json_decode($curlResult->getBody(), true);
1092 if (count($data) == 1) {
1093 $serverdata['directory-type'] = self::DT_MASTODON;
1100 * Detects Peertube via their known endpoint
1102 * @param string $url URL of the given server
1103 * @param array $serverdata array with server data
1105 * @return array server data
1107 private static function detectPeertube(string $url, array $serverdata)
1109 $curlResult = DI::httpClient()->get($url . '/api/v1/config');
1111 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1115 $data = json_decode($curlResult->getBody(), true);
1120 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1121 $serverdata['platform'] = 'peertube';
1122 $serverdata['version'] = $data['serverVersion'];
1123 $serverdata['network'] = Protocol::ACTIVITYPUB;
1125 if (!empty($data['instance']['name'])) {
1126 $serverdata['site_name'] = $data['instance']['name'];
1129 if (!empty($data['instance']['shortDescription'])) {
1130 $serverdata['info'] = $data['instance']['shortDescription'];
1133 if (!empty($data['signup'])) {
1134 if (!empty($data['signup']['allowed'])) {
1135 $serverdata['register_policy'] = Register::OPEN;
1139 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1140 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1148 * Detects the version number of a given server when it was a NextCloud installation
1150 * @param string $url URL of the given server
1151 * @param array $serverdata array with server data
1153 * @return array server data
1155 private static function detectNextcloud(string $url, array $serverdata)
1157 $curlResult = DI::httpClient()->get($url . '/status.php');
1159 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1163 $data = json_decode($curlResult->getBody(), true);
1168 if (!empty($data['version'])) {
1169 $serverdata['platform'] = 'nextcloud';
1170 $serverdata['version'] = $data['version'];
1171 $serverdata['network'] = Protocol::ACTIVITYPUB;
1173 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1174 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1182 * Detects data from a given server url if it was a mastodon alike system
1184 * @param string $url URL of the given server
1185 * @param array $serverdata array with server data
1187 * @return array server data
1189 private static function detectMastodonAlikes(string $url, array $serverdata)
1191 $curlResult = DI::httpClient()->get($url . '/api/v1/instance');
1193 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1197 $data = json_decode($curlResult->getBody(), true);
1202 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1203 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1206 if (!empty($data['version'])) {
1207 $serverdata['platform'] = 'mastodon';
1208 $serverdata['version'] = $data['version'] ?? '';
1209 $serverdata['network'] = Protocol::ACTIVITYPUB;
1212 if (!empty($data['title'])) {
1213 $serverdata['site_name'] = $data['title'];
1216 if (!empty($data['title']) && empty($serverdata['platform']) && empty($serverdata['network'])) {
1217 $serverdata['platform'] = 'mastodon';
1218 $serverdata['network'] = Protocol::ACTIVITYPUB;
1221 if (!empty($data['description'])) {
1222 $serverdata['info'] = trim($data['description']);
1225 if (!empty($data['stats']['user_count'])) {
1226 $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1229 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1230 $serverdata['platform'] = strtolower($matches[1]);
1231 $serverdata['version'] = $matches[2];
1234 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1235 $serverdata['platform'] = 'pleroma';
1236 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1239 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1240 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1241 $serverdata['platform'] = 'pleroma';
1248 * Detects data from typical Hubzilla endpoints
1250 * @param string $url URL of the given server
1251 * @param array $serverdata array with server data
1253 * @return array server data
1255 private static function detectHubzilla(string $url, array $serverdata)
1257 $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json');
1258 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1262 $data = json_decode($curlResult->getBody(), true);
1263 if (empty($data) || empty($data['site'])) {
1267 if (!empty($data['site']['name'])) {
1268 $serverdata['site_name'] = $data['site']['name'];
1271 if (!empty($data['site']['platform'])) {
1272 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1273 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1274 $serverdata['network'] = Protocol::ZOT;
1277 if (!empty($data['site']['hubzilla'])) {
1278 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1279 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1280 $serverdata['network'] = Protocol::ZOT;
1283 if (!empty($data['site']['redmatrix'])) {
1284 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1285 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1286 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1287 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1290 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1291 $serverdata['network'] = Protocol::ZOT;
1295 $inviteonly = false;
1298 if (!empty($data['site']['closed'])) {
1299 $closed = self::toBoolean($data['site']['closed']);
1302 if (!empty($data['site']['private'])) {
1303 $private = self::toBoolean($data['site']['private']);
1306 if (!empty($data['site']['inviteonly'])) {
1307 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1310 if (!$closed && !$private and $inviteonly) {
1311 $serverdata['register_policy'] = Register::APPROVE;
1312 } elseif (!$closed && !$private) {
1313 $serverdata['register_policy'] = Register::OPEN;
1315 $serverdata['register_policy'] = Register::CLOSED;
1318 if (!empty($serverdata['network']) && in_array($serverdata['detection-method'],
1319 [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1320 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1327 * Converts input value to a boolean value
1329 * @param string|integer $val
1333 private static function toBoolean($val)
1335 if (($val == 'true') || ($val == 1)) {
1337 } elseif (($val == 'false') || ($val == 0)) {
1345 * Detect if the URL belongs to a GNU Social server
1347 * @param string $url URL of the given server
1348 * @param array $serverdata array with server data
1350 * @return array server data
1352 private static function detectGNUSocial(string $url, array $serverdata)
1354 // Test for GNU Social
1355 $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json');
1356 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1357 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1358 $serverdata['platform'] = 'gnusocial';
1359 // Remove junk that some GNU Social servers return
1360 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1361 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1362 $serverdata['version'] = trim($serverdata['version'], '"');
1363 $serverdata['network'] = Protocol::OSTATUS;
1365 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1366 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1372 // Test for Statusnet
1373 $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json');
1374 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1375 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1377 // Remove junk that some GNU Social servers return
1378 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1379 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1380 $serverdata['version'] = trim($serverdata['version'], '"');
1382 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1383 $serverdata['platform'] = 'pleroma';
1384 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1385 $serverdata['network'] = Protocol::ACTIVITYPUB;
1387 $serverdata['platform'] = 'statusnet';
1388 $serverdata['network'] = Protocol::OSTATUS;
1391 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1392 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1400 * Detect if the URL belongs to a Friendica server
1402 * @param string $url URL of the given server
1403 * @param array $serverdata array with server data
1405 * @return array server data
1407 private static function detectFriendica(string $url, array $serverdata)
1409 $curlResult = DI::httpClient()->get($url . '/friendica/json');
1410 if (!$curlResult->isSuccess()) {
1411 $curlResult = DI::httpClient()->get($url . '/friendika/json');
1413 $platform = 'Friendika';
1416 $platform = 'Friendica';
1419 if (!$curlResult->isSuccess()) {
1423 $data = json_decode($curlResult->getBody(), true);
1424 if (empty($data) || empty($data['version'])) {
1428 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1429 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1432 $serverdata['network'] = Protocol::DFRN;
1433 $serverdata['version'] = $data['version'];
1435 if (!empty($data['no_scrape_url'])) {
1436 $serverdata['noscrape'] = $data['no_scrape_url'];
1439 if (!empty($data['site_name'])) {
1440 $serverdata['site_name'] = $data['site_name'];
1443 if (!empty($data['info'])) {
1444 $serverdata['info'] = trim($data['info']);
1447 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1448 switch ($register_policy) {
1449 case 'REGISTER_OPEN':
1450 $serverdata['register_policy'] = Register::OPEN;
1453 case 'REGISTER_APPROVE':
1454 $serverdata['register_policy'] = Register::APPROVE;
1457 case 'REGISTER_CLOSED':
1458 case 'REGISTER_INVITATION':
1459 $serverdata['register_policy'] = Register::CLOSED;
1462 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
1463 $serverdata['register_policy'] = Register::CLOSED;
1467 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
1473 * Analyses the landing page of a given server for hints about type and system of that server
1475 * @param object $curlResult result of curl execution
1476 * @param array $serverdata array with server data
1477 * @param string $url Server URL
1479 * @return array server data
1481 private static function analyseRootBody($curlResult, array $serverdata, string $url)
1483 if (empty($curlResult->getBody())) {
1487 $doc = new DOMDocument();
1488 @$doc->loadHTML($curlResult->getBody());
1489 $xpath = new DOMXPath($doc);
1491 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
1492 if (!empty($title)) {
1493 $serverdata['site_name'] = $title;
1496 $list = $xpath->query('//meta[@name]');
1498 foreach ($list as $node) {
1500 if ($node->attributes->length) {
1501 foreach ($node->attributes as $attribute) {
1502 $value = trim($attribute->value);
1503 if (empty($value)) {
1507 $attr[$attribute->name] = $value;
1510 if (empty($attr['name']) || empty($attr['content'])) {
1515 if ($attr['name'] == 'description') {
1516 $serverdata['info'] = $attr['content'];
1519 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
1520 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad'])) {
1521 $serverdata['platform'] = strtolower($attr['content']);
1522 if (in_array($attr['content'], ['Misskey', 'Write.as'])) {
1523 $serverdata['network'] = Protocol::ACTIVITYPUB;
1526 if (($attr['name'] == 'generator') && (empty($serverdata['platform']) || (substr(strtolower($attr['content']), 0, 9) == 'wordpress'))) {
1527 $serverdata['platform'] = strtolower($attr['content']);
1528 $version_part = explode(' ', $attr['content']);
1530 if (count($version_part) == 2) {
1531 if (in_array($version_part[0], ['WordPress'])) {
1532 $serverdata['platform'] = 'wordpress';
1533 $serverdata['version'] = $version_part[1];
1535 // We still do need a reliable test if some AP plugin is activated
1536 if (DBA::exists('apcontact', ['baseurl' => $url])) {
1537 $serverdata['network'] = Protocol::ACTIVITYPUB;
1539 $serverdata['network'] = Protocol::FEED;
1542 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1543 $serverdata['detection-method'] = self::DETECT_BODY;
1546 if (in_array($version_part[0], ['Friendika', 'Friendica'])) {
1547 $serverdata['platform'] = strtolower($version_part[0]);
1548 $serverdata['version'] = $version_part[1];
1549 $serverdata['network'] = Protocol::DFRN;
1555 $list = $xpath->query('//meta[@property]');
1557 foreach ($list as $node) {
1559 if ($node->attributes->length) {
1560 foreach ($node->attributes as $attribute) {
1561 $value = trim($attribute->value);
1562 if (empty($value)) {
1566 $attr[$attribute->name] = $value;
1569 if (empty($attr['property']) || empty($attr['content'])) {
1574 if ($attr['property'] == 'og:site_name') {
1575 $serverdata['site_name'] = $attr['content'];
1578 if ($attr['property'] == 'og:description') {
1579 $serverdata['info'] = $attr['content'];
1582 if ($attr['property'] == 'og:platform') {
1583 $serverdata['platform'] = strtolower($attr['content']);
1585 if (in_array($attr['content'], ['PeerTube'])) {
1586 $serverdata['network'] = Protocol::ACTIVITYPUB;
1590 if ($attr['property'] == 'generator') {
1591 $serverdata['platform'] = strtolower($attr['content']);
1593 if (in_array($attr['content'], ['hubzilla'])) {
1594 // We later check which compatible protocol modules are loaded.
1595 $serverdata['network'] = Protocol::ZOT;
1600 if (!empty($serverdata['network']) && ($serverdata['detection-method'] == self::DETECT_MANUAL)) {
1601 $serverdata['detection-method'] = self::DETECT_BODY;
1608 * Analyses the header data of a given server for hints about type and system of that server
1610 * @param object $curlResult result of curl execution
1611 * @param array $serverdata array with server data
1613 * @return array server data
1615 private static function analyseRootHeader($curlResult, array $serverdata)
1617 if ($curlResult->getHeader('server') == 'Mastodon') {
1618 $serverdata['platform'] = 'mastodon';
1619 $serverdata['network'] = Protocol::ACTIVITYPUB;
1620 } elseif ($curlResult->inHeader('x-diaspora-version')) {
1621 $serverdata['platform'] = 'diaspora';
1622 $serverdata['network'] = Protocol::DIASPORA;
1623 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
1624 } elseif ($curlResult->inHeader('x-friendica-version')) {
1625 $serverdata['platform'] = 'friendica';
1626 $serverdata['network'] = Protocol::DFRN;
1627 $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
1632 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1633 $serverdata['detection-method'] = self::DETECT_HEADER;
1640 * Test if the body contains valid content
1642 * @param string $body
1645 private static function invalidBody(string $body)
1647 // Currently we only test for a HTML element.
1648 // Possibly we enhance this in the future.
1649 return !strpos($body, '>');
1653 * Update GServer entries
1655 public static function discover()
1657 // Update the server list
1658 self::discoverFederation();
1662 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
1664 if ($requery_days == 0) {
1668 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
1670 $gservers = DBA::p("SELECT `id`, `url`, `nurl`, `network`, `poco`, `directory-type`
1673 AND `directory-type` != ?
1674 AND `last_poco_query` < ?
1675 ORDER BY RAND()", self::DT_NONE, $last_update
1678 while ($gserver = DBA::fetch($gservers)) {
1679 Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1680 Worker::add(PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
1682 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1683 Worker::add(PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
1685 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1686 DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);
1688 if (--$no_of_queries == 0) {
1693 DBA::close($gservers);
1697 * Discover federated servers
1699 private static function discoverFederation()
1701 $last = DI::config()->get('poco', 'last_federation_discovery');
1704 $next = $last + (24 * 60 * 60);
1706 if ($next > time()) {
1711 // Discover federated servers
1712 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
1713 foreach ($protocols as $protocol) {
1714 $query = '{nodes(protocol:"' . $protocol . '"){host}}';
1715 $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query));
1716 if (!empty($curlResult)) {
1717 $data = json_decode($curlResult, true);
1718 if (!empty($data['data']['nodes'])) {
1719 foreach ($data['data']['nodes'] as $server) {
1720 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
1721 self::add('https://' . $server['host'], true);
1727 // Disvover Mastodon servers
1728 $accesstoken = DI::config()->get('system', 'instances_social_key');
1730 if (!empty($accesstoken)) {
1731 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1732 $curlResult = DI::httpClient()->get($api, [HTTPClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
1734 if ($curlResult->isSuccess()) {
1735 $servers = json_decode($curlResult->getBody(), true);
1737 foreach ($servers['instances'] as $server) {
1738 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
1744 DI::config()->set('poco', 'last_federation_discovery', time());
1748 * Set the protocol for the given server
1750 * @param int $gsid Server id
1751 * @param int $protocol Protocol id
1755 public static function setProtocol(int $gsid, int $protocol)
1761 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
1762 if (!DBA::isResult($gserver)) {
1766 $old = $gserver['protocol'];
1768 if (!is_null($old)) {
1770 The priority for the protocols is:
1772 2. DFRN via Diaspora
1778 // We don't need to change it when nothing is to be changed
1779 if ($old == $protocol) {
1783 // We don't want to mark a server as OStatus when it had been marked with any other protocol before
1784 if ($protocol == Post\DeliveryData::OSTATUS) {
1788 // If the server is marked as ActivityPub then we won't change it to anything different
1789 if ($old == Post\DeliveryData::ACTIVITYPUB) {
1793 // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
1794 if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
1798 // Don't change it to Diaspora when it is a legacy DFRN server
1799 if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
1804 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url'], 'callstack' => System::callstack(20)]);
1805 DBA::update('gserver', ['protocol' => $protocol], ['id' => $gsid]);
1809 * Fetch the protocol of the given server
1811 * @param int $gsid Server id
1815 public static function getProtocol(int $gsid)
1821 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
1822 if (DBA::isResult($gserver)) {
1823 return $gserver['protocol'];