4 * @file src/Model/GServer.php
5 * This file includes the GServer class to handle with servers
7 namespace Friendica\Model;
11 use Friendica\Core\Config;
12 use Friendica\Core\Protocol;
13 use Friendica\Database\DBA;
14 use Friendica\Module\Register;
15 use Friendica\Network\CurlResult;
16 use Friendica\Util\Network;
17 use Friendica\Util\DateTimeFormat;
18 use Friendica\Util\Strings;
19 use Friendica\Util\XML;
20 use Friendica\Core\Logger;
21 use Friendica\Protocol\PortableContact;
22 use Friendica\Protocol\Diaspora;
23 use Friendica\Network\Probe;
26 * This class handles GServer related functions
33 const DT_MASTODON = 2;
35 * Checks if the given server is reachable
37 * @param string $profile URL of the given profile
38 * @param string $server URL of the given server (If empty, taken from profile)
39 * @param string $network Network value that is used, when detection failed
40 * @param boolean $force Force an update.
42 * @return boolean 'true' if server seems vital
44 public static function reachable(string $profile, string $server = '', string $network = '', bool $force = false)
47 $server = Contact::getBasepath($profile);
54 return self::check($server, $network, $force);
58 * Decides if a server needs to be updated, based upon several date fields
60 * @param date $created Creation date of that server entry
61 * @param date $updated When had the server entry be updated
62 * @param date $last_failure Last failure when contacting that server
63 * @param date $last_contact Last time the server had been contacted
65 * @return boolean Does the server record needs an update?
67 public static function updateNeeded($created, $updated, $last_failure, $last_contact)
69 $now = strtotime(DateTimeFormat::utcNow());
71 if ($updated > $last_contact) {
72 $contact_time = strtotime($updated);
74 $contact_time = strtotime($last_contact);
77 $failure_time = strtotime($last_failure);
78 $created_time = strtotime($created);
80 // If there is no "created" time then use the current time
81 if ($created_time <= 0) {
85 // If the last contact was less than 24 hours then don't update
86 if (($now - $contact_time) < (60 * 60 * 24)) {
90 // If the last failure was less than 24 hours then don't update
91 if (($now - $failure_time) < (60 * 60 * 24)) {
95 // If the last contact was less than a week ago and the last failure is older than a week then don't update
96 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) && ($contact_time > $failure_time))
99 // 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
100 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) && (($now - $created_time) > (60 * 60 * 24 * 7)) && (($now - $failure_time) < (60 * 60 * 24 * 7))) {
104 // 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
105 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) && (($now - $created_time) > (60 * 60 * 24 * 30)) && (($now - $failure_time) < (60 * 60 * 24 * 30))) {
113 * Checks the state of the given server.
115 * @param string $server_url URL of the given server
116 * @param string $network Network value that is used, when detection failed
117 * @param boolean $force Force an update.
119 * @return boolean 'true' if server seems vital
121 public static function check(string $server_url, string $network = '', bool $force = false)
123 // Unify the server address
124 $server_url = trim($server_url, '/');
125 $server_url = str_replace('/index.php', '', $server_url);
127 if ($server_url == '') {
131 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
132 if (DBA::isResult($gserver)) {
133 if ($gserver['created'] <= DBA::NULL_DATETIME) {
134 $fields = ['created' => DateTimeFormat::utcNow()];
135 $condition = ['nurl' => Strings::normaliseLink($server_url)];
136 DBA::update('gserver', $fields, $condition);
139 $last_contact = $gserver['last_contact'];
140 $last_failure = $gserver['last_failure'];
142 // See discussion under https://forum.friendi.ca/display/0b6b25a8135aabc37a5a0f5684081633
143 // It can happen that a zero date is in the database, but storing it again is forbidden.
144 if ($last_contact < DBA::NULL_DATETIME) {
145 $last_contact = DBA::NULL_DATETIME;
148 if ($last_failure < DBA::NULL_DATETIME) {
149 $last_failure = DBA::NULL_DATETIME;
152 if (!$force && !self::updateNeeded($gserver['created'], '', $last_failure, $last_contact)) {
153 Logger::info('No update needed', ['server' => $server_url]);
154 return ($last_contact >= $last_failure);
156 Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force, 'Created' => $gserver['created'], 'Failure' => $last_failure, 'Contact' => $last_contact]);
158 Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
161 return self::detect($server_url, $network);
165 * Detect server data (type, protocol, version number, ...)
166 * The detected data is then updated or inserted in the gserver table.
168 * @param string $url URL of the given server
169 * @param string $network Network value that is used, when detection failed
171 * @return boolean 'true' if server could be detected
173 public static function detect(string $url, string $network = '')
175 Logger::info('Detect server type', ['server' => $url]);
178 $original_url = $url;
180 // Remove URL content that is not supposed to exist for a server url
181 $urlparts = parse_url($url);
182 unset($urlparts['user']);
183 unset($urlparts['pass']);
184 unset($urlparts['query']);
185 unset($urlparts['fragment']);
186 $url = Network::unparseURL($urlparts);
188 // If the URL missmatches, then we mark the old entry as failure
189 if ($url != $original_url) {
190 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => Strings::normaliseLink($original_url)]);
193 // When a nodeinfo is present, we don't need to dig further
194 $xrd_timeout = Config::get('system', 'xrd_timeout');
195 $curlResult = Network::curl($url . '/.well-known/nodeinfo', false, ['timeout' => $xrd_timeout]);
196 if ($curlResult->isTimeout()) {
197 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => Strings::normaliseLink($url)]);
201 $nodeinfo = self::fetchNodeinfo($url, $curlResult);
203 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
204 if (empty($nodeinfo)) {
205 $nodeinfo = self::fetchStatistics($url);
208 // If that didn't work out well, we use some protocol specific endpoints
209 // For Friendica and Zot based networks we have to dive deeper to reveal more details
210 if (empty($nodeinfo['network']) || in_array($nodeinfo['network'], [Protocol::DFRN, Protocol::ZOT])) {
211 // Fetch the landing page, possibly it reveals some data
212 if (empty($nodeinfo['network'])) {
213 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout]);
214 if ($curlResult->isSuccess()) {
215 $serverdata = self::analyseRootHeader($curlResult, $serverdata);
216 $serverdata = self::analyseRootBody($curlResult, $serverdata, $url);
219 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
220 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => Strings::normaliseLink($url)]);
225 if (empty($serverdata['network']) || ($serverdata['network'] == Protocol::ACTIVITYPUB)) {
226 $serverdata = self::detectMastodonAlikes($url, $serverdata);
229 // All following checks are done for systems that always have got a "host-meta" endpoint.
230 // With this check we don't have to waste time and ressources for dead systems.
231 // Also this hopefully prevents us from receiving abuse messages.
232 if (empty($serverdata['network']) && !self::validHostMeta($url)) {
233 DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => Strings::normaliseLink($url)]);
237 if (empty($serverdata['network']) || in_array($serverdata['network'], [Protocol::DFRN, Protocol::ACTIVITYPUB])) {
238 $serverdata = self::detectFriendica($url, $serverdata);
241 // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
242 if (empty($serverdata['network']) || ($serverdata['network'] == Protocol::ZOT)) {
243 $serverdata = self::fetchSiteinfo($url, $serverdata);
246 // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations
247 if (empty($serverdata['network'])) {
248 $serverdata = self::detectHubzilla($url, $serverdata);
251 if (empty($serverdata['network'])) {
252 $serverdata = self::detectNextcloud($url, $serverdata);
255 if (empty($serverdata['network'])) {
256 $serverdata = self::detectGNUSocial($url, $serverdata);
259 $serverdata = $nodeinfo;
262 // Detect the directory type
263 $serverdata['directory-type'] = self::DT_NONE;
264 $serverdata = self::checkPoCo($url, $serverdata);
265 $serverdata = self::checkMastodonDirectory($url, $serverdata);
267 // We can't detect the network type. Possibly it is some system that we don't know yet
268 if (empty($serverdata['network'])) {
269 $serverdata['network'] = Protocol::PHANTOM;
272 // When we hadn't been able to detect the network type, we use the hint from the parameter
273 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
274 $serverdata['network'] = $network;
277 $serverdata['url'] = $url;
278 $serverdata['nurl'] = Strings::normaliseLink($url);
280 // We take the highest number that we do find
281 $registeredUsers = $serverdata['registered-users'] ?? 0;
283 // On an active server there has to be at least a single user
284 if (($serverdata['network'] != Protocol::PHANTOM) && ($registeredUsers == 0)) {
285 $registeredUsers = 1;
288 if ($serverdata['network'] != Protocol::PHANTOM) {
289 $gcontacts = DBA::count('gcontact', ['server_url' => [$url, $serverdata['nurl']]]);
290 $apcontacts = DBA::count('apcontact', ['baseurl' => [$url, $serverdata['nurl']]]);
291 $contacts = DBA::count('contact', ['uid' => 0, 'baseurl' => [$url, $serverdata['nurl']]]);
292 $serverdata['registered-users'] = max($gcontacts, $apcontacts, $contacts, $registeredUsers);
294 $serverdata['registered-users'] = $registeredUsers;
295 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
298 $serverdata['last_contact'] = DateTimeFormat::utcNow();
300 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
301 if (!DBA::isResult($gserver)) {
302 $serverdata['created'] = DateTimeFormat::utcNow();
303 $ret = DBA::insert('gserver', $serverdata);
305 // Don't override the network with 'unknown' when there had been a valid entry before
306 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($gserver['network'])) {
307 unset($serverdata['network']);
310 $ret = DBA::update('gserver', $serverdata, ['nurl' => $serverdata['nurl']]);
313 if (!empty($serverdata['network']) && in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
314 self::discoverRelay($url);
321 * Fetch relay data from a given server url
323 * @param string $server_url address of the server
324 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
326 private static function discoverRelay(string $server_url)
328 Logger::info('Discover relay data', ['server' => $server_url]);
330 $curlResult = Network::curl($server_url . '/.well-known/x-social-relay');
331 if (!$curlResult->isSuccess()) {
335 $data = json_decode($curlResult->getBody(), true);
336 if (!is_array($data)) {
340 $gserver = DBA::selectFirst('gserver', ['id', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
341 if (!DBA::isResult($gserver)) {
345 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
346 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
347 DBA::update('gserver', $fields, ['id' => $gserver['id']]);
350 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
352 if ($data['scope'] == 'tags') {
355 foreach ($data['tags'] as $tag) {
356 $tag = mb_strtolower($tag);
357 if (strlen($tag) < 100) {
362 foreach ($tags as $tag) {
363 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], true);
367 // Create or update the relay contact
369 if (isset($data['protocols'])) {
370 if (isset($data['protocols']['diaspora'])) {
371 $fields['network'] = Protocol::DIASPORA;
373 if (isset($data['protocols']['diaspora']['receive'])) {
374 $fields['batch'] = $data['protocols']['diaspora']['receive'];
375 } elseif (is_string($data['protocols']['diaspora'])) {
376 $fields['batch'] = $data['protocols']['diaspora'];
380 if (isset($data['protocols']['dfrn'])) {
381 $fields['network'] = Protocol::DFRN;
383 if (isset($data['protocols']['dfrn']['receive'])) {
384 $fields['batch'] = $data['protocols']['dfrn']['receive'];
385 } elseif (is_string($data['protocols']['dfrn'])) {
386 $fields['batch'] = $data['protocols']['dfrn'];
390 Diaspora::setRelayContact($server_url, $fields);
394 * Fetch server data from '/statistics.json' on the given server
396 * @param string $url URL of the given server
398 * @return array server data
400 private static function fetchStatistics(string $url)
402 $curlResult = Network::curl($url . '/statistics.json');
403 if (!$curlResult->isSuccess()) {
407 $data = json_decode($curlResult->getBody(), true);
414 if (!empty($data['version'])) {
415 $serverdata['version'] = $data['version'];
416 // Version numbers on statistics.json are presented with additional info, e.g.:
417 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
418 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
421 if (!empty($data['name'])) {
422 $serverdata['site_name'] = $data['name'];
425 if (!empty($data['network'])) {
426 $serverdata['platform'] = $data['network'];
428 if ($serverdata['platform'] == 'Diaspora') {
429 $serverdata['network'] = Protocol::DIASPORA;
430 } elseif ($serverdata['platform'] == 'Friendica') {
431 $serverdata['network'] = Protocol::DFRN;
432 } elseif ($serverdata['platform'] == 'hubzilla') {
433 $serverdata['network'] = Protocol::ZOT;
434 } elseif ($serverdata['platform'] == 'redmatrix') {
435 $serverdata['network'] = Protocol::ZOT;
440 if (!empty($data['registrations_open'])) {
441 $serverdata['register_policy'] = Register::OPEN;
443 $serverdata['register_policy'] = Register::CLOSED;
450 * Detect server type by using the nodeinfo data
452 * @param string $url address of the server
453 * @param CurlResult $curlResult
454 * @return array Server data
455 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
457 private static function fetchNodeinfo(string $url, CurlResult $curlResult)
459 $nodeinfo = json_decode($curlResult->getBody(), true);
461 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
468 foreach ($nodeinfo['links'] as $link) {
469 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
470 Logger::info('Invalid nodeinfo format', ['url' => $url]);
473 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
474 $nodeinfo1_url = $link['href'];
475 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
476 $nodeinfo2_url = $link['href'];
480 if ($nodeinfo1_url . $nodeinfo2_url == '') {
486 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
487 if (!empty($nodeinfo2_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
488 $server = self::parseNodeinfo2($nodeinfo2_url);
491 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
492 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
493 $server = self::parseNodeinfo1($nodeinfo1_url);
502 * @param string $nodeinfo_url address of the nodeinfo path
503 * @return array Server data
504 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
506 private static function parseNodeinfo1(string $nodeinfo_url)
508 $curlResult = Network::curl($nodeinfo_url);
510 if (!$curlResult->isSuccess()) {
514 $nodeinfo = json_decode($curlResult->getBody(), true);
516 if (!is_array($nodeinfo)) {
522 $server['register_policy'] = Register::CLOSED;
524 if (!empty($nodeinfo['openRegistrations'])) {
525 $server['register_policy'] = Register::OPEN;
528 if (is_array($nodeinfo['software'])) {
529 if (!empty($nodeinfo['software']['name'])) {
530 $server['platform'] = $nodeinfo['software']['name'];
533 if (!empty($nodeinfo['software']['version'])) {
534 $server['version'] = $nodeinfo['software']['version'];
535 // Version numbers on Nodeinfo are presented with additional info, e.g.:
536 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
537 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
541 if (!empty($nodeinfo['metadata']['nodeName'])) {
542 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
545 if (!empty($nodeinfo['usage']['users']['total'])) {
546 $server['registered-users'] = $nodeinfo['usage']['users']['total'];
549 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
551 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
552 $protocols[$protocol] = true;
555 if (!empty($protocols['friendica'])) {
556 $server['network'] = Protocol::DFRN;
557 } elseif (!empty($protocols['activitypub'])) {
558 $server['network'] = Protocol::ACTIVITYPUB;
559 } elseif (!empty($protocols['diaspora'])) {
560 $server['network'] = Protocol::DIASPORA;
561 } elseif (!empty($protocols['ostatus'])) {
562 $server['network'] = Protocol::OSTATUS;
563 } elseif (!empty($protocols['gnusocial'])) {
564 $server['network'] = Protocol::OSTATUS;
565 } elseif (!empty($protocols['zot'])) {
566 $server['network'] = Protocol::ZOT;
570 if (empty($server)) {
580 * @param string $nodeinfo_url address of the nodeinfo path
581 * @return array Server data
582 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
584 private static function parseNodeinfo2(string $nodeinfo_url)
586 $curlResult = Network::curl($nodeinfo_url);
587 if (!$curlResult->isSuccess()) {
591 $nodeinfo = json_decode($curlResult->getBody(), true);
593 if (!is_array($nodeinfo)) {
599 $server['register_policy'] = Register::CLOSED;
601 if (!empty($nodeinfo['openRegistrations'])) {
602 $server['register_policy'] = Register::OPEN;
605 if (is_array($nodeinfo['software'])) {
606 if (!empty($nodeinfo['software']['name'])) {
607 $server['platform'] = $nodeinfo['software']['name'];
610 if (!empty($nodeinfo['software']['version'])) {
611 $server['version'] = $nodeinfo['software']['version'];
612 // Version numbers on Nodeinfo are presented with additional info, e.g.:
613 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
614 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
618 if (!empty($nodeinfo['metadata']['nodeName'])) {
619 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
622 if (!empty($nodeinfo['usage']['users']['total'])) {
623 $server['registered-users'] = $nodeinfo['usage']['users']['total'];
626 if (!empty($nodeinfo['protocols'])) {
628 foreach ($nodeinfo['protocols'] as $protocol) {
629 $protocols[$protocol] = true;
632 if (!empty($protocols['dfrn'])) {
633 $server['network'] = Protocol::DFRN;
634 } elseif (!empty($protocols['activitypub'])) {
635 $server['network'] = Protocol::ACTIVITYPUB;
636 } elseif (!empty($protocols['diaspora'])) {
637 $server['network'] = Protocol::DIASPORA;
638 } elseif (!empty($protocols['ostatus'])) {
639 $server['network'] = Protocol::OSTATUS;
640 } elseif (!empty($protocols['gnusocial'])) {
641 $server['network'] = Protocol::OSTATUS;
642 } elseif (!empty($protocols['zot'])) {
643 $server['network'] = Protocol::ZOT;
647 if (empty($server)) {
655 * Fetch server information from a 'siteinfo.json' file on the given server
657 * @param string $url URL of the given server
658 * @param array $serverdata array with server data
660 * @return array server data
662 private static function fetchSiteinfo(string $url, array $serverdata)
664 $curlResult = Network::curl($url . '/siteinfo.json');
665 if (!$curlResult->isSuccess()) {
669 $data = json_decode($curlResult->getBody(), true);
674 if (!empty($data['url'])) {
675 $serverdata['platform'] = $data['platform'];
676 $serverdata['version'] = $data['version'];
679 if (!empty($data['plugins'])) {
680 if (in_array('pubcrawl', $data['plugins'])) {
681 $serverdata['network'] = Protocol::ACTIVITYPUB;
682 } elseif (in_array('diaspora', $data['plugins'])) {
683 $serverdata['network'] = Protocol::DIASPORA;
684 } elseif (in_array('gnusoc', $data['plugins'])) {
685 $serverdata['network'] = Protocol::OSTATUS;
687 $serverdata['network'] = Protocol::ZOT;
691 if (!empty($data['site_name'])) {
692 $serverdata['site_name'] = $data['site_name'];
695 if (!empty($data['channels_total'])) {
696 $serverdata['registered-users'] = $data['channels_total'];
699 if (!empty($data['register_policy'])) {
700 switch ($data['register_policy']) {
701 case 'REGISTER_OPEN':
702 $serverdata['register_policy'] = Register::OPEN;
705 case 'REGISTER_APPROVE':
706 $serverdata['register_policy'] = Register::APPROVE;
709 case 'REGISTER_CLOSED':
711 $serverdata['register_policy'] = Register::CLOSED;
720 * Checks if the server contains a valid host meta file
722 * @param string $url URL of the given server
724 * @return boolean 'true' if the server seems to be vital
726 private static function validHostMeta(string $url)
728 $xrd_timeout = Config::get('system', 'xrd_timeout');
729 $curlResult = Network::curl($url . '/.well-known/host-meta', false, ['timeout' => $xrd_timeout]);
730 if (!$curlResult->isSuccess()) {
734 $xrd = XML::parseString($curlResult->getBody(), false);
735 if (!is_object($xrd)) {
739 $elements = XML::elementToArray($xrd);
740 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
745 foreach ($elements['xrd']['link'] as $link) {
746 // When there is more than a single "link" element, the array looks slightly different
747 if (!empty($link['@attributes'])) {
748 $link = $link['@attributes'];
751 if (empty($link['rel']) || empty($link['template'])) {
755 if ($link['rel'] == 'lrdd') {
756 // When the webfinger host is the same like the system host, it should be ok.
757 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
765 * Detect the network of the given server via their known contacts
767 * @param string $url URL of the given server
768 * @param array $serverdata array with server data
770 * @return array server data
772 private static function detectNetworkViaContacts(string $url, array $serverdata)
776 $gcontacts = DBA::select('gcontact', ['url', 'nurl'], ['server_url' => [$url, $serverdata['nurl']]]);
777 while ($gcontact = DBA::fetch($gcontacts)) {
778 $contacts[$gcontact['nurl']] = $gcontact['url'];
780 DBA::close($gcontacts);
782 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $serverdata['nurl']]]);
783 while ($gcontact = DBA::fetch($gcontacts)) {
784 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
786 DBA::close($apcontacts);
788 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $serverdata['nurl']]]);
789 while ($gcontact = DBA::fetch($gcontacts)) {
790 $contacts[$pcontact['nurl']] = $pcontact['url'];
792 DBA::close($pcontacts);
794 if (empty($contacts)) {
798 foreach ($contacts as $contact) {
799 $probed = Probe::uri($contact);
800 if (in_array($probed['network'], Protocol::FEDERATED)) {
801 $serverdata['network'] = $probed['network'];
806 $serverdata['registered-users'] = max($serverdata['registered-users'], count($contacts));
812 * Checks if the given server does have a '/poco' endpoint.
813 * This is used for the 'PortableContact' functionality,
814 * which is used by both Friendica and Hubzilla.
816 * @param string $url URL of the given server
817 * @param array $serverdata array with server data
819 * @return array server data
821 private static function checkPoCo(string $url, array $serverdata)
823 $serverdata['poco'] = '';
825 $curlResult = Network::curl($url. '/poco');
826 if (!$curlResult->isSuccess()) {
830 $data = json_decode($curlResult->getBody(), true);
835 if (!empty($data['totalResults'])) {
836 $registeredUsers = $serverdata['registered-users'] ?? 0;
837 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers);
838 $serverdata['directory-type'] = self::DT_POCO;
839 $serverdata['poco'] = $url . '/poco';
846 * Checks if the given server does have a Mastodon style directory endpoint.
848 * @param string $url URL of the given server
849 * @param array $serverdata array with server data
851 * @return array server data
853 public static function checkMastodonDirectory(string $url, array $serverdata)
855 $curlResult = Network::curl($url . '/api/v1/directory?limit=1');
856 if (!$curlResult->isSuccess()) {
860 $data = json_decode($curlResult->getBody(), true);
865 if (count($data) == 1) {
866 $serverdata['directory-type'] = self::DT_MASTODON;
873 * Detects the version number of a given server when it was a NextCloud installation
875 * @param string $url URL of the given server
876 * @param array $serverdata array with server data
878 * @return array server data
880 private static function detectNextcloud(string $url, array $serverdata)
882 $curlResult = Network::curl($url . '/status.php');
884 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
888 $data = json_decode($curlResult->getBody(), true);
893 if (!empty($data['version'])) {
894 $serverdata['platform'] = 'nextcloud';
895 $serverdata['version'] = $data['version'];
896 $serverdata['network'] = Protocol::ACTIVITYPUB;
903 * Detects data from a given server url if it was a mastodon alike system
905 * @param string $url URL of the given server
906 * @param array $serverdata array with server data
908 * @return array server data
910 private static function detectMastodonAlikes(string $url, array $serverdata)
912 $curlResult = Network::curl($url . '/api/v1/instance');
914 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
918 $data = json_decode($curlResult->getBody(), true);
923 if (!empty($data['version'])) {
924 $serverdata['platform'] = 'mastodon';
925 $serverdata['version'] = $data['version'] ?? '';
926 $serverdata['network'] = Protocol::ACTIVITYPUB;
929 if (!empty($data['title'])) {
930 $serverdata['site_name'] = $data['title'];
933 if (!empty($data['description'])) {
934 $serverdata['info'] = trim($data['description']);
937 if (!empty($data['stats']['user_count'])) {
938 $serverdata['registered-users'] = $data['stats']['user_count'];
941 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
942 $serverdata['platform'] = $matches[1];
943 $serverdata['version'] = $matches[2];
946 if (!empty($serverdata['version']) && strstr($serverdata['version'], 'Pleroma')) {
947 $serverdata['platform'] = 'pleroma';
948 $serverdata['version'] = trim(str_replace('Pleroma', '', $serverdata['version']));
955 * Detects data from typical Hubzilla endpoints
957 * @param string $url URL of the given server
958 * @param array $serverdata array with server data
960 * @return array server data
962 private static function detectHubzilla(string $url, array $serverdata)
964 $curlResult = Network::curl($url . '/api/statusnet/config.json');
965 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
969 $data = json_decode($curlResult->getBody(), true);
974 if (!empty($data['site']['name'])) {
975 $serverdata['site_name'] = $data['site']['name'];
978 if (!empty($data['site']['platform'])) {
979 $serverdata['platform'] = $data['site']['platform']['PLATFORM_NAME'];
980 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
981 $serverdata['network'] = Protocol::ZOT;
984 if (!empty($data['site']['hubzilla'])) {
985 $serverdata['platform'] = $data['site']['hubzilla']['PLATFORM_NAME'];
986 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
987 $serverdata['network'] = Protocol::ZOT;
990 if (!empty($data['site']['redmatrix'])) {
991 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
992 $serverdata['platform'] = $data['site']['redmatrix']['PLATFORM_NAME'];
993 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
994 $serverdata['platform'] = $data['site']['redmatrix']['RED_PLATFORM'];
997 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
998 $serverdata['network'] = Protocol::ZOT;
1002 $inviteonly = false;
1005 if (!empty($data['site']['closed'])) {
1006 $closed = self::toBoolean($data['site']['closed']);
1009 if (!empty($data['site']['private'])) {
1010 $private = self::toBoolean($data['site']['private']);
1013 if (!empty($data['site']['inviteonly'])) {
1014 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1017 if (!$closed && !$private and $inviteonly) {
1018 $register_policy = Register::APPROVE;
1019 } elseif (!$closed && !$private) {
1020 $register_policy = Register::OPEN;
1022 $register_policy = Register::CLOSED;
1029 * Converts input value to a boolean value
1031 * @param string|integer $val
1035 private static function toBoolean($val)
1037 if (($val == 'true') || ($val == 1)) {
1039 } elseif (($val == 'false') || ($val == 0)) {
1047 * Detect if the URL belongs to a GNU Social server
1049 * @param string $url URL of the given server
1050 * @param array $serverdata array with server data
1052 * @return array server data
1054 private static function detectGNUSocial(string $url, array $serverdata)
1056 // Test for GNU Social
1057 $curlResult = Network::curl($url . '/api/gnusocial/version.json');
1058 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1059 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1060 $serverdata['platform'] = 'gnusocial';
1061 // Remove junk that some GNU Social servers return
1062 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1063 $serverdata['version'] = trim($serverdata['version'], '"');
1064 $serverdata['network'] = Protocol::OSTATUS;
1068 // Test for Statusnet
1069 $curlResult = Network::curl($url . '/api/statusnet/version.json');
1070 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1071 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1072 $serverdata['platform'] = 'statusnet';
1073 // Remove junk that some GNU Social servers return
1074 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1075 $serverdata['version'] = trim($serverdata['version'], '"');
1076 $serverdata['network'] = Protocol::OSTATUS;
1083 * Detect if the URL belongs to a Friendica server
1085 * @param string $url URL of the given server
1086 * @param array $serverdata array with server data
1088 * @return array server data
1090 private static function detectFriendica(string $url, array $serverdata)
1092 $curlResult = Network::curl($url . '/friendica/json');
1093 if (!$curlResult->isSuccess()) {
1094 $curlResult = Network::curl($url . '/friendika/json');
1097 if (!$curlResult->isSuccess()) {
1101 $data = json_decode($curlResult->getBody(), true);
1102 if (empty($data) || empty($data['version'])) {
1106 $serverdata['network'] = Protocol::DFRN;
1107 $serverdata['version'] = $data['version'];
1109 if (!empty($data['no_scrape_url'])) {
1110 $serverdata['noscrape'] = $data['no_scrape_url'];
1113 if (!empty($data['site_name'])) {
1114 $serverdata['site_name'] = $data['site_name'];
1117 if (!empty($data['info'])) {
1118 $serverdata['info'] = trim($data['info']);
1121 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1122 switch ($register_policy) {
1123 case 'REGISTER_OPEN':
1124 $serverdata['register_policy'] = Register::OPEN;
1127 case 'REGISTER_APPROVE':
1128 $serverdata['register_policy'] = Register::APPROVE;
1131 case 'REGISTER_CLOSED':
1132 case 'REGISTER_INVITATION':
1133 $serverdata['register_policy'] = Register::CLOSED;
1136 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
1137 $serverdata['register_policy'] = Register::CLOSED;
1141 $serverdata['platform'] = $data['platform'] ?? '';
1147 * Analyses the landing page of a given server for hints about type and system of that server
1149 * @param object $curlResult result of curl execution
1150 * @param array $serverdata array with server data
1151 * @param string $url Server URL
1153 * @return array server data
1155 private static function analyseRootBody($curlResult, array $serverdata, string $url)
1157 $doc = new DOMDocument();
1158 @$doc->loadHTML($curlResult->getBody());
1159 $xpath = new DOMXPath($doc);
1161 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
1162 if (!empty($title)) {
1163 $serverdata['site_name'] = $title;
1166 $list = $xpath->query('//meta[@name]');
1168 foreach ($list as $node) {
1170 if ($node->attributes->length) {
1171 foreach ($node->attributes as $attribute) {
1172 $value = trim($attribute->value);
1173 if (empty($value)) {
1177 $attr[$attribute->name] = $value;
1180 if (empty($attr['name']) || empty($attr['content'])) {
1185 if ($attr['name'] == 'description') {
1186 $serverdata['info'] = $attr['content'];
1189 if ($attr['name'] == 'application-name') {
1190 $serverdata['platform'] = $attr['content'];
1191 if (in_array($attr['content'], ['Misskey', 'Write.as'])) {
1192 $serverdata['network'] = Protocol::ACTIVITYPUB;
1196 if ($attr['name'] == 'generator') {
1197 $serverdata['platform'] = $attr['content'];
1199 $version_part = explode(' ', $attr['content']);
1201 if (count($version_part) == 2) {
1202 if (in_array($version_part[0], ['WordPress'])) {
1203 $serverdata['platform'] = $version_part[0];
1204 $serverdata['version'] = $version_part[1];
1206 // We still do need a reliable test if some AP plugin is activated
1207 if (DBA::exists('apcontact', ['baseurl' => $url])) {
1208 $serverdata['network'] = Protocol::ACTIVITYPUB;
1210 $serverdata['network'] = Protocol::FEED;
1213 if (in_array($version_part[0], ['Friendika', 'Friendica'])) {
1214 $serverdata['platform'] = $version_part[0];
1215 $serverdata['version'] = $version_part[1];
1216 $serverdata['network'] = Protocol::DFRN;
1222 $list = $xpath->query('//meta[@property]');
1224 foreach ($list as $node) {
1226 if ($node->attributes->length) {
1227 foreach ($node->attributes as $attribute) {
1228 $value = trim($attribute->value);
1229 if (empty($value)) {
1233 $attr[$attribute->name] = $value;
1236 if (empty($attr['property']) || empty($attr['content'])) {
1241 if ($attr['property'] == 'og:site_name') {
1242 $serverdata['site_name'] = $attr['content'];
1245 if ($attr['property'] == 'og:description') {
1246 $serverdata['info'] = $attr['content'];
1249 if ($attr['property'] == 'og:platform') {
1250 $serverdata['platform'] = $attr['content'];
1252 if (in_array($attr['content'], ['PeerTube'])) {
1253 $serverdata['network'] = Protocol::ACTIVITYPUB;
1257 if ($attr['property'] == 'generator') {
1258 $serverdata['platform'] = $attr['content'];
1260 if (in_array($attr['content'], ['hubzilla'])) {
1261 // We later check which compatible protocol modules are loaded.
1262 $serverdata['network'] = Protocol::ZOT;
1271 * Analyses the header data of a given server for hints about type and system of that server
1273 * @param object $curlResult result of curl execution
1274 * @param array $serverdata array with server data
1276 * @return array server data
1278 private static function analyseRootHeader($curlResult, array $serverdata)
1280 if ($curlResult->getHeader('server') == 'Mastodon') {
1281 $serverdata['platform'] = 'mastodon';
1282 $serverdata['network'] = $network = Protocol::ACTIVITYPUB;
1283 } elseif ($curlResult->inHeader('x-diaspora-version')) {
1284 $serverdata['platform'] = 'diaspora';
1285 $serverdata['network'] = $network = Protocol::DIASPORA;
1286 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version');
1288 } elseif ($curlResult->inHeader('x-friendica-version')) {
1289 $serverdata['platform'] = 'friendica';
1290 $serverdata['network'] = $network = Protocol::DFRN;
1291 $serverdata['version'] = $curlResult->getHeader('x-friendica-version');
1297 * Update the user directory of a given gserver record
1299 * @param array $gserver gserver record
1301 public static function updateDirectory(array $gserver)
1303 /// @todo Add Mastodon API directory
1305 if (!empty($gserver['poco'])) {
1306 PortableContact::discoverSingleServer($gserver['id']);