]> git.mxchange.org Git - friendica.git/blob - src/Model/GServer.php
Merge pull request #11259 from annando/conversation-receivers
[friendica.git] / src / Model / GServer.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Model;
23
24 use DOMDocument;
25 use DOMXPath;
26 use Exception;
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;
33 use Friendica\DI;
34 use Friendica\Module\Register;
35 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
36 use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses;
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;
42
43 /**
44  * This class handles GServer related functions
45  */
46 class GServer
47 {
48         // Directory types
49         const DT_NONE = 0;
50         const DT_POCO = 1;
51         const DT_MASTODON = 2;
52
53         // Methods to detect server types
54
55         // Non endpoint specific methods
56         const DETECT_MANUAL = 0;
57         const DETECT_HEADER = 1;
58         const DETECT_BODY = 2;
59
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;
70         const DETECT_PUMPIO = 19;
71
72         // Standardized endpoints
73         const DETECT_STATISTICS_JSON = 100;
74         const DETECT_NODEINFO_1 = 101;
75         const DETECT_NODEINFO_2 = 102;
76
77         /**
78          * Check for the existance of a server and adds it in the background if not existant
79          *
80          * @param string $url
81          * @param boolean $only_nodeinfo
82          * @return void
83          */
84         public static function add(string $url, bool $only_nodeinfo = false)
85         {
86                 if (self::getID($url, false)) {
87                         return;
88                 }
89
90                 Worker::add(PRIORITY_LOW, 'UpdateGServer', $url, $only_nodeinfo);
91         }
92
93         /**
94          * Get the ID for the given server URL
95          *
96          * @param string $url
97          * @param boolean $no_check Don't check if the server hadn't been found
98          * @return int gserver id
99          */
100         public static function getID(string $url, bool $no_check = false)
101         {
102                 if (empty($url)) {
103                         return null;
104                 }
105
106                 $url = self::cleanURL($url);
107
108                 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
109                 if (DBA::isResult($gserver)) {
110                         Logger::info('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
111                         return $gserver['id'];
112                 }
113
114                 if ($no_check || !self::check($url)) {
115                         return null;
116                 }
117
118                 return self::getID($url, true);
119         }
120
121         /**
122          * Retrieves all the servers which base domain are matching the provided domain pattern
123          *
124          * The pattern is a simple fnmatch() pattern with ? for single wildcard and * for multiple wildcard
125          *
126          * @param string $pattern
127          * @return array
128          * @throws Exception
129          */
130         public static function listByDomainPattern(string $pattern): array
131         {
132                 $likePattern = 'http://' . strtr($pattern, ['_' => '\_', '%' => '\%', '?' => '_', '*' => '%']);
133
134                 // The SUBSTRING_INDEX returns everything before the eventual third /, which effectively trims an
135                 // eventual server path and keep only the server domain which we're matching against the pattern.
136                 $sql = "SELECT `gserver`.*, COUNT(*) AS `contacts`
137                         FROM `gserver`
138                         LEFT JOIN `contact` ON `gserver`.`id` = `contact`.`gsid`
139                         WHERE SUBSTRING_INDEX(`gserver`.`nurl`, '/', 3) LIKE ?
140                         AND NOT `gserver`.`failed`
141                         GROUP BY `gserver`.`id`";
142
143                 $stmt = DI::dba()->p($sql, $likePattern);
144
145                 return DI::dba()->toArray($stmt);
146         }
147
148         /**
149          * Checks if the given server is reachable
150          *
151          * @param string  $profile URL of the given profile
152          * @param string  $server  URL of the given server (If empty, taken from profile)
153          * @param string  $network Network value that is used, when detection failed
154          * @param boolean $force   Force an update.
155          *
156          * @return boolean 'true' if server seems vital
157          */
158         public static function reachable(string $profile, string $server = '', string $network = '', bool $force = false)
159         {
160                 if ($server == '') {
161                         $contact = Contact::getByURL($profile, null, ['baseurl']);
162                         if (!empty($contact['baseurl'])) {
163                                 $server = $contact['baseurl'];
164                         }
165                 }
166
167                 if ($server == '') {
168                         return true;
169                 }
170
171                 return self::check($server, $network, $force);
172         }
173
174         public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '')
175         {
176                 // On successful contact process check again next week
177                 if ($success) {
178                         return DateTimeFormat::utc('now +7 day');
179                 }
180
181                 $now = strtotime(DateTimeFormat::utcNow());
182
183                 if ($created > $last_contact) {
184                         $contact_time = strtotime($created);
185                 } else {
186                         $contact_time = strtotime($last_contact);
187                 }
188
189                 // If the last contact was less than 6 hours before then try again in 6 hours
190                 if (($now - $contact_time) < (60 * 60 * 6)) {
191                         return DateTimeFormat::utc('now +6 hour');
192                 }
193
194                 // If the last contact was less than 12 hours before then try again in 12 hours
195                 if (($now - $contact_time) < (60 * 60 * 12)) {
196                         return DateTimeFormat::utc('now +12 hour');
197                 }
198
199                 // If the last contact was less than 24 hours before then try tomorrow again
200                 if (($now - $contact_time) < (60 * 60 * 24)) {
201                         return DateTimeFormat::utc('now +1 day');
202                 }
203
204                 // If the last contact was less than a week before then try again in a week
205                 if (($now - $contact_time) < (60 * 60 * 24 * 7)) {
206                         return DateTimeFormat::utc('now +1 week');
207                 }
208
209                 // If the last contact was less than two weeks before then try again in two week
210                 if (($now - $contact_time) < (60 * 60 * 24 * 14)) {
211                         return DateTimeFormat::utc('now +2 week');
212                 }
213
214                 // If the last contact was less than a month before then try again in a month
215                 if (($now - $contact_time) < (60 * 60 * 24 * 30)) {
216                         return DateTimeFormat::utc('now +1 month');
217                 }
218
219                 // The system hadn't been successul contacted for more than a month, so try again in three months
220                 return DateTimeFormat::utc('now +3 month');
221         }
222
223         /**
224          * Checks the state of the given server.
225          *
226          * @param string  $server_url    URL of the given server
227          * @param string  $network       Network value that is used, when detection failed
228          * @param boolean $force         Force an update.
229          * @param boolean $only_nodeinfo Only use nodeinfo for server detection
230          *
231          * @return boolean 'true' if server seems vital
232          */
233         public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false)
234         {
235                 $server_url = self::cleanURL($server_url);
236                 if ($server_url == '') {
237                         return false;
238                 }
239
240                 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
241                 if (DBA::isResult($gserver)) {
242                         if ($gserver['created'] <= DBA::NULL_DATETIME) {
243                                 $fields = ['created' => DateTimeFormat::utcNow()];
244                                 $condition = ['nurl' => Strings::normaliseLink($server_url)];
245                                 DBA::update('gserver', $fields, $condition);
246                         }
247
248                         if (!$force && (strtotime($gserver['next_contact']) > time())) {
249                                 Logger::info('No update needed', ['server' => $server_url]);
250                                 return (!$gserver['failed']);
251                         }
252                         Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]);
253                 } else {
254                         Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
255                 }
256
257                 return self::detect($server_url, $network, $only_nodeinfo);
258         }
259
260         /**
261          * Set failed server status
262          *
263          * @param string $url
264          */
265         public static function setFailure(string $url)
266         {
267                 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($url)]);
268                 if (DBA::isResult($gserver)) {
269                         $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
270                         DBA::update('gserver', ['failed' => true, 'last_failure' => DateTimeFormat::utcNow(),
271                         'next_contact' => $next_update, 'detection-method' => null],
272                         ['nurl' => Strings::normaliseLink($url)]);
273                         Logger::info('Set failed status for existing server', ['url' => $url]);
274                         return;
275                 }
276                 DBA::insert('gserver', ['url' => $url, 'nurl' => Strings::normaliseLink($url),
277                         'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
278                         'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
279                 Logger::info('Set failed status for new server', ['url' => $url]);
280         }
281
282         /**
283          * Remove unwanted content from the given URL
284          *
285          * @param string $url
286          * @return string cleaned URL
287          */
288         public static function cleanURL(string $url)
289         {
290                 $url = trim($url, '/');
291                 $url = str_replace('/index.php', '', $url);
292
293                 $urlparts = parse_url($url);
294                 unset($urlparts['user']);
295                 unset($urlparts['pass']);
296                 unset($urlparts['query']);
297                 unset($urlparts['fragment']);
298                 return Network::unparseURL($urlparts);
299         }
300
301         /**
302          * Return the base URL
303          *
304          * @param string $url
305          * @return string base URL
306          */
307         private static function getBaseURL(string $url)
308         {
309                 $urlparts = parse_url(self::cleanURL($url));
310                 unset($urlparts['path']);
311                 return Network::unparseURL($urlparts);
312         }
313
314         /**
315          * Detect server data (type, protocol, version number, ...)
316          * The detected data is then updated or inserted in the gserver table.
317          *
318          * @param string  $url           URL of the given server
319          * @param string  $network       Network value that is used, when detection failed
320          * @param boolean $only_nodeinfo Only use nodeinfo for server detection
321          *
322          * @return boolean 'true' if server could be detected
323          */
324         public static function detect(string $url, string $network = '', bool $only_nodeinfo = false)
325         {
326                 Logger::info('Detect server type', ['server' => $url]);
327                 $serverdata = ['detection-method' => self::DETECT_MANUAL];
328
329                 $original_url = $url;
330
331                 // Remove URL content that is not supposed to exist for a server url
332                 $url = self::cleanURL($url);
333
334                 // Get base URL
335                 $baseurl = self::getBaseURL($url);
336
337                 // If the URL missmatches, then we mark the old entry as failure
338                 if ($url != $original_url) {
339                         /// @todo What to do with "next_contact" here?
340                         DBA::update('gserver', ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()],
341                                 ['nurl' => Strings::normaliseLink($original_url)]);
342                 }
343
344                 // When a nodeinfo is present, we don't need to dig further
345                 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
346                 $curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', [HttpClientOptions::TIMEOUT => $xrd_timeout]);
347                 if ($curlResult->isTimeout()) {
348                         self::setFailure($url);
349                         return false;
350                 }
351
352                 // On a redirect follow the new host but mark the old one as failure
353                 if ($curlResult->isSuccess() && !empty($curlResult->getRedirectUrl()) && (parse_url($url, PHP_URL_HOST) != parse_url($curlResult->getRedirectUrl(), PHP_URL_HOST))) {
354                         $curlResult = DI::httpClient()->get($url, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
355                         if (!empty($curlResult->getRedirectUrl()) && parse_url($url, PHP_URL_HOST) != parse_url($curlResult->getRedirectUrl(), PHP_URL_HOST)) {
356                                 Logger::info('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $curlResult->getRedirectUrl()]);
357                                 self::setFailure($url);
358                                 self::detect($curlResult->getRedirectUrl(), $network, $only_nodeinfo);
359                                 return false;
360                         }
361                 }
362
363                 $nodeinfo = self::fetchNodeinfo($url, $curlResult);
364                 if ($only_nodeinfo && empty($nodeinfo)) {
365                         Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
366                         self::setFailure($url);
367                         return false;
368                 }
369
370                 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
371                 if (empty($nodeinfo)) {
372                         $nodeinfo = self::fetchStatistics($url);
373                 }
374
375                 // If that didn't work out well, we use some protocol specific endpoints
376                 // For Friendica and Zot based networks we have to dive deeper to reveal more details
377                 if (empty($nodeinfo['network']) || in_array($nodeinfo['network'], [Protocol::DFRN, Protocol::ZOT])) {
378                         if (!empty($nodeinfo['detection-method'])) {
379                                 $serverdata['detection-method'] = $nodeinfo['detection-method'];
380
381                                 foreach (['registered-users', 'active_users_monthly', 'active-halfyear-users', 'local-posts'] as $field) {
382                                         if (!empty($nodeinfo[$field])) {
383                                                 $serverdata[$field] = $nodeinfo[$field];
384                                         }
385                                 }
386                         }
387
388                         // Fetch the landing page, possibly it reveals some data
389                         if (empty($nodeinfo['network'])) {
390                                 if ($baseurl == $url) {
391                                         $basedata = $serverdata;
392                                 } else {
393                                         $basedata = ['detection-method' => self::DETECT_MANUAL];
394                                 }
395
396                                 $curlResult = DI::httpClient()->get($baseurl, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
397                                 if ($curlResult->isSuccess()) {
398                                         if (!empty($curlResult->getRedirectUrl()) && (parse_url($baseurl, PHP_URL_HOST) != parse_url($curlResult->getRedirectUrl(), PHP_URL_HOST))) {
399                                                 Logger::info('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $curlResult->getRedirectUrl()]);
400                                                 self::setFailure($url);
401                                                 self::detect($curlResult->getRedirectUrl(), $network, $only_nodeinfo);
402                                                 return false;
403                                         }
404
405                                         $basedata = self::analyseRootHeader($curlResult, $basedata);
406                                         $basedata = self::analyseRootBody($curlResult, $basedata, $baseurl);
407                                 }
408
409                                 if (!$curlResult->isSuccess() || empty($curlResult->getBody()) || self::invalidBody($curlResult->getBody())) {
410                                         self::setFailure($url);
411                                         return false;
412                                 }
413
414                                 if ($baseurl == $url) {
415                                         $serverdata = $basedata;
416                                 } else {
417                                         // When the base path doesn't seem to contain a social network we try the complete path.
418                                         // Most detectable system have to be installed in the root directory.
419                                         // We checked the base to avoid false positives.
420                                         $curlResult = DI::httpClient()->get($url, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
421                                         if ($curlResult->isSuccess()) {
422                                                 $urldata = self::analyseRootHeader($curlResult, $serverdata);
423                                                 $urldata = self::analyseRootBody($curlResult, $urldata, $url);
424
425                                                 $comparebase = $basedata;
426                                                 unset($comparebase['info']);
427                                                 unset($comparebase['site_name']);
428                                                 $compareurl = $urldata;
429                                                 unset($compareurl['info']);
430                                                 unset($compareurl['site_name']);
431
432                                                 // We assume that no one will install the identical system in the root and a subfolder
433                                                 if (!empty(array_diff($comparebase, $compareurl))) {
434                                                         $serverdata = $urldata;
435                                                 }
436                                         }
437                                 }
438                         }
439
440                         if (empty($serverdata['network']) || ($serverdata['network'] == Protocol::ACTIVITYPUB)) {
441                                 $serverdata = self::detectMastodonAlikes($url, $serverdata);
442                         }
443
444                         // All following checks are done for systems that always have got a "host-meta" endpoint.
445                         // With this check we don't have to waste time and ressources for dead systems.
446                         // Also this hopefully prevents us from receiving abuse messages.
447                         if (empty($serverdata['network']) && !self::validHostMeta($url)) {
448                                 self::setFailure($url);
449                                 return false;
450                         }
451
452                         if (empty($serverdata['network']) || in_array($serverdata['network'], [Protocol::DFRN, Protocol::ACTIVITYPUB])) {
453                                 $serverdata = self::detectFriendica($url, $serverdata);
454                         }
455
456                         // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
457                         if (empty($serverdata['network']) || ($serverdata['network'] == Protocol::ZOT)) {
458                                 $serverdata = self::fetchSiteinfo($url, $serverdata);
459                         }
460
461                         // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations
462                         if (empty($serverdata['network'])) {
463                                 $serverdata = self::detectHubzilla($url, $serverdata);
464                         }
465
466                         if (empty($serverdata['network']) || in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_BODY])) {
467                                 $serverdata = self::detectPeertube($url, $serverdata);
468                         }
469
470                         if (empty($serverdata['network'])) {
471                                 $serverdata = self::detectNextcloud($url, $serverdata);
472                         }
473
474                         if (empty($serverdata['network'])) {
475                                 $serverdata = self::detectGNUSocial($url, $serverdata);
476                         }
477
478                         if (empty($serverdata['network'])) {
479                                 $serverdata = self::detectPumpIO($url, $serverdata);
480                         }
481
482                         $serverdata = array_merge($nodeinfo, $serverdata);
483                 } else {
484                         $serverdata = $nodeinfo;
485                 }
486
487                 // Detect the directory type
488                 $serverdata['directory-type'] = self::DT_NONE;
489                 $serverdata = self::checkPoCo($url, $serverdata);
490                 $serverdata = self::checkMastodonDirectory($url, $serverdata);
491
492                 // We can't detect the network type. Possibly it is some system that we don't know yet
493                 if (empty($serverdata['network'])) {
494                         $serverdata['network'] = Protocol::PHANTOM;
495                 }
496
497                 // When we hadn't been able to detect the network type, we use the hint from the parameter
498                 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
499                         $serverdata['network'] = $network;
500                 }
501
502                 $serverdata['url'] = $url;
503                 $serverdata['nurl'] = Strings::normaliseLink($url);
504
505                 if (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
506                         $serverdata = self::detectNetworkViaContacts($url, $serverdata);
507                 }
508
509                 if ($serverdata['network'] == Protocol::ACTIVITYPUB) {
510                         $serverdata = self::fetchWeeklyUsage($url, $serverdata);
511                 }
512
513                 $serverdata['registered-users'] = $serverdata['registered-users'] ?? 0;
514
515                 // On an active server there has to be at least a single user
516                 if (!in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) && ($serverdata['registered-users'] == 0)) {
517                         $serverdata['registered-users'] = 1;
518                 } elseif (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
519                         $serverdata['registered-users'] = 0;
520                 }
521
522                 $serverdata['next_contact'] = self::getNextUpdateDate(true);
523
524                 $serverdata['last_contact'] = DateTimeFormat::utcNow();
525                 $serverdata['failed'] = false;
526
527                 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
528                 if (!DBA::isResult($gserver)) {
529                         $serverdata['created'] = DateTimeFormat::utcNow();
530                         $ret = DBA::insert('gserver', $serverdata);
531                         $id = DBA::lastInsertId();
532                 } else {
533                         $ret = DBA::update('gserver', $serverdata, ['nurl' => $serverdata['nurl']]);
534                         $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
535                         if (DBA::isResult($gserver)) {
536                                 $id = $gserver['id'];
537                         }
538                 }
539
540                 // Count the number of known contacts from this server
541                 if (!empty($id) && !in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
542                         $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
543                         $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]);
544                         $max_users = max($apcontacts, $contacts);
545                         if ($max_users > $serverdata['registered-users']) {
546                                 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
547                                 DBA::update('gserver', ['registered-users' => $max_users], ['id' => $id]);
548                         }
549                 }
550
551                 if (!empty($serverdata['network']) && in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
552                         self::discoverRelay($url);
553                 }
554
555                 return $ret;
556         }
557
558         /**
559          * Fetch relay data from a given server url
560          *
561          * @param string $server_url address of the server
562          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
563          */
564         private static function discoverRelay(string $server_url)
565         {
566                 Logger::info('Discover relay data', ['server' => $server_url]);
567
568                 $curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay');
569                 if (!$curlResult->isSuccess()) {
570                         return;
571                 }
572
573                 $data = json_decode($curlResult->getBody(), true);
574                 if (!is_array($data)) {
575                         return;
576                 }
577
578                 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
579                 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
580
581                 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
582                         $data['scope'] = '';
583                         $data['subscribe'] = false;
584                         $data['tags'] = [];
585                 }
586
587                 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
588                 if (!DBA::isResult($gserver)) {
589                         return;
590                 }
591
592                 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
593                         $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
594                         DBA::update('gserver', $fields, ['id' => $gserver['id']]);
595                 }
596
597                 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
598
599                 if ($data['scope'] == 'tags') {
600                         // Avoid duplicates
601                         $tags = [];
602                         foreach ($data['tags'] as $tag) {
603                                 $tag = mb_strtolower($tag);
604                                 if (strlen($tag) < 100) {
605                                         $tags[$tag] = $tag;
606                                 }
607                         }
608
609                         foreach ($tags as $tag) {
610                                 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
611                         }
612                 }
613
614                 // Create or update the relay contact
615                 $fields = [];
616                 if (isset($data['protocols'])) {
617                         if (isset($data['protocols']['diaspora'])) {
618                                 $fields['network'] = Protocol::DIASPORA;
619
620                                 if (isset($data['protocols']['diaspora']['receive'])) {
621                                         $fields['batch'] = $data['protocols']['diaspora']['receive'];
622                                 } elseif (is_string($data['protocols']['diaspora'])) {
623                                         $fields['batch'] = $data['protocols']['diaspora'];
624                                 }
625                         }
626
627                         if (isset($data['protocols']['dfrn'])) {
628                                 $fields['network'] = Protocol::DFRN;
629
630                                 if (isset($data['protocols']['dfrn']['receive'])) {
631                                         $fields['batch'] = $data['protocols']['dfrn']['receive'];
632                                 } elseif (is_string($data['protocols']['dfrn'])) {
633                                         $fields['batch'] = $data['protocols']['dfrn'];
634                                 }
635                         }
636
637                         if (isset($data['protocols']['activitypub'])) {
638                                 $fields['network'] = Protocol::ACTIVITYPUB;
639
640                                 if (!empty($data['protocols']['activitypub']['actor'])) {
641                                         $fields['url'] = $data['protocols']['activitypub']['actor'];
642                                 }
643                                 if (!empty($data['protocols']['activitypub']['receive'])) {
644                                         $fields['batch'] = $data['protocols']['activitypub']['receive'];
645                                 }
646                         }
647                 }
648
649                 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
650
651                 Relay::updateContact($gserver, $fields);
652         }
653
654         /**
655          * Fetch server data from '/statistics.json' on the given server
656          *
657          * @param string $url URL of the given server
658          *
659          * @return array server data
660          */
661         private static function fetchStatistics(string $url)
662         {
663                 $curlResult = DI::httpClient()->get($url . '/statistics.json');
664                 if (!$curlResult->isSuccess()) {
665                         return [];
666                 }
667
668                 $data = json_decode($curlResult->getBody(), true);
669                 if (empty($data)) {
670                         return [];
671                 }
672
673                 $serverdata = ['detection-method' => self::DETECT_STATISTICS_JSON];
674
675                 if (!empty($data['version'])) {
676                         $serverdata['version'] = $data['version'];
677                         // Version numbers on statistics.json are presented with additional info, e.g.:
678                         // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
679                         $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
680                 }
681
682                 if (!empty($data['name'])) {
683                         $serverdata['site_name'] = $data['name'];
684                 }
685
686                 if (!empty($data['network'])) {
687                         $serverdata['platform'] = strtolower($data['network']);
688
689                         if ($serverdata['platform'] == 'diaspora') {
690                                 $serverdata['network'] = Protocol::DIASPORA;
691                         } elseif ($serverdata['platform'] == 'friendica') {
692                                 $serverdata['network'] = Protocol::DFRN;
693                         } elseif ($serverdata['platform'] == 'hubzilla') {
694                                 $serverdata['network'] = Protocol::ZOT;
695                         } elseif ($serverdata['platform'] == 'redmatrix') {
696                                 $serverdata['network'] = Protocol::ZOT;
697                         }
698                 }
699
700                 if (!empty($data['total_users'])) {
701                         $serverdata['registered-users'] = max($data['total_users'], 1);
702                 }
703
704                 if (!empty($data['active_users_monthly'])) {
705                         $serverdata['active-month-users'] = max($data['active_users_monthly'], 0);
706                 }
707
708                 if (!empty($data['active_users_halfyear'])) {
709                         $serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0);
710                 }
711
712                 if (!empty($data['local_posts'])) {
713                         $serverdata['local-posts'] = max($data['local_posts'], 0);
714                 }
715
716                 if (!empty($data['registrations_open'])) {
717                         $serverdata['register_policy'] = Register::OPEN;
718                 } else {
719                         $serverdata['register_policy'] = Register::CLOSED;
720                 }
721
722                 return $serverdata;
723         }
724
725         /**
726          * Detect server type by using the nodeinfo data
727          *
728          * @param string                  $url        address of the server
729          * @param ICanHandleHttpResponses $httpResult
730          *
731          * @return array Server data
732          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
733          */
734         private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult)
735         {
736                 if (!$httpResult->isSuccess()) {
737                         return [];
738                 }
739
740                 $nodeinfo = json_decode($httpResult->getBody(), true);
741
742                 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
743                         return [];
744                 }
745
746                 $nodeinfo1_url = '';
747                 $nodeinfo2_url = '';
748
749                 foreach ($nodeinfo['links'] as $link) {
750                         if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
751                                 Logger::info('Invalid nodeinfo format', ['url' => $url]);
752                                 continue;
753                         }
754                         if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
755                                 $nodeinfo1_url = $link['href'];
756                         } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
757                                 $nodeinfo2_url = $link['href'];
758                         }
759                 }
760
761                 if ($nodeinfo1_url . $nodeinfo2_url == '') {
762                         return [];
763                 }
764
765                 $server = [];
766
767                 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
768                 if (!empty($nodeinfo2_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
769                         $server = self::parseNodeinfo2($nodeinfo2_url);
770                 }
771
772                 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
773                 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
774                         $server = self::parseNodeinfo1($nodeinfo1_url);
775                 }
776
777                 return $server;
778         }
779
780         /**
781          * Parses Nodeinfo 1
782          *
783          * @param string $nodeinfo_url address of the nodeinfo path
784          * @return array Server data
785          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
786          */
787         private static function parseNodeinfo1(string $nodeinfo_url)
788         {
789                 $curlResult = DI::httpClient()->get($nodeinfo_url);
790
791                 if (!$curlResult->isSuccess()) {
792                         return [];
793                 }
794
795                 $nodeinfo = json_decode($curlResult->getBody(), true);
796
797                 if (!is_array($nodeinfo)) {
798                         return [];
799                 }
800
801                 $server = ['detection-method' => self::DETECT_NODEINFO_1,
802                         'register_policy' => Register::CLOSED];
803
804                 if (!empty($nodeinfo['openRegistrations'])) {
805                         $server['register_policy'] = Register::OPEN;
806                 }
807
808                 if (is_array($nodeinfo['software'])) {
809                         if (!empty($nodeinfo['software']['name'])) {
810                                 $server['platform'] = strtolower($nodeinfo['software']['name']);
811                         }
812
813                         if (!empty($nodeinfo['software']['version'])) {
814                                 $server['version'] = $nodeinfo['software']['version'];
815                                 // Version numbers on Nodeinfo are presented with additional info, e.g.:
816                                 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
817                                 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
818                         }
819                 }
820
821                 if (!empty($nodeinfo['metadata']['nodeName'])) {
822                         $server['site_name'] = $nodeinfo['metadata']['nodeName'];
823                 }
824
825                 if (!empty($nodeinfo['usage']['users']['total'])) {
826                         $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
827                 }
828
829                 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
830                         $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
831                 }
832
833                 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
834                         $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
835                 }
836
837                 if (!empty($nodeinfo['usage']['localPosts'])) {
838                         $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
839                 }
840
841                 if (!empty($nodeinfo['usage']['localComments'])) {
842                         $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
843                 }
844
845                 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
846                         $protocols = [];
847                         foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
848                                 $protocols[$protocol] = true;
849                         }
850
851                         if (!empty($protocols['friendica'])) {
852                                 $server['network'] = Protocol::DFRN;
853                         } elseif (!empty($protocols['activitypub'])) {
854                                 $server['network'] = Protocol::ACTIVITYPUB;
855                         } elseif (!empty($protocols['diaspora'])) {
856                                 $server['network'] = Protocol::DIASPORA;
857                         } elseif (!empty($protocols['ostatus'])) {
858                                 $server['network'] = Protocol::OSTATUS;
859                         } elseif (!empty($protocols['gnusocial'])) {
860                                 $server['network'] = Protocol::OSTATUS;
861                         } elseif (!empty($protocols['zot'])) {
862                                 $server['network'] = Protocol::ZOT;
863                         }
864                 }
865
866                 if (empty($server)) {
867                         return [];
868                 }
869
870                 return $server;
871         }
872
873         /**
874          * Parses Nodeinfo 2
875          *
876          * @see https://git.feneas.org/jaywink/nodeinfo2
877          * @param string $nodeinfo_url address of the nodeinfo path
878          * @return array Server data
879          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
880          */
881         private static function parseNodeinfo2(string $nodeinfo_url)
882         {
883                 $curlResult = DI::httpClient()->get($nodeinfo_url);
884                 if (!$curlResult->isSuccess()) {
885                         return [];
886                 }
887
888                 $nodeinfo = json_decode($curlResult->getBody(), true);
889
890                 if (!is_array($nodeinfo)) {
891                         return [];
892                 }
893
894                 $server = ['detection-method' => self::DETECT_NODEINFO_2,
895                         'register_policy' => Register::CLOSED];
896
897                 if (!empty($nodeinfo['openRegistrations'])) {
898                         $server['register_policy'] = Register::OPEN;
899                 }
900
901                 if (is_array($nodeinfo['software'])) {
902                         if (!empty($nodeinfo['software']['name'])) {
903                                 $server['platform'] = strtolower($nodeinfo['software']['name']);
904                         }
905
906                         if (!empty($nodeinfo['software']['version'])) {
907                                 $server['version'] = $nodeinfo['software']['version'];
908                                 // Version numbers on Nodeinfo are presented with additional info, e.g.:
909                                 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
910                                 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
911                         }
912                 }
913
914                 if (!empty($nodeinfo['metadata']['nodeName'])) {
915                         $server['site_name'] = $nodeinfo['metadata']['nodeName'];
916                 }
917
918                 if (!empty($nodeinfo['usage']['users']['total'])) {
919                         $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
920                 }
921
922                 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
923                         $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
924                 }
925
926                 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
927                         $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
928                 }
929
930                 if (!empty($nodeinfo['usage']['localPosts'])) {
931                         $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
932                 }
933
934                 if (!empty($nodeinfo['usage']['localComments'])) {
935                         $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
936                 }
937
938                 if (!empty($nodeinfo['protocols'])) {
939                         $protocols = [];
940                         foreach ($nodeinfo['protocols'] as $protocol) {
941                                 if (is_string($protocol)) {
942                                         $protocols[$protocol] = true;
943                                 }
944                         }
945
946                         if (!empty($protocols['dfrn'])) {
947                                 $server['network'] = Protocol::DFRN;
948                         } elseif (!empty($protocols['activitypub'])) {
949                                 $server['network'] = Protocol::ACTIVITYPUB;
950                         } elseif (!empty($protocols['diaspora'])) {
951                                 $server['network'] = Protocol::DIASPORA;
952                         } elseif (!empty($protocols['ostatus'])) {
953                                 $server['network'] = Protocol::OSTATUS;
954                         } elseif (!empty($protocols['gnusocial'])) {
955                                 $server['network'] = Protocol::OSTATUS;
956                         } elseif (!empty($protocols['zot'])) {
957                                 $server['network'] = Protocol::ZOT;
958                         }
959                 }
960
961                 if (empty($server)) {
962                         return [];
963                 }
964
965                 return $server;
966         }
967
968         /**
969          * Fetch server information from a 'siteinfo.json' file on the given server
970          *
971          * @param string $url        URL of the given server
972          * @param array  $serverdata array with server data
973          *
974          * @return array server data
975          */
976         private static function fetchSiteinfo(string $url, array $serverdata)
977         {
978                 $curlResult = DI::httpClient()->get($url . '/siteinfo.json');
979                 if (!$curlResult->isSuccess()) {
980                         return $serverdata;
981                 }
982
983                 $data = json_decode($curlResult->getBody(), true);
984                 if (empty($data)) {
985                         return $serverdata;
986                 }
987
988                 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
989                         $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
990                 }
991
992                 if (!empty($data['url'])) {
993                         $serverdata['platform'] = strtolower($data['platform']);
994                         $serverdata['version'] = $data['version'];
995                 }
996
997                 if (!empty($data['plugins'])) {
998                         if (in_array('pubcrawl', $data['plugins'])) {
999                                 $serverdata['network'] = Protocol::ACTIVITYPUB;
1000                         } elseif (in_array('diaspora', $data['plugins'])) {
1001                                 $serverdata['network'] = Protocol::DIASPORA;
1002                         } elseif (in_array('gnusoc', $data['plugins'])) {
1003                                 $serverdata['network'] = Protocol::OSTATUS;
1004                         } else {
1005                                 $serverdata['network'] = Protocol::ZOT;
1006                         }
1007                 }
1008
1009                 if (!empty($data['site_name'])) {
1010                         $serverdata['site_name'] = $data['site_name'];
1011                 }
1012
1013                 if (!empty($data['channels_total'])) {
1014                         $serverdata['registered-users'] = max($data['channels_total'], 1);
1015                 }
1016
1017                 if (!empty($data['channels_active_monthly'])) {
1018                         $serverdata['active-month-users'] = max($data['channels_active_monthly'], 0);
1019                 }
1020
1021                 if (!empty($data['channels_active_halfyear'])) {
1022                         $serverdata['active-halfyear-users'] = max($data['channels_active_halfyear'], 0);
1023                 }
1024
1025                 if (!empty($data['local_posts'])) {
1026                         $serverdata['local-posts'] = max($data['local_posts'], 0);
1027                 }
1028
1029                 if (!empty($data['local_comments'])) {
1030                         $serverdata['local-comments'] = max($data['local_comments'], 0);
1031                 }
1032
1033                 if (!empty($data['register_policy'])) {
1034                         switch ($data['register_policy']) {
1035                                 case 'REGISTER_OPEN':
1036                                         $serverdata['register_policy'] = Register::OPEN;
1037                                         break;
1038
1039                                 case 'REGISTER_APPROVE':
1040                                         $serverdata['register_policy'] = Register::APPROVE;
1041                                         break;
1042
1043                                 case 'REGISTER_CLOSED':
1044                                 default:
1045                                         $serverdata['register_policy'] = Register::CLOSED;
1046                                         break;
1047                         }
1048                 }
1049
1050                 return $serverdata;
1051         }
1052
1053         /**
1054          * Checks if the server contains a valid host meta file
1055          *
1056          * @param string $url URL of the given server
1057          *
1058          * @return boolean 'true' if the server seems to be vital
1059          */
1060         private static function validHostMeta(string $url)
1061         {
1062                 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
1063                 $curlResult = DI::httpClient()->get($url . '/.well-known/host-meta', [HttpClientOptions::TIMEOUT => $xrd_timeout]);
1064                 if (!$curlResult->isSuccess()) {
1065                         return false;
1066                 }
1067
1068                 $xrd = XML::parseString($curlResult->getBody());
1069                 if (!is_object($xrd)) {
1070                         return false;
1071                 }
1072
1073                 $elements = XML::elementToArray($xrd);
1074                 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
1075                         return false;
1076                 }
1077
1078                 $valid = false;
1079                 foreach ($elements['xrd']['link'] as $link) {
1080                         // When there is more than a single "link" element, the array looks slightly different
1081                         if (!empty($link['@attributes'])) {
1082                                 $link = $link['@attributes'];
1083                         }
1084
1085                         if (empty($link['rel']) || empty($link['template'])) {
1086                                 continue;
1087                         }
1088
1089                         if ($link['rel'] == 'lrdd') {
1090                                 // When the webfinger host is the same like the system host, it should be ok.
1091                                 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
1092                         }
1093                 }
1094
1095                 return $valid;
1096         }
1097
1098         /**
1099          * Detect the network of the given server via their known contacts
1100          *
1101          * @param string $url        URL of the given server
1102          * @param array  $serverdata array with server data
1103          *
1104          * @return array server data
1105          */
1106         private static function detectNetworkViaContacts(string $url, array $serverdata)
1107         {
1108                 $contacts = [];
1109
1110                 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $serverdata['nurl']]]);
1111                 while ($apcontact = DBA::fetch($apcontacts)) {
1112                         $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1113                 }
1114                 DBA::close($apcontacts);
1115
1116                 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $serverdata['nurl']]]);
1117                 while ($pcontact = DBA::fetch($pcontacts)) {
1118                         $contacts[$pcontact['nurl']] = $pcontact['url'];
1119                 }
1120                 DBA::close($pcontacts);
1121
1122                 if (empty($contacts)) {
1123                         return $serverdata;
1124                 }
1125
1126                 $time = time();
1127                 foreach ($contacts as $contact) {
1128                         $probed = Contact::getByURL($contact, true);
1129                         if (!empty($probed) && !$probed['failed'] && in_array($probed['network'], Protocol::FEDERATED)) {
1130                                 $serverdata['network'] = $probed['network'];
1131                                 break;
1132                         } elseif ((time() - $time) > 10) {
1133                                 // To reduce the stress on remote systems we probe a maximum of 10 seconds
1134                                 break;
1135                         }
1136                 }
1137
1138                 return $serverdata;
1139         }
1140
1141         /**
1142          * Checks if the given server does have a '/poco' endpoint.
1143          * This is used for the 'PortableContact' functionality,
1144          * which is used by both Friendica and Hubzilla.
1145          *
1146          * @param string $url        URL of the given server
1147          * @param array  $serverdata array with server data
1148          *
1149          * @return array server data
1150          */
1151         private static function checkPoCo(string $url, array $serverdata)
1152         {
1153                 $serverdata['poco'] = '';
1154
1155                 $curlResult = DI::httpClient()->get($url . '/poco');
1156                 if (!$curlResult->isSuccess()) {
1157                         return $serverdata;
1158                 }
1159
1160                 $data = json_decode($curlResult->getBody(), true);
1161                 if (empty($data)) {
1162                         return $serverdata;
1163                 }
1164
1165                 if (!empty($data['totalResults'])) {
1166                         $registeredUsers = $serverdata['registered-users'] ?? 0;
1167                         $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1168                         $serverdata['directory-type'] = self::DT_POCO;
1169                         $serverdata['poco'] = $url . '/poco';
1170                 }
1171
1172                 return $serverdata;
1173         }
1174
1175         /**
1176          * Checks if the given server does have a Mastodon style directory endpoint.
1177          *
1178          * @param string $url        URL of the given server
1179          * @param array  $serverdata array with server data
1180          *
1181          * @return array server data
1182          */
1183         public static function checkMastodonDirectory(string $url, array $serverdata)
1184         {
1185                 $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1');
1186                 if (!$curlResult->isSuccess()) {
1187                         return $serverdata;
1188                 }
1189
1190                 $data = json_decode($curlResult->getBody(), true);
1191                 if (empty($data)) {
1192                         return $serverdata;
1193                 }
1194
1195                 if (count($data) == 1) {
1196                         $serverdata['directory-type'] = self::DT_MASTODON;
1197                 }
1198
1199                 return $serverdata;
1200         }
1201
1202         /**
1203          * Detects Peertube via their known endpoint
1204          *
1205          * @param string $url        URL of the given server
1206          * @param array  $serverdata array with server data
1207          *
1208          * @return array server data
1209          */
1210         private static function detectPeertube(string $url, array $serverdata)
1211         {
1212                 $curlResult = DI::httpClient()->get($url . '/api/v1/config');
1213
1214                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1215                         return $serverdata;
1216                 }
1217
1218                 $data = json_decode($curlResult->getBody(), true);
1219                 if (empty($data)) {
1220                         return $serverdata;
1221                 }
1222
1223                 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1224                         $serverdata['platform'] = 'peertube';
1225                         $serverdata['version'] = $data['serverVersion'];
1226                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1227
1228                         if (!empty($data['instance']['name'])) {
1229                                 $serverdata['site_name'] = $data['instance']['name'];
1230                         }
1231
1232                         if (!empty($data['instance']['shortDescription'])) {
1233                                 $serverdata['info'] = $data['instance']['shortDescription'];
1234                         }
1235
1236                         if (!empty($data['signup'])) {
1237                                 if (!empty($data['signup']['allowed'])) {
1238                                         $serverdata['register_policy'] = Register::OPEN;
1239                                 }
1240                         }
1241
1242                         if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1243                                 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1244                         }
1245                 }
1246
1247                 return $serverdata;
1248         }
1249
1250         /**
1251          * Detects the version number of a given server when it was a NextCloud installation
1252          *
1253          * @param string $url        URL of the given server
1254          * @param array  $serverdata array with server data
1255          *
1256          * @return array server data
1257          */
1258         private static function detectNextcloud(string $url, array $serverdata)
1259         {
1260                 $curlResult = DI::httpClient()->get($url . '/status.php');
1261
1262                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1263                         return $serverdata;
1264                 }
1265
1266                 $data = json_decode($curlResult->getBody(), true);
1267                 if (empty($data)) {
1268                         return $serverdata;
1269                 }
1270
1271                 if (!empty($data['version'])) {
1272                         $serverdata['platform'] = 'nextcloud';
1273                         $serverdata['version'] = $data['version'];
1274                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1275
1276                         if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1277                                 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1278                         }
1279                 }
1280
1281                 return $serverdata;
1282         }
1283
1284         private static function fetchWeeklyUsage(string $url, array $serverdata) {
1285                 $curlResult = DI::httpClient()->get($url . '/api/v1/instance/activity');
1286
1287                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1288                         return $serverdata;
1289                 }
1290
1291                 $data = json_decode($curlResult->getBody(), true);
1292                 if (empty($data)) {
1293                         return $serverdata;
1294                 }
1295
1296                 $current_week = [];
1297                 foreach ($data as $week) {
1298                         // Use only data from a full week
1299                         if (empty($week['week']) || (time() - $week['week']) < 7 * 24 * 60 * 60) {
1300                                 continue;
1301                         }
1302
1303                         // Most likely the data is sorted correctly. But we better are safe than sorry
1304                         if (empty($current_week['week']) || ($current_week['week'] < $week['week'])) {
1305                                 $current_week = $week;
1306                         } 
1307                 }
1308
1309                 if (!empty($current_week['logins'])) {
1310                         $serverdata['active-week-users'] = max($current_week['logins'], 0);
1311                 }
1312
1313                 return $serverdata;
1314         }
1315
1316         /**
1317          * Detects data from a given server url if it was a mastodon alike system
1318          *
1319          * @param string $url        URL of the given server
1320          * @param array  $serverdata array with server data
1321          *
1322          * @return array server data
1323          */
1324         private static function detectMastodonAlikes(string $url, array $serverdata)
1325         {
1326                 $curlResult = DI::httpClient()->get($url . '/api/v1/instance');
1327
1328                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1329                         return $serverdata;
1330                 }
1331
1332                 $data = json_decode($curlResult->getBody(), true);
1333                 if (empty($data)) {
1334                         return $serverdata;
1335                 }
1336
1337                 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1338                         $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1339                 }
1340
1341                 if (!empty($data['version'])) {
1342                         $serverdata['platform'] = 'mastodon';
1343                         $serverdata['version'] = $data['version'] ?? '';
1344                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1345                 }
1346
1347                 if (!empty($data['title'])) {
1348                         $serverdata['site_name'] = $data['title'];
1349                 }
1350
1351                 if (!empty($data['title']) && empty($serverdata['platform']) && empty($serverdata['network'])) {
1352                         $serverdata['platform'] = 'mastodon';
1353                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1354                 }
1355
1356                 if (!empty($data['description'])) {
1357                         $serverdata['info'] = trim($data['description']);
1358                 }
1359
1360                 if (!empty($data['stats']['user_count'])) {
1361                         $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1362                 }
1363
1364                 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1365                         $serverdata['platform'] = strtolower($matches[1]);
1366                         $serverdata['version'] = $matches[2];
1367                 }
1368
1369                 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1370                         $serverdata['platform'] = 'pleroma';
1371                         $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1372                 }
1373
1374                 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1375                         $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1376                         $serverdata['platform'] = 'pleroma';
1377                 }
1378
1379                 return $serverdata;
1380         }
1381
1382         /**
1383          * Detects data from typical Hubzilla endpoints
1384          *
1385          * @param string $url        URL of the given server
1386          * @param array  $serverdata array with server data
1387          *
1388          * @return array server data
1389          */
1390         private static function detectHubzilla(string $url, array $serverdata)
1391         {
1392                 $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json');
1393                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1394                         return $serverdata;
1395                 }
1396
1397                 $data = json_decode($curlResult->getBody(), true);
1398                 if (empty($data) || empty($data['site'])) {
1399                         return $serverdata;
1400                 }
1401
1402                 if (!empty($data['site']['name'])) {
1403                         $serverdata['site_name'] = $data['site']['name'];
1404                 }
1405
1406                 if (!empty($data['site']['platform'])) {
1407                         $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1408                         $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1409                         $serverdata['network'] = Protocol::ZOT;
1410                 }
1411
1412                 if (!empty($data['site']['hubzilla'])) {
1413                         $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1414                         $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1415                         $serverdata['network'] = Protocol::ZOT;
1416                 }
1417
1418                 if (!empty($data['site']['redmatrix'])) {
1419                         if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1420                                 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1421                         } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1422                                 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1423                         }
1424
1425                         $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1426                         $serverdata['network'] = Protocol::ZOT;
1427                 }
1428
1429                 $private = false;
1430                 $inviteonly = false;
1431                 $closed = false;
1432
1433                 if (!empty($data['site']['closed'])) {
1434                         $closed = self::toBoolean($data['site']['closed']);
1435                 }
1436
1437                 if (!empty($data['site']['private'])) {
1438                         $private = self::toBoolean($data['site']['private']);
1439                 }
1440
1441                 if (!empty($data['site']['inviteonly'])) {
1442                         $inviteonly = self::toBoolean($data['site']['inviteonly']);
1443                 }
1444
1445                 if (!$closed && !$private and $inviteonly) {
1446                         $serverdata['register_policy'] = Register::APPROVE;
1447                 } elseif (!$closed && !$private) {
1448                         $serverdata['register_policy'] = Register::OPEN;
1449                 } else {
1450                         $serverdata['register_policy'] = Register::CLOSED;
1451                 }
1452
1453                 if (!empty($serverdata['network']) && in_array($serverdata['detection-method'],
1454                         [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1455                         $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1456                 }
1457
1458                 return $serverdata;
1459         }
1460
1461         /**
1462          * Converts input value to a boolean value
1463          *
1464          * @param string|integer $val
1465          *
1466          * @return boolean
1467          */
1468         private static function toBoolean($val)
1469         {
1470                 if (($val == 'true') || ($val == 1)) {
1471                         return true;
1472                 } elseif (($val == 'false') || ($val == 0)) {
1473                         return false;
1474                 }
1475
1476                 return $val;
1477         }
1478
1479         /**
1480          * Detect if the URL belongs to a pump.io server
1481          *
1482          * @param string $url        URL of the given server
1483          * @param array  $serverdata array with server data
1484          *
1485          * @return array server data
1486          */
1487         private static function detectPumpIO(string $url, array $serverdata)
1488         {
1489                 $curlResult = DI::httpClient()->get($url . '/.well-known/host-meta.json');
1490                 if (!$curlResult->isSuccess()) {
1491                         return $serverdata;
1492                 }
1493
1494                 $data = json_decode($curlResult->getBody(), true);
1495                 if (empty($data['links'])) {
1496                         return $serverdata;
1497
1498                 }
1499
1500                 // We are looking for some endpoints that are typical for pump.io
1501                 $trust = 0;
1502                 foreach ($data['links'] as $link) {
1503                         if (empty($link['rel'])) {
1504                                 continue;
1505                         }
1506                         if (in_array($link['rel'], ['registration_endpoint', 'dialback', 'http://apinamespace.org/activitypub/whoami'])) {
1507                                 ++$trust;
1508                         }
1509                 }
1510
1511                 if ($trust == 3) {
1512                         $serverdata['detection-method'] = self::DETECT_PUMPIO;
1513
1514                         $serverdata['platform'] = 'pumpio';
1515                         $serverdata['version']  = '';
1516                         $serverdata['network']  = Protocol::PUMPIO;
1517
1518                         $servers = $curlResult->getHeader('Server');
1519                         foreach ($servers as $server) {
1520                                 if (preg_match("#pump.io/(.*)\s#U", $server, $matches)) {
1521                                         $serverdata['version']  = $matches[1];
1522                                 }
1523                         }
1524                 }
1525
1526                 return $serverdata;
1527         }
1528
1529         /**
1530          * Detect if the URL belongs to a GNU Social server
1531          *
1532          * @param string $url        URL of the given server
1533          * @param array  $serverdata array with server data
1534          *
1535          * @return array server data
1536          */
1537         private static function detectGNUSocial(string $url, array $serverdata)
1538         {
1539                 // Test for GNU Social
1540                 $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json');
1541                 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1542                         ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1543                         $serverdata['platform'] = 'gnusocial';
1544                         // Remove junk that some GNU Social servers return
1545                         $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1546                         $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1547                         $serverdata['version'] = trim($serverdata['version'], '"');
1548                         $serverdata['network'] = Protocol::OSTATUS;
1549
1550                         if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1551                                 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1552                         }
1553
1554                         return $serverdata;
1555                 }
1556
1557                 // Test for Statusnet
1558                 $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json');
1559                 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1560                         ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1561
1562                         // Remove junk that some GNU Social servers return
1563                         $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1564                         $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1565                         $serverdata['version'] = trim($serverdata['version'], '"');
1566
1567                         if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1568                                 $serverdata['platform'] = 'pleroma';
1569                                 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1570                                 $serverdata['network'] = Protocol::ACTIVITYPUB;
1571                         } else {
1572                                 $serverdata['platform'] = 'statusnet';
1573                                 $serverdata['network'] = Protocol::OSTATUS;
1574                         }
1575
1576                         if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1577                                 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1578                         }
1579                 }
1580
1581                 return $serverdata;
1582         }
1583
1584         /**
1585          * Detect if the URL belongs to a Friendica server
1586          *
1587          * @param string $url        URL of the given server
1588          * @param array  $serverdata array with server data
1589          *
1590          * @return array server data
1591          */
1592         private static function detectFriendica(string $url, array $serverdata)
1593         {
1594                 $curlResult = DI::httpClient()->get($url . '/friendica/json');
1595                 if (!$curlResult->isSuccess()) {
1596                         $curlResult = DI::httpClient()->get($url . '/friendika/json');
1597                         $friendika = true;
1598                         $platform = 'Friendika';
1599                 } else {
1600                         $friendika = false;
1601                         $platform = 'Friendica';
1602                 }
1603
1604                 if (!$curlResult->isSuccess()) {
1605                         return $serverdata;
1606                 }
1607
1608                 $data = json_decode($curlResult->getBody(), true);
1609                 if (empty($data) || empty($data['version'])) {
1610                         return $serverdata;
1611                 }
1612
1613                 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1614                         $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1615                 }
1616
1617                 $serverdata['network'] = Protocol::DFRN;
1618                 $serverdata['version'] = $data['version'];
1619
1620                 if (!empty($data['no_scrape_url'])) {
1621                         $serverdata['noscrape'] = $data['no_scrape_url'];
1622                 }
1623
1624                 if (!empty($data['site_name'])) {
1625                         $serverdata['site_name'] = $data['site_name'];
1626                 }
1627
1628                 if (!empty($data['info'])) {
1629                         $serverdata['info'] = trim($data['info']);
1630                 }
1631
1632                 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1633                 switch ($register_policy) {
1634                         case 'REGISTER_OPEN':
1635                                 $serverdata['register_policy'] = Register::OPEN;
1636                                 break;
1637
1638                         case 'REGISTER_APPROVE':
1639                                 $serverdata['register_policy'] = Register::APPROVE;
1640                                 break;
1641
1642                         case 'REGISTER_CLOSED':
1643                         case 'REGISTER_INVITATION':
1644                                 $serverdata['register_policy'] = Register::CLOSED;
1645                                 break;
1646                         default:
1647                                 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
1648                                 $serverdata['register_policy'] = Register::CLOSED;
1649                                 break;
1650                 }
1651
1652                 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
1653
1654                 return $serverdata;
1655         }
1656
1657         /**
1658          * Analyses the landing page of a given server for hints about type and system of that server
1659          *
1660          * @param object $curlResult result of curl execution
1661          * @param array  $serverdata array with server data
1662          * @param string $url        Server URL
1663          *
1664          * @return array server data
1665          */
1666         private static function analyseRootBody($curlResult, array $serverdata, string $url)
1667         {
1668                 if (empty($curlResult->getBody())) {
1669                         return $serverdata;
1670                 }
1671
1672                 // Using only body information we cannot safely detect a lot of systems.
1673                 // So we define a list of platforms that we can detect safely.
1674                 $valid_platforms = ['friendica', 'friendika', 'diaspora', 'mastodon', 'hubzilla', 'misskey', 'peertube', 'wordpress', 'write.as'];
1675
1676                 $doc = new DOMDocument();
1677                 @$doc->loadHTML($curlResult->getBody());
1678                 $xpath = new DOMXPath($doc);
1679
1680                 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
1681                 if (!empty($title)) {
1682                         $serverdata['site_name'] = $title;
1683                 }
1684
1685                 $list = $xpath->query('//meta[@name]');
1686
1687                 foreach ($list as $node) {
1688                         $attr = [];
1689                         if ($node->attributes->length) {
1690                                 foreach ($node->attributes as $attribute) {
1691                                         $value = trim($attribute->value);
1692                                         if (empty($value)) {
1693                                                 continue;
1694                                         }
1695
1696                                         $attr[$attribute->name] = $value;
1697                                 }
1698
1699                                 if (empty($attr['name']) || empty($attr['content'])) {
1700                                         continue;
1701                                 }
1702                         }
1703
1704                         if ($attr['name'] == 'description') {
1705                                 $serverdata['info'] = $attr['content'];
1706                         }
1707
1708                         if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
1709                                 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad'])) {
1710                                 $serverdata['platform'] = strtolower($attr['content']);
1711                                 if (in_array($attr['content'], ['Misskey', 'Write.as'])) {
1712                                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1713                                 }
1714                         }
1715                         if (($attr['name'] == 'generator') && (empty($serverdata['platform']) || (substr(strtolower($attr['content']), 0, 9) == 'wordpress'))) {
1716                                 $serverdata['platform'] = strtolower($attr['content']);
1717                                 $version_part = explode(' ', $attr['content']);
1718
1719                                 if (count($version_part) == 2) {
1720                                         if (in_array($version_part[0], ['WordPress'])) {
1721                                                 $serverdata['platform'] = 'wordpress';
1722                                                 $serverdata['version'] = $version_part[1];
1723
1724                                                 // We still do need a reliable test if some AP plugin is activated
1725                                                 // By now we just check in a later process for some known contacts
1726                                                 $serverdata['network'] = Protocol::FEED;
1727
1728                                                 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1729                                                         $serverdata['detection-method'] = self::DETECT_BODY;
1730                                                 }
1731                                         }
1732                                         if (in_array($version_part[0], ['Friendika', 'Friendica'])) {
1733                                                 $serverdata['platform'] = strtolower($version_part[0]);
1734                                                 $serverdata['version'] = $version_part[1];
1735                                                 $serverdata['network'] = Protocol::DFRN;
1736                                         }
1737                                 }
1738                         }
1739                 }
1740
1741                 $list = $xpath->query('//meta[@property]');
1742
1743                 foreach ($list as $node) {
1744                         $attr = [];
1745                         if ($node->attributes->length) {
1746                                 foreach ($node->attributes as $attribute) {
1747                                         $value = trim($attribute->value);
1748                                         if (empty($value)) {
1749                                                 continue;
1750                                         }
1751
1752                                         $attr[$attribute->name] = $value;
1753                                 }
1754
1755                                 if (empty($attr['property']) || empty($attr['content'])) {
1756                                         continue;
1757                                 }
1758                         }
1759
1760                         if ($attr['property'] == 'og:site_name') {
1761                                 $serverdata['site_name'] = $attr['content'];
1762                         }
1763
1764                         if ($attr['property'] == 'og:description') {
1765                                 $serverdata['info'] = $attr['content'];
1766                         }
1767
1768                         if ($attr['property'] == 'og:platform') {
1769                                 $serverdata['platform'] = strtolower($attr['content']);
1770
1771                                 if (in_array($attr['content'], ['PeerTube'])) {
1772                                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1773                                 }
1774                         }
1775
1776                         if ($attr['property'] == 'generator') {
1777                                 $serverdata['platform'] = strtolower($attr['content']);
1778
1779                                 if (in_array($attr['content'], ['hubzilla'])) {
1780                                         // We later check which compatible protocol modules are loaded.
1781                                         $serverdata['network'] = Protocol::ZOT;
1782                                 }
1783                         }
1784                 }
1785
1786                 if (!empty($serverdata['platform']) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_BODY]) && !in_array($serverdata['platform'], $valid_platforms)) {
1787                         $serverdata['network'] = Protocol::PHANTOM;
1788                         $serverdata['version'] = '';
1789                         $serverdata['detection-method'] = self::DETECT_MANUAL;
1790                 } elseif (!empty($serverdata['network']) && ($serverdata['detection-method'] == self::DETECT_MANUAL)) {
1791                         $serverdata['detection-method'] = self::DETECT_BODY;
1792                 }
1793
1794                 return $serverdata;
1795         }
1796
1797         /**
1798          * Analyses the header data of a given server for hints about type and system of that server
1799          *
1800          * @param object $curlResult result of curl execution
1801          * @param array  $serverdata array with server data
1802          *
1803          * @return array server data
1804          */
1805         private static function analyseRootHeader($curlResult, array $serverdata)
1806         {
1807                 if ($curlResult->getHeader('server') == 'Mastodon') {
1808                         $serverdata['platform'] = 'mastodon';
1809                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1810                 } elseif ($curlResult->inHeader('x-diaspora-version')) {
1811                         $serverdata['platform'] = 'diaspora';
1812                         $serverdata['network'] = Protocol::DIASPORA;
1813                         $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
1814                 } elseif ($curlResult->inHeader('x-friendica-version')) {
1815                         $serverdata['platform'] = 'friendica';
1816                         $serverdata['network'] = Protocol::DFRN;
1817                         $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
1818                 } else {
1819                         return $serverdata;
1820                 }
1821
1822                 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1823                         $serverdata['detection-method'] = self::DETECT_HEADER;
1824                 }
1825
1826                 return $serverdata;
1827         }
1828
1829         /**
1830          * Test if the body contains valid content
1831          *
1832          * @param string $body
1833          * @return boolean
1834          */
1835         private static function invalidBody(string $body)
1836         {
1837                 // Currently we only test for a HTML element.
1838                 // Possibly we enhance this in the future.
1839                 return !strpos($body, '>');
1840         }
1841
1842         /**
1843          * Update GServer entries
1844          */
1845         public static function discover()
1846         {
1847                 // Update the server list
1848                 self::discoverFederation();
1849
1850                 $no_of_queries = 5;
1851
1852                 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
1853
1854                 if ($requery_days == 0) {
1855                         $requery_days = 7;
1856                 }
1857
1858                 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
1859
1860                 $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
1861                         ["NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
1862                         ['order' => ['RAND()']]);
1863
1864                 while ($gserver = DBA::fetch($gservers)) {
1865                         Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1866                         Worker::add(PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
1867
1868                         Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1869                         Worker::add(PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
1870
1871                         $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1872                         DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);
1873
1874                         if (--$no_of_queries == 0) {
1875                                 break;
1876                         }
1877                 }
1878
1879                 DBA::close($gservers);
1880         }
1881
1882         /**
1883          * Discover federated servers
1884          */
1885         private static function discoverFederation()
1886         {
1887                 $last = DI::config()->get('poco', 'last_federation_discovery');
1888
1889                 if ($last) {
1890                         $next = $last + (24 * 60 * 60);
1891
1892                         if ($next > time()) {
1893                                 return;
1894                         }
1895                 }
1896
1897                 // Discover federated servers
1898                 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
1899                 foreach ($protocols as $protocol) {
1900                         $query = '{nodes(protocol:"' . $protocol . '"){host}}';
1901                         $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query));
1902                         if (!empty($curlResult)) {
1903                                 $data = json_decode($curlResult, true);
1904                                 if (!empty($data['data']['nodes'])) {
1905                                         foreach ($data['data']['nodes'] as $server) {
1906                                                 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
1907                                                 self::add('https://' . $server['host'], true);
1908                                         }
1909                                 }
1910                         }
1911                 }
1912
1913                 // Disvover Mastodon servers
1914                 $accesstoken = DI::config()->get('system', 'instances_social_key');
1915
1916                 if (!empty($accesstoken)) {
1917                         $api = 'https://instances.social/api/1.0/instances/list?count=0';
1918                         $curlResult = DI::httpClient()->get($api, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
1919
1920                         if ($curlResult->isSuccess()) {
1921                                 $servers = json_decode($curlResult->getBody(), true);
1922
1923                                 foreach ($servers['instances'] as $server) {
1924                                         $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
1925                                         self::add($url);
1926                                 }
1927                         }
1928                 }
1929
1930                 DI::config()->set('poco', 'last_federation_discovery', time());
1931         }
1932
1933         /**
1934          * Set the protocol for the given server
1935          *
1936          * @param int $gsid     Server id
1937          * @param int $protocol Protocol id
1938          * @return void
1939          * @throws Exception
1940          */
1941         public static function setProtocol(int $gsid, int $protocol)
1942         {
1943                 if (empty($gsid)) {
1944                         return;
1945                 }
1946
1947                 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
1948                 if (!DBA::isResult($gserver)) {
1949                         return;
1950                 }
1951
1952                 $old = $gserver['protocol'];
1953
1954                 if (!is_null($old)) {
1955                         /*
1956                         The priority for the protocols is:
1957                                 1. ActivityPub
1958                                 2. DFRN via Diaspora
1959                                 3. Legacy DFRN
1960                                 4. Diaspora
1961                                 5. OStatus
1962                         */
1963
1964                         // We don't need to change it when nothing is to be changed
1965                         if ($old == $protocol) {
1966                                 return;
1967                         }
1968
1969                         // We don't want to mark a server as OStatus when it had been marked with any other protocol before
1970                         if ($protocol == Post\DeliveryData::OSTATUS) {
1971                                 return;
1972                         }
1973
1974                         // If the server is marked as ActivityPub then we won't change it to anything different
1975                         if ($old == Post\DeliveryData::ACTIVITYPUB) {
1976                                 return;
1977                         }
1978
1979                         // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
1980                         if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
1981                                 return;
1982                         }
1983
1984                         // Don't change it to Diaspora when it is a legacy DFRN server
1985                         if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
1986                                 return;
1987                         }
1988                 }
1989
1990                 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url'], 'callstack' => System::callstack(20)]);
1991                 DBA::update('gserver', ['protocol' => $protocol], ['id' => $gsid]);
1992         }
1993
1994         /**
1995          * Fetch the protocol of the given server
1996          *
1997          * @param int $gsid Server id
1998          * @return int
1999          * @throws Exception
2000          */
2001         public static function getProtocol(int $gsid)
2002         {
2003                 if (empty($gsid)) {
2004                         return null;
2005                 }
2006
2007                 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
2008                 if (DBA::isResult($gserver)) {
2009                         return $gserver['protocol'];
2010                 }
2011
2012                 return null;
2013         }
2014 }