3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
26 use Friendica\Core\Logger;
27 use Friendica\Core\Protocol;
28 use Friendica\Core\System;
29 use Friendica\Core\Worker;
30 use Friendica\Database\DBA;
32 use Friendica\Module\Register;
33 use Friendica\Network\CurlResult;
34 use Friendica\Protocol\Diaspora;
35 use Friendica\Protocol\PortableContact;
36 use Friendica\Util\DateTimeFormat;
37 use Friendica\Util\Network;
38 use Friendica\Util\Strings;
39 use Friendica\Util\XML;
42 * This class handles GServer related functions
49 const DT_MASTODON = 2;
51 // Methods to detect server types
53 // Non endpoint specific methods
54 const DETECT_MANUAL = 0;
55 const DETECT_HEADER = 1;
56 const DETECT_BODY = 2;
58 // Implementation specific endpoints
59 const DETECT_FRIENDIKA = 10;
60 const DETECT_FRIENDICA = 11;
61 const DETECT_STATUSNET = 12;
62 const DETECT_GNUSOCIAL = 13;
63 const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix
64 const DETECT_SITEINFO_JSON = 15; // Newer Hubzilla
65 const DETECT_MASTODON_API = 16;
66 const DETECT_STATUS_PHP = 17; // Nextcloud
68 // Standardized endpoints
69 const DETECT_STATISTICS_JSON = 100;
70 const DETECT_NODEINFO_1 = 101;
71 const DETECT_NODEINFO_2 = 102;
74 * Get the ID for the given server URL
77 * @param boolean $no_check Don't check if the server hadn't been found
78 * @return int gserver id
80 public static function getID(string $url, bool $no_check = false)
86 $url = self::cleanURL($url);
88 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
89 if (DBA::isResult($gserver)) {
90 Logger::info('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
91 return $gserver['id'];
94 if ($no_check || !self::check($url)) {
98 return self::getID($url, true);
102 * Checks if the given server is reachable
104 * @param string $profile URL of the given profile
105 * @param string $server URL of the given server (If empty, taken from profile)
106 * @param string $network Network value that is used, when detection failed
107 * @param boolean $force Force an update.
109 * @return boolean 'true' if server seems vital
111 public static function reachable(string $profile, string $server = '', string $network = '', bool $force = false)
114 $server = GContact::getBasepath($profile);
121 return self::check($server, $network, $force);
125 * Decides if a server needs to be updated, based upon several date fields
127 * @param date $created Creation date of that server entry
128 * @param date $updated When had the server entry be updated
129 * @param date $last_failure Last failure when contacting that server
130 * @param date $last_contact Last time the server had been contacted
132 * @return boolean Does the server record needs an update?
134 public static function updateNeeded($created, $updated, $last_failure, $last_contact)
136 $now = strtotime(DateTimeFormat::utcNow());
138 if ($updated > $last_contact) {
139 $contact_time = strtotime($updated);
141 $contact_time = strtotime($last_contact);
144 $failure_time = strtotime($last_failure);
145 $created_time = strtotime($created);
147 // If there is no "created" time then use the current time
148 if ($created_time <= 0) {
149 $created_time = $now;
152 // If the last contact was less than 24 hours then don't update
153 if (($now - $contact_time) < (60 * 60 * 24)) {
157 // If the last failure was less than 24 hours then don't update
158 if (($now - $failure_time) < (60 * 60 * 24)) {
162 // If the last contact was less than a week ago and the last failure is older than a week then don't update
163 //if ((($now - $contact_time) < (60 * 60 * 24 * 7)) && ($contact_time > $failure_time))
166 // 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
167 if ((($now - $contact_time) > (60 * 60 * 24 * 7)) && (($now - $created_time) > (60 * 60 * 24 * 7)) && (($now - $failure_time) < (60 * 60 * 24 * 7))) {
171 // 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
172 if ((($now - $contact_time) > (60 * 60 * 24 * 30)) && (($now - $created_time) > (60 * 60 * 24 * 30)) && (($now - $failure_time) < (60 * 60 * 24 * 30))) {
180 * Checks the state of the given server.
182 * @param string $server_url URL of the given server
183 * @param string $network Network value that is used, when detection failed
184 * @param boolean $force Force an update.
185 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
187 * @return boolean 'true' if server seems vital
189 public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false)
191 $server_url = self::cleanURL($server_url);
193 if ($server_url == '') {
197 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
198 if (DBA::isResult($gserver)) {
199 if ($gserver['created'] <= DBA::NULL_DATETIME) {
200 $fields = ['created' => DateTimeFormat::utcNow()];
201 $condition = ['nurl' => Strings::normaliseLink($server_url)];
202 DBA::update('gserver', $fields, $condition);
205 $last_contact = $gserver['last_contact'];
206 $last_failure = $gserver['last_failure'];
208 // See discussion under https://forum.friendi.ca/display/0b6b25a8135aabc37a5a0f5684081633
209 // It can happen that a zero date is in the database, but storing it again is forbidden.
210 if ($last_contact < DBA::NULL_DATETIME) {
211 $last_contact = DBA::NULL_DATETIME;
214 if ($last_failure < DBA::NULL_DATETIME) {
215 $last_failure = DBA::NULL_DATETIME;
218 if (!$force && !self::updateNeeded($gserver['created'], '', $last_failure, $last_contact)) {
219 Logger::info('No update needed', ['server' => $server_url]);
220 return ($last_contact >= $last_failure);
222 Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force, 'Created' => $gserver['created'], 'Failure' => $last_failure, 'Contact' => $last_contact]);
224 Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
227 return self::detect($server_url, $network, $only_nodeinfo);
231 * Set failed server status
235 private static function setFailure(string $url)
237 if (DBA::exists('gserver', ['nurl' => Strings::normaliseLink($url)])) {
238 DBA::update('gserver', ['failed' => true, 'last_failure' => DateTimeFormat::utcNow(), 'detection-method' => null],
239 ['nurl' => Strings::normaliseLink($url)]);
240 Logger::info('Set failed status for existing server', ['url' => $url]);
243 DBA::insert('gserver', ['url' => $url, 'nurl' => Strings::normaliseLink($url),
244 'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
245 'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
246 Logger::info('Set failed status for new server', ['url' => $url]);
250 * Remove unwanted content from the given URL
253 * @return string cleaned URL
255 public static function cleanURL(string $url)
257 $url = trim($url, '/');
258 $url = str_replace('/index.php', '', $url);
260 $urlparts = parse_url($url);
261 unset($urlparts['user']);
262 unset($urlparts['pass']);
263 unset($urlparts['query']);
264 unset($urlparts['fragment']);
265 return Network::unparseURL($urlparts);
269 * Return the base URL
272 * @return string base URL
274 private static function getBaseURL(string $url)
276 $urlparts = parse_url(self::cleanURL($url));
277 unset($urlparts['path']);
278 return Network::unparseURL($urlparts);
282 * Detect server data (type, protocol, version number, ...)
283 * The detected data is then updated or inserted in the gserver table.
285 * @param string $url URL of the given server
286 * @param string $network Network value that is used, when detection failed
287 * @param boolean $only_nodeinfo Only use nodeinfo for server detection
289 * @return boolean 'true' if server could be detected
291 public static function detect(string $url, string $network = '', bool $only_nodeinfo = false)
293 Logger::info('Detect server type', ['server' => $url]);
294 $serverdata = ['detection-method' => self::DETECT_MANUAL];
296 $original_url = $url;
298 // Remove URL content that is not supposed to exist for a server url
299 $url = self::cleanURL($url);
302 $baseurl = self::getBaseURL($url);
304 // If the URL missmatches, then we mark the old entry as failure
305 if ($url != $original_url) {
306 DBA::update('gserver', ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()],
307 ['nurl' => Strings::normaliseLink($original_url)]);
310 // When a nodeinfo is present, we don't need to dig further
311 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
312 $curlResult = DI::httpRequest()->get($url . '/.well-known/nodeinfo', false, ['timeout' => $xrd_timeout]);
313 if ($curlResult->isTimeout()) {
314 self::setFailure($url);
318 $nodeinfo = self::fetchNodeinfo($url, $curlResult);
319 if ($only_nodeinfo && empty($nodeinfo)) {
320 Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
321 self::setFailure($url);
325 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
326 if (empty($nodeinfo)) {
327 $nodeinfo = self::fetchStatistics($url);
330 // If that didn't work out well, we use some protocol specific endpoints
331 // For Friendica and Zot based networks we have to dive deeper to reveal more details
332 if (empty($nodeinfo['network']) || in_array($nodeinfo['network'], [Protocol::DFRN, Protocol::ZOT])) {
333 if (!empty($nodeinfo['detection-method'])) {
334 $serverdata['detection-method'] = $nodeinfo['detection-method'];
337 // Fetch the landing page, possibly it reveals some data
338 if (empty($nodeinfo['network'])) {
339 if ($baseurl == $url) {
340 $basedata = $serverdata;
342 $basedata = ['detection-method' => self::DETECT_MANUAL];
345 $curlResult = DI::httpRequest()->get($baseurl, false, ['timeout' => $xrd_timeout]);
346 if ($curlResult->isSuccess()) {
347 $basedata = self::analyseRootHeader($curlResult, $basedata);
348 $basedata = self::analyseRootBody($curlResult, $basedata, $baseurl);
351 if (!$curlResult->isSuccess() || empty($curlResult->getBody()) || self::invalidBody($curlResult->getBody())) {
352 self::setFailure($url);
356 if ($baseurl == $url) {
357 $serverdata = $basedata;
359 // When the base path doesn't seem to contain a social network we try the complete path.
360 // Most detectable system have to be installed in the root directory.
361 // We checked the base to avoid false positives.
362 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout]);
363 if ($curlResult->isSuccess()) {
364 $urldata = self::analyseRootHeader($curlResult, $serverdata);
365 $urldata = self::analyseRootBody($curlResult, $urldata, $url);
367 $comparebase = $basedata;
368 unset($comparebase['info']);
369 unset($comparebase['site_name']);
370 $compareurl = $urldata;
371 unset($compareurl['info']);
372 unset($compareurl['site_name']);
374 // We assume that no one will install the identical system in the root and a subfolder
375 if (!empty(array_diff($comparebase, $compareurl))) {
376 $serverdata = $urldata;
382 if (empty($serverdata['network']) || ($serverdata['network'] == Protocol::ACTIVITYPUB)) {
383 $serverdata = self::detectMastodonAlikes($url, $serverdata);
386 // All following checks are done for systems that always have got a "host-meta" endpoint.
387 // With this check we don't have to waste time and ressources for dead systems.
388 // Also this hopefully prevents us from receiving abuse messages.
389 if (empty($serverdata['network']) && !self::validHostMeta($url)) {
390 self::setFailure($url);
394 if (empty($serverdata['network']) || in_array($serverdata['network'], [Protocol::DFRN, Protocol::ACTIVITYPUB])) {
395 $serverdata = self::detectFriendica($url, $serverdata);
398 // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
399 if (empty($serverdata['network']) || ($serverdata['network'] == Protocol::ZOT)) {
400 $serverdata = self::fetchSiteinfo($url, $serverdata);
403 // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations
404 if (empty($serverdata['network'])) {
405 $serverdata = self::detectHubzilla($url, $serverdata);
408 if (empty($serverdata['network'])) {
409 $serverdata = self::detectNextcloud($url, $serverdata);
412 if (empty($serverdata['network'])) {
413 $serverdata = self::detectGNUSocial($url, $serverdata);
416 $serverdata = array_merge($nodeinfo, $serverdata);
418 $serverdata = $nodeinfo;
421 // Detect the directory type
422 $serverdata['directory-type'] = self::DT_NONE;
423 $serverdata = self::checkPoCo($url, $serverdata);
424 $serverdata = self::checkMastodonDirectory($url, $serverdata);
426 // We can't detect the network type. Possibly it is some system that we don't know yet
427 if (empty($serverdata['network'])) {
428 $serverdata['network'] = Protocol::PHANTOM;
431 // When we hadn't been able to detect the network type, we use the hint from the parameter
432 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
433 $serverdata['network'] = $network;
436 $serverdata['url'] = $url;
437 $serverdata['nurl'] = Strings::normaliseLink($url);
439 // We take the highest number that we do find
440 $registeredUsers = $serverdata['registered-users'] ?? 0;
442 // On an active server there has to be at least a single user
443 if (($serverdata['network'] != Protocol::PHANTOM) && ($registeredUsers == 0)) {
444 $registeredUsers = 1;
447 if ($serverdata['network'] == Protocol::PHANTOM) {
448 $serverdata['registered-users'] = $registeredUsers;
449 $serverdata = self::detectNetworkViaContacts($url, $serverdata);
452 $serverdata['last_contact'] = DateTimeFormat::utcNow();
453 $serverdata['failed'] = false;
455 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
456 if (!DBA::isResult($gserver)) {
457 $serverdata['created'] = DateTimeFormat::utcNow();
458 $ret = DBA::insert('gserver', $serverdata);
459 $id = DBA::lastInsertId();
461 // Don't override the network with 'unknown' when there had been a valid entry before
462 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($gserver['network'])) {
463 unset($serverdata['network']);
466 $ret = DBA::update('gserver', $serverdata, ['nurl' => $serverdata['nurl']]);
467 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
468 if (DBA::isResult($gserver)) {
469 $id = $gserver['id'];
473 if (!empty($serverdata['network']) && !empty($id) && ($serverdata['network'] != Protocol::PHANTOM)) {
474 $gcontacts = DBA::count('gcontact', ['gsid' => $id]);
475 $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
476 $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id]);
477 $max_users = max($gcontacts, $apcontacts, $contacts, $registeredUsers);
478 if ($max_users > $registeredUsers) {
479 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
480 DBA::update('gserver', ['registered-users' => $max_users], ['id' => $id]);
484 if (!empty($serverdata['network']) && in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
485 self::discoverRelay($url);
492 * Fetch relay data from a given server url
494 * @param string $server_url address of the server
495 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
497 private static function discoverRelay(string $server_url)
499 Logger::info('Discover relay data', ['server' => $server_url]);
501 $curlResult = DI::httpRequest()->get($server_url . '/.well-known/x-social-relay');
502 if (!$curlResult->isSuccess()) {
506 $data = json_decode($curlResult->getBody(), true);
507 if (!is_array($data)) {
511 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
512 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
514 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
516 $data['subscribe'] = false;
520 $gserver = DBA::selectFirst('gserver', ['id', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
521 if (!DBA::isResult($gserver)) {
525 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
526 $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
527 DBA::update('gserver', $fields, ['id' => $gserver['id']]);
530 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
532 if ($data['scope'] == 'tags') {
535 foreach ($data['tags'] as $tag) {
536 $tag = mb_strtolower($tag);
537 if (strlen($tag) < 100) {
542 foreach ($tags as $tag) {
543 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], true);
547 // Create or update the relay contact
549 if (isset($data['protocols'])) {
550 if (isset($data['protocols']['diaspora'])) {
551 $fields['network'] = Protocol::DIASPORA;
553 if (isset($data['protocols']['diaspora']['receive'])) {
554 $fields['batch'] = $data['protocols']['diaspora']['receive'];
555 } elseif (is_string($data['protocols']['diaspora'])) {
556 $fields['batch'] = $data['protocols']['diaspora'];
560 if (isset($data['protocols']['dfrn'])) {
561 $fields['network'] = Protocol::DFRN;
563 if (isset($data['protocols']['dfrn']['receive'])) {
564 $fields['batch'] = $data['protocols']['dfrn']['receive'];
565 } elseif (is_string($data['protocols']['dfrn'])) {
566 $fields['batch'] = $data['protocols']['dfrn'];
570 Diaspora::setRelayContact($server_url, $fields);
574 * Fetch server data from '/statistics.json' on the given server
576 * @param string $url URL of the given server
578 * @return array server data
580 private static function fetchStatistics(string $url)
582 $curlResult = DI::httpRequest()->get($url . '/statistics.json');
583 if (!$curlResult->isSuccess()) {
587 $data = json_decode($curlResult->getBody(), true);
592 $serverdata = ['detection-method' => self::DETECT_STATISTICS_JSON];
594 if (!empty($data['version'])) {
595 $serverdata['version'] = $data['version'];
596 // Version numbers on statistics.json are presented with additional info, e.g.:
597 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
598 $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
601 if (!empty($data['name'])) {
602 $serverdata['site_name'] = $data['name'];
605 if (!empty($data['network'])) {
606 $serverdata['platform'] = strtolower($data['network']);
608 if ($serverdata['platform'] == 'diaspora') {
609 $serverdata['network'] = Protocol::DIASPORA;
610 } elseif ($serverdata['platform'] == 'friendica') {
611 $serverdata['network'] = Protocol::DFRN;
612 } elseif ($serverdata['platform'] == 'hubzilla') {
613 $serverdata['network'] = Protocol::ZOT;
614 } elseif ($serverdata['platform'] == 'redmatrix') {
615 $serverdata['network'] = Protocol::ZOT;
620 if (!empty($data['registrations_open'])) {
621 $serverdata['register_policy'] = Register::OPEN;
623 $serverdata['register_policy'] = Register::CLOSED;
630 * Detect server type by using the nodeinfo data
632 * @param string $url address of the server
633 * @param CurlResult $curlResult
634 * @return array Server data
635 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
637 private static function fetchNodeinfo(string $url, CurlResult $curlResult)
639 if (!$curlResult->isSuccess()) {
643 $nodeinfo = json_decode($curlResult->getBody(), true);
645 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
652 foreach ($nodeinfo['links'] as $link) {
653 if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
654 Logger::info('Invalid nodeinfo format', ['url' => $url]);
657 if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
658 $nodeinfo1_url = $link['href'];
659 } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
660 $nodeinfo2_url = $link['href'];
664 if ($nodeinfo1_url . $nodeinfo2_url == '') {
670 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
671 if (!empty($nodeinfo2_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
672 $server = self::parseNodeinfo2($nodeinfo2_url);
675 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
676 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
677 $server = self::parseNodeinfo1($nodeinfo1_url);
686 * @param string $nodeinfo_url address of the nodeinfo path
687 * @return array Server data
688 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
690 private static function parseNodeinfo1(string $nodeinfo_url)
692 $curlResult = DI::httpRequest()->get($nodeinfo_url);
694 if (!$curlResult->isSuccess()) {
698 $nodeinfo = json_decode($curlResult->getBody(), true);
700 if (!is_array($nodeinfo)) {
704 $server = ['detection-method' => self::DETECT_NODEINFO_1,
705 'register_policy' => Register::CLOSED];
707 if (!empty($nodeinfo['openRegistrations'])) {
708 $server['register_policy'] = Register::OPEN;
711 if (is_array($nodeinfo['software'])) {
712 if (!empty($nodeinfo['software']['name'])) {
713 $server['platform'] = strtolower($nodeinfo['software']['name']);
716 if (!empty($nodeinfo['software']['version'])) {
717 $server['version'] = $nodeinfo['software']['version'];
718 // Version numbers on Nodeinfo are presented with additional info, e.g.:
719 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
720 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
724 if (!empty($nodeinfo['metadata']['nodeName'])) {
725 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
728 if (!empty($nodeinfo['usage']['users']['total'])) {
729 $server['registered-users'] = $nodeinfo['usage']['users']['total'];
732 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
734 foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
735 $protocols[$protocol] = true;
738 if (!empty($protocols['friendica'])) {
739 $server['network'] = Protocol::DFRN;
740 } elseif (!empty($protocols['activitypub'])) {
741 $server['network'] = Protocol::ACTIVITYPUB;
742 } elseif (!empty($protocols['diaspora'])) {
743 $server['network'] = Protocol::DIASPORA;
744 } elseif (!empty($protocols['ostatus'])) {
745 $server['network'] = Protocol::OSTATUS;
746 } elseif (!empty($protocols['gnusocial'])) {
747 $server['network'] = Protocol::OSTATUS;
748 } elseif (!empty($protocols['zot'])) {
749 $server['network'] = Protocol::ZOT;
753 if (empty($server)) {
763 * @param string $nodeinfo_url address of the nodeinfo path
764 * @return array Server data
765 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
767 private static function parseNodeinfo2(string $nodeinfo_url)
769 $curlResult = DI::httpRequest()->get($nodeinfo_url);
770 if (!$curlResult->isSuccess()) {
774 $nodeinfo = json_decode($curlResult->getBody(), true);
776 if (!is_array($nodeinfo)) {
780 $server = ['detection-method' => self::DETECT_NODEINFO_2,
781 'register_policy' => Register::CLOSED];
783 if (!empty($nodeinfo['openRegistrations'])) {
784 $server['register_policy'] = Register::OPEN;
787 if (is_array($nodeinfo['software'])) {
788 if (!empty($nodeinfo['software']['name'])) {
789 $server['platform'] = strtolower($nodeinfo['software']['name']);
792 if (!empty($nodeinfo['software']['version'])) {
793 $server['version'] = $nodeinfo['software']['version'];
794 // Version numbers on Nodeinfo are presented with additional info, e.g.:
795 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
796 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
800 if (!empty($nodeinfo['metadata']['nodeName'])) {
801 $server['site_name'] = $nodeinfo['metadata']['nodeName'];
804 if (!empty($nodeinfo['usage']['users']['total'])) {
805 $server['registered-users'] = $nodeinfo['usage']['users']['total'];
808 if (!empty($nodeinfo['protocols'])) {
810 foreach ($nodeinfo['protocols'] as $protocol) {
811 $protocols[$protocol] = true;
814 if (!empty($protocols['dfrn'])) {
815 $server['network'] = Protocol::DFRN;
816 } elseif (!empty($protocols['activitypub'])) {
817 $server['network'] = Protocol::ACTIVITYPUB;
818 } elseif (!empty($protocols['diaspora'])) {
819 $server['network'] = Protocol::DIASPORA;
820 } elseif (!empty($protocols['ostatus'])) {
821 $server['network'] = Protocol::OSTATUS;
822 } elseif (!empty($protocols['gnusocial'])) {
823 $server['network'] = Protocol::OSTATUS;
824 } elseif (!empty($protocols['zot'])) {
825 $server['network'] = Protocol::ZOT;
829 if (empty($server)) {
837 * Fetch server information from a 'siteinfo.json' file on the given server
839 * @param string $url URL of the given server
840 * @param array $serverdata array with server data
842 * @return array server data
844 private static function fetchSiteinfo(string $url, array $serverdata)
846 $curlResult = DI::httpRequest()->get($url . '/siteinfo.json');
847 if (!$curlResult->isSuccess()) {
851 $data = json_decode($curlResult->getBody(), true);
856 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
857 $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
860 if (!empty($data['url'])) {
861 $serverdata['platform'] = strtolower($data['platform']);
862 $serverdata['version'] = $data['version'];
865 if (!empty($data['plugins'])) {
866 if (in_array('pubcrawl', $data['plugins'])) {
867 $serverdata['network'] = Protocol::ACTIVITYPUB;
868 } elseif (in_array('diaspora', $data['plugins'])) {
869 $serverdata['network'] = Protocol::DIASPORA;
870 } elseif (in_array('gnusoc', $data['plugins'])) {
871 $serverdata['network'] = Protocol::OSTATUS;
873 $serverdata['network'] = Protocol::ZOT;
877 if (!empty($data['site_name'])) {
878 $serverdata['site_name'] = $data['site_name'];
881 if (!empty($data['channels_total'])) {
882 $serverdata['registered-users'] = $data['channels_total'];
885 if (!empty($data['register_policy'])) {
886 switch ($data['register_policy']) {
887 case 'REGISTER_OPEN':
888 $serverdata['register_policy'] = Register::OPEN;
891 case 'REGISTER_APPROVE':
892 $serverdata['register_policy'] = Register::APPROVE;
895 case 'REGISTER_CLOSED':
897 $serverdata['register_policy'] = Register::CLOSED;
906 * Checks if the server contains a valid host meta file
908 * @param string $url URL of the given server
910 * @return boolean 'true' if the server seems to be vital
912 private static function validHostMeta(string $url)
914 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
915 $curlResult = DI::httpRequest()->get($url . '/.well-known/host-meta', false, ['timeout' => $xrd_timeout]);
916 if (!$curlResult->isSuccess()) {
920 $xrd = XML::parseString($curlResult->getBody());
921 if (!is_object($xrd)) {
925 $elements = XML::elementToArray($xrd);
926 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
931 foreach ($elements['xrd']['link'] as $link) {
932 // When there is more than a single "link" element, the array looks slightly different
933 if (!empty($link['@attributes'])) {
934 $link = $link['@attributes'];
937 if (empty($link['rel']) || empty($link['template'])) {
941 if ($link['rel'] == 'lrdd') {
942 // When the webfinger host is the same like the system host, it should be ok.
943 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
951 * Detect the network of the given server via their known contacts
953 * @param string $url URL of the given server
954 * @param array $serverdata array with server data
956 * @return array server data
958 private static function detectNetworkViaContacts(string $url, array $serverdata)
962 $gcontacts = DBA::select('gcontact', ['url', 'nurl'], ['server_url' => [$url, $serverdata['nurl']]]);
963 while ($gcontact = DBA::fetch($gcontacts)) {
964 $contacts[$gcontact['nurl']] = $gcontact['url'];
966 DBA::close($gcontacts);
968 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $serverdata['nurl']]]);
969 while ($apcontact = DBA::fetch($apcontacts)) {
970 $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
972 DBA::close($apcontacts);
974 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $serverdata['nurl']]]);
975 while ($pcontact = DBA::fetch($pcontacts)) {
976 $contacts[$pcontact['nurl']] = $pcontact['url'];
978 DBA::close($pcontacts);
980 if (empty($contacts)) {
984 foreach ($contacts as $contact) {
985 $probed = Contact::getByURL($contact);
986 if (!empty($probed) && in_array($probed['network'], Protocol::FEDERATED)) {
987 $serverdata['network'] = $probed['network'];
992 $serverdata['registered-users'] = max($serverdata['registered-users'], count($contacts));
998 * Checks if the given server does have a '/poco' endpoint.
999 * This is used for the 'PortableContact' functionality,
1000 * which is used by both Friendica and Hubzilla.
1002 * @param string $url URL of the given server
1003 * @param array $serverdata array with server data
1005 * @return array server data
1007 private static function checkPoCo(string $url, array $serverdata)
1009 $serverdata['poco'] = '';
1011 $curlResult = DI::httpRequest()->get($url . '/poco');
1012 if (!$curlResult->isSuccess()) {
1016 $data = json_decode($curlResult->getBody(), true);
1021 if (!empty($data['totalResults'])) {
1022 $registeredUsers = $serverdata['registered-users'] ?? 0;
1023 $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers);
1024 $serverdata['directory-type'] = self::DT_POCO;
1025 $serverdata['poco'] = $url . '/poco';
1032 * Checks if the given server does have a Mastodon style directory endpoint.
1034 * @param string $url URL of the given server
1035 * @param array $serverdata array with server data
1037 * @return array server data
1039 public static function checkMastodonDirectory(string $url, array $serverdata)
1041 $curlResult = DI::httpRequest()->get($url . '/api/v1/directory?limit=1');
1042 if (!$curlResult->isSuccess()) {
1046 $data = json_decode($curlResult->getBody(), true);
1051 if (count($data) == 1) {
1052 $serverdata['directory-type'] = self::DT_MASTODON;
1059 * Detects the version number of a given server when it was a NextCloud installation
1061 * @param string $url URL of the given server
1062 * @param array $serverdata array with server data
1064 * @return array server data
1066 private static function detectNextcloud(string $url, array $serverdata)
1068 $curlResult = DI::httpRequest()->get($url . '/status.php');
1070 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1074 $data = json_decode($curlResult->getBody(), true);
1079 if (!empty($data['version'])) {
1080 $serverdata['platform'] = 'nextcloud';
1081 $serverdata['version'] = $data['version'];
1082 $serverdata['network'] = Protocol::ACTIVITYPUB;
1084 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1085 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1093 * Detects data from a given server url if it was a mastodon alike system
1095 * @param string $url URL of the given server
1096 * @param array $serverdata array with server data
1098 * @return array server data
1100 private static function detectMastodonAlikes(string $url, array $serverdata)
1102 $curlResult = DI::httpRequest()->get($url . '/api/v1/instance');
1104 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1108 $data = json_decode($curlResult->getBody(), true);
1113 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1114 $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1117 if (!empty($data['version'])) {
1118 $serverdata['platform'] = 'mastodon';
1119 $serverdata['version'] = $data['version'] ?? '';
1120 $serverdata['network'] = Protocol::ACTIVITYPUB;
1123 if (!empty($data['title'])) {
1124 $serverdata['site_name'] = $data['title'];
1127 if (!empty($data['title']) && empty($serverdata['platform']) && empty($serverdata['network'])) {
1128 $serverdata['platform'] = 'mastodon';
1129 $serverdata['network'] = Protocol::ACTIVITYPUB;
1132 if (!empty($data['description'])) {
1133 $serverdata['info'] = trim($data['description']);
1136 if (!empty($data['stats']['user_count'])) {
1137 $serverdata['registered-users'] = $data['stats']['user_count'];
1140 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1141 $serverdata['platform'] = strtolower($matches[1]);
1142 $serverdata['version'] = $matches[2];
1145 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1146 $serverdata['platform'] = 'pleroma';
1147 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1150 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1151 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1152 $serverdata['platform'] = 'pleroma';
1159 * Detects data from typical Hubzilla endpoints
1161 * @param string $url URL of the given server
1162 * @param array $serverdata array with server data
1164 * @return array server data
1166 private static function detectHubzilla(string $url, array $serverdata)
1168 $curlResult = DI::httpRequest()->get($url . '/api/statusnet/config.json');
1169 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1173 $data = json_decode($curlResult->getBody(), true);
1174 if (empty($data) || empty($data['site'])) {
1178 if (!empty($data['site']['name'])) {
1179 $serverdata['site_name'] = $data['site']['name'];
1182 if (!empty($data['site']['platform'])) {
1183 $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1184 $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1185 $serverdata['network'] = Protocol::ZOT;
1188 if (!empty($data['site']['hubzilla'])) {
1189 $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1190 $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1191 $serverdata['network'] = Protocol::ZOT;
1194 if (!empty($data['site']['redmatrix'])) {
1195 if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1196 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1197 } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1198 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1201 $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1202 $serverdata['network'] = Protocol::ZOT;
1206 $inviteonly = false;
1209 if (!empty($data['site']['closed'])) {
1210 $closed = self::toBoolean($data['site']['closed']);
1213 if (!empty($data['site']['private'])) {
1214 $private = self::toBoolean($data['site']['private']);
1217 if (!empty($data['site']['inviteonly'])) {
1218 $inviteonly = self::toBoolean($data['site']['inviteonly']);
1221 if (!$closed && !$private and $inviteonly) {
1222 $serverdata['register_policy'] = Register::APPROVE;
1223 } elseif (!$closed && !$private) {
1224 $serverdata['register_policy'] = Register::OPEN;
1226 $serverdata['register_policy'] = Register::CLOSED;
1229 if (!empty($serverdata['network']) && in_array($serverdata['detection-method'],
1230 [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1231 $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1238 * Converts input value to a boolean value
1240 * @param string|integer $val
1244 private static function toBoolean($val)
1246 if (($val == 'true') || ($val == 1)) {
1248 } elseif (($val == 'false') || ($val == 0)) {
1256 * Detect if the URL belongs to a GNU Social server
1258 * @param string $url URL of the given server
1259 * @param array $serverdata array with server data
1261 * @return array server data
1263 private static function detectGNUSocial(string $url, array $serverdata)
1265 // Test for GNU Social
1266 $curlResult = DI::httpRequest()->get($url . '/api/gnusocial/version.json');
1267 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1268 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1269 $serverdata['platform'] = 'gnusocial';
1270 // Remove junk that some GNU Social servers return
1271 $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1272 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1273 $serverdata['version'] = trim($serverdata['version'], '"');
1274 $serverdata['network'] = Protocol::OSTATUS;
1276 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1277 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1283 // Test for Statusnet
1284 $curlResult = DI::httpRequest()->get($url . '/api/statusnet/version.json');
1285 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1286 ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1288 // Remove junk that some GNU Social servers return
1289 $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1290 $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1291 $serverdata['version'] = trim($serverdata['version'], '"');
1293 if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1294 $serverdata['platform'] = 'pleroma';
1295 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1296 $serverdata['network'] = Protocol::ACTIVITYPUB;
1298 $serverdata['platform'] = 'statusnet';
1299 $serverdata['network'] = Protocol::OSTATUS;
1302 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1303 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1311 * Detect if the URL belongs to a Friendica server
1313 * @param string $url URL of the given server
1314 * @param array $serverdata array with server data
1316 * @return array server data
1318 private static function detectFriendica(string $url, array $serverdata)
1320 $curlResult = DI::httpRequest()->get($url . '/friendica/json');
1321 if (!$curlResult->isSuccess()) {
1322 $curlResult = DI::httpRequest()->get($url . '/friendika/json');
1324 $platform = 'Friendika';
1327 $platform = 'Friendica';
1330 if (!$curlResult->isSuccess()) {
1334 $data = json_decode($curlResult->getBody(), true);
1335 if (empty($data) || empty($data['version'])) {
1339 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1340 $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1343 $serverdata['network'] = Protocol::DFRN;
1344 $serverdata['version'] = $data['version'];
1346 if (!empty($data['no_scrape_url'])) {
1347 $serverdata['noscrape'] = $data['no_scrape_url'];
1350 if (!empty($data['site_name'])) {
1351 $serverdata['site_name'] = $data['site_name'];
1354 if (!empty($data['info'])) {
1355 $serverdata['info'] = trim($data['info']);
1358 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1359 switch ($register_policy) {
1360 case 'REGISTER_OPEN':
1361 $serverdata['register_policy'] = Register::OPEN;
1364 case 'REGISTER_APPROVE':
1365 $serverdata['register_policy'] = Register::APPROVE;
1368 case 'REGISTER_CLOSED':
1369 case 'REGISTER_INVITATION':
1370 $serverdata['register_policy'] = Register::CLOSED;
1373 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
1374 $serverdata['register_policy'] = Register::CLOSED;
1378 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
1384 * Analyses the landing page of a given server for hints about type and system of that server
1386 * @param object $curlResult result of curl execution
1387 * @param array $serverdata array with server data
1388 * @param string $url Server URL
1390 * @return array server data
1392 private static function analyseRootBody($curlResult, array $serverdata, string $url)
1394 $doc = new DOMDocument();
1395 @$doc->loadHTML($curlResult->getBody());
1396 $xpath = new DOMXPath($doc);
1398 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
1399 if (!empty($title)) {
1400 $serverdata['site_name'] = $title;
1403 $list = $xpath->query('//meta[@name]');
1405 foreach ($list as $node) {
1407 if ($node->attributes->length) {
1408 foreach ($node->attributes as $attribute) {
1409 $value = trim($attribute->value);
1410 if (empty($value)) {
1414 $attr[$attribute->name] = $value;
1417 if (empty($attr['name']) || empty($attr['content'])) {
1422 if ($attr['name'] == 'description') {
1423 $serverdata['info'] = $attr['content'];
1426 if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
1427 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad'])) {
1428 $serverdata['platform'] = strtolower($attr['content']);
1429 if (in_array($attr['content'], ['Misskey', 'Write.as'])) {
1430 $serverdata['network'] = Protocol::ACTIVITYPUB;
1433 if (($attr['name'] == 'generator') && (empty($serverdata['platform']) || (substr(strtolower($attr['content']), 0, 9) == 'wordpress'))) {
1434 $serverdata['platform'] = strtolower($attr['content']);
1435 $version_part = explode(' ', $attr['content']);
1437 if (count($version_part) == 2) {
1438 if (in_array($version_part[0], ['WordPress'])) {
1439 $serverdata['platform'] = strtolower($version_part[0]);
1440 $serverdata['version'] = $version_part[1];
1442 // We still do need a reliable test if some AP plugin is activated
1443 if (DBA::exists('apcontact', ['baseurl' => $url])) {
1444 $serverdata['network'] = Protocol::ACTIVITYPUB;
1446 $serverdata['network'] = Protocol::FEED;
1449 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1450 $serverdata['detection-method'] = self::DETECT_BODY;
1453 if (in_array($version_part[0], ['Friendika', 'Friendica'])) {
1454 $serverdata['platform'] = strtolower($version_part[0]);
1455 $serverdata['version'] = $version_part[1];
1456 $serverdata['network'] = Protocol::DFRN;
1462 $list = $xpath->query('//meta[@property]');
1464 foreach ($list as $node) {
1466 if ($node->attributes->length) {
1467 foreach ($node->attributes as $attribute) {
1468 $value = trim($attribute->value);
1469 if (empty($value)) {
1473 $attr[$attribute->name] = $value;
1476 if (empty($attr['property']) || empty($attr['content'])) {
1481 if ($attr['property'] == 'og:site_name') {
1482 $serverdata['site_name'] = $attr['content'];
1485 if ($attr['property'] == 'og:description') {
1486 $serverdata['info'] = $attr['content'];
1489 if ($attr['property'] == 'og:platform') {
1490 $serverdata['platform'] = strtolower($attr['content']);
1492 if (in_array($attr['content'], ['PeerTube'])) {
1493 $serverdata['network'] = Protocol::ACTIVITYPUB;
1497 if ($attr['property'] == 'generator') {
1498 $serverdata['platform'] = strtolower($attr['content']);
1500 if (in_array($attr['content'], ['hubzilla'])) {
1501 // We later check which compatible protocol modules are loaded.
1502 $serverdata['network'] = Protocol::ZOT;
1507 if (!empty($serverdata['network']) && ($serverdata['detection-method'] == self::DETECT_MANUAL)) {
1508 $serverdata['detection-method'] = self::DETECT_BODY;
1515 * Analyses the header data of a given server for hints about type and system of that server
1517 * @param object $curlResult result of curl execution
1518 * @param array $serverdata array with server data
1520 * @return array server data
1522 private static function analyseRootHeader($curlResult, array $serverdata)
1524 if ($curlResult->getHeader('server') == 'Mastodon') {
1525 $serverdata['platform'] = 'mastodon';
1526 $serverdata['network'] = Protocol::ACTIVITYPUB;
1527 } elseif ($curlResult->inHeader('x-diaspora-version')) {
1528 $serverdata['platform'] = 'diaspora';
1529 $serverdata['network'] = Protocol::DIASPORA;
1530 $serverdata['version'] = $curlResult->getHeader('x-diaspora-version');
1531 } elseif ($curlResult->inHeader('x-friendica-version')) {
1532 $serverdata['platform'] = 'friendica';
1533 $serverdata['network'] = Protocol::DFRN;
1534 $serverdata['version'] = $curlResult->getHeader('x-friendica-version');
1539 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1540 $serverdata['detection-method'] = self::DETECT_HEADER;
1547 * Test if the body contains valid content
1549 * @param string $body
1552 private static function invalidBody(string $body)
1554 // Currently we only test for a HTML element.
1555 // Possibly we enhance this in the future.
1556 return !strpos($body, '>');
1560 * Update the user directory of a given gserver record
1562 * @param array $gserver gserver record
1564 public static function updateDirectory(array $gserver)
1566 /// @todo Add Mastodon API directory
1568 if (!empty($gserver['poco'])) {
1569 PortableContact::discoverSingleServer($gserver['id']);
1574 * Update GServer entries
1576 public static function discover()
1578 // Update the server list
1579 self::discoverFederation();
1583 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
1585 if ($requery_days == 0) {
1589 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
1591 $gservers = DBA::p("SELECT `id`, `url`, `nurl`, `network`, `poco`
1595 AND `last_poco_query` < ?
1596 ORDER BY RAND()", $last_update
1599 while ($gserver = DBA::fetch($gservers)) {
1600 if (!GServer::check($gserver['url'], $gserver['network'])) {
1601 // The server is not reachable? Okay, then we will try it later
1602 $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1603 DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);
1607 Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1608 Worker::add(PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
1610 if (--$no_of_queries == 0) {
1615 DBA::close($gservers);
1619 * Discover federated servers
1621 private static function discoverFederation()
1623 $last = DI::config()->get('poco', 'last_federation_discovery');
1626 $next = $last + (24 * 60 * 60);
1628 if ($next > time()) {
1633 // Discover federated servers
1634 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
1635 foreach ($protocols as $protocol) {
1636 $query = '{nodes(protocol:"' . $protocol . '"){host}}';
1637 $curlResult = DI::httpRequest()->fetchUrl('https://the-federation.info/graphql?query=' . urlencode($query));
1638 if (!empty($curlResult)) {
1639 $data = json_decode($curlResult, true);
1640 if (!empty($data['data']['nodes'])) {
1641 foreach ($data['data']['nodes'] as $server) {
1642 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
1643 Worker::add(PRIORITY_LOW, 'UpdateGServer', 'https://' . $server['host'], true);
1649 // Disvover Mastodon servers
1650 $accesstoken = DI::config()->get('system', 'instances_social_key');
1652 if (!empty($accesstoken)) {
1653 $api = 'https://instances.social/api/1.0/instances/list?count=0';
1654 $header = ['Authorization: Bearer '.$accesstoken];
1655 $curlResult = DI::httpRequest()->get($api, false, ['headers' => $header]);
1657 if ($curlResult->isSuccess()) {
1658 $servers = json_decode($curlResult->getBody(), true);
1660 foreach ($servers['instances'] as $server) {
1661 $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
1662 Worker::add(PRIORITY_LOW, 'UpdateGServer', $url);
1667 DI::config()->set('poco', 'last_federation_discovery', time());