]> git.mxchange.org Git - friendica.git/blob - src/Model/GServer.php
Merge pull request #11318 from annando/issue-11315
[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                         if (empty($serverdata['active-month-users'])) {
551                                 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 30 days')]);
552                                 if ($contacts > 0) {
553                                         Logger::info('Update monthly users', ['id' => $id, 'url' => $serverdata['nurl'], 'monthly-users' => $contacts]);
554                                         DBA::update('gserver', ['active-month-users' => $contacts], ['id' => $id]);
555                                 }
556                         }
557         
558                         if (empty($serverdata['active-halfyear-users'])) {
559                                 $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 180 days')]);
560                                 if ($contacts > 0) {
561                                         Logger::info('Update halfyear users', ['id' => $id, 'url' => $serverdata['nurl'], 'halfyear-users' => $contacts]);
562                                         DBA::update('gserver', ['active-halfyear-users' => $contacts], ['id' => $id]);
563                                 }
564                         }
565                 }
566
567                 if (!empty($serverdata['network']) && in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
568                         self::discoverRelay($url);
569                 }
570
571                 return $ret;
572         }
573
574         /**
575          * Fetch relay data from a given server url
576          *
577          * @param string $server_url address of the server
578          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
579          */
580         private static function discoverRelay(string $server_url)
581         {
582                 Logger::info('Discover relay data', ['server' => $server_url]);
583
584                 $curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay');
585                 if (!$curlResult->isSuccess()) {
586                         return;
587                 }
588
589                 $data = json_decode($curlResult->getBody(), true);
590                 if (!is_array($data)) {
591                         return;
592                 }
593
594                 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
595                 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
596
597                 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
598                         $data['scope'] = '';
599                         $data['subscribe'] = false;
600                         $data['tags'] = [];
601                 }
602
603                 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
604                 if (!DBA::isResult($gserver)) {
605                         return;
606                 }
607
608                 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
609                         $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
610                         DBA::update('gserver', $fields, ['id' => $gserver['id']]);
611                 }
612
613                 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
614
615                 if ($data['scope'] == 'tags') {
616                         // Avoid duplicates
617                         $tags = [];
618                         foreach ($data['tags'] as $tag) {
619                                 $tag = mb_strtolower($tag);
620                                 if (strlen($tag) < 100) {
621                                         $tags[$tag] = $tag;
622                                 }
623                         }
624
625                         foreach ($tags as $tag) {
626                                 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
627                         }
628                 }
629
630                 // Create or update the relay contact
631                 $fields = [];
632                 if (isset($data['protocols'])) {
633                         if (isset($data['protocols']['diaspora'])) {
634                                 $fields['network'] = Protocol::DIASPORA;
635
636                                 if (isset($data['protocols']['diaspora']['receive'])) {
637                                         $fields['batch'] = $data['protocols']['diaspora']['receive'];
638                                 } elseif (is_string($data['protocols']['diaspora'])) {
639                                         $fields['batch'] = $data['protocols']['diaspora'];
640                                 }
641                         }
642
643                         if (isset($data['protocols']['dfrn'])) {
644                                 $fields['network'] = Protocol::DFRN;
645
646                                 if (isset($data['protocols']['dfrn']['receive'])) {
647                                         $fields['batch'] = $data['protocols']['dfrn']['receive'];
648                                 } elseif (is_string($data['protocols']['dfrn'])) {
649                                         $fields['batch'] = $data['protocols']['dfrn'];
650                                 }
651                         }
652
653                         if (isset($data['protocols']['activitypub'])) {
654                                 $fields['network'] = Protocol::ACTIVITYPUB;
655
656                                 if (!empty($data['protocols']['activitypub']['actor'])) {
657                                         $fields['url'] = $data['protocols']['activitypub']['actor'];
658                                 }
659                                 if (!empty($data['protocols']['activitypub']['receive'])) {
660                                         $fields['batch'] = $data['protocols']['activitypub']['receive'];
661                                 }
662                         }
663                 }
664
665                 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
666
667                 Relay::updateContact($gserver, $fields);
668         }
669
670         /**
671          * Fetch server data from '/statistics.json' on the given server
672          *
673          * @param string $url URL of the given server
674          *
675          * @return array server data
676          */
677         private static function fetchStatistics(string $url)
678         {
679                 $curlResult = DI::httpClient()->get($url . '/statistics.json');
680                 if (!$curlResult->isSuccess()) {
681                         return [];
682                 }
683
684                 $data = json_decode($curlResult->getBody(), true);
685                 if (empty($data)) {
686                         return [];
687                 }
688
689                 $serverdata = ['detection-method' => self::DETECT_STATISTICS_JSON];
690
691                 if (!empty($data['version'])) {
692                         $serverdata['version'] = $data['version'];
693                         // Version numbers on statistics.json are presented with additional info, e.g.:
694                         // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
695                         $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
696                 }
697
698                 if (!empty($data['name'])) {
699                         $serverdata['site_name'] = $data['name'];
700                 }
701
702                 if (!empty($data['network'])) {
703                         $serverdata['platform'] = strtolower($data['network']);
704
705                         if ($serverdata['platform'] == 'diaspora') {
706                                 $serverdata['network'] = Protocol::DIASPORA;
707                         } elseif ($serverdata['platform'] == 'friendica') {
708                                 $serverdata['network'] = Protocol::DFRN;
709                         } elseif ($serverdata['platform'] == 'hubzilla') {
710                                 $serverdata['network'] = Protocol::ZOT;
711                         } elseif ($serverdata['platform'] == 'redmatrix') {
712                                 $serverdata['network'] = Protocol::ZOT;
713                         }
714                 }
715
716                 if (!empty($data['total_users'])) {
717                         $serverdata['registered-users'] = max($data['total_users'], 1);
718                 }
719
720                 if (!empty($data['active_users_monthly'])) {
721                         $serverdata['active-month-users'] = max($data['active_users_monthly'], 0);
722                 }
723
724                 if (!empty($data['active_users_halfyear'])) {
725                         $serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0);
726                 }
727
728                 if (!empty($data['local_posts'])) {
729                         $serverdata['local-posts'] = max($data['local_posts'], 0);
730                 }
731
732                 if (!empty($data['registrations_open'])) {
733                         $serverdata['register_policy'] = Register::OPEN;
734                 } else {
735                         $serverdata['register_policy'] = Register::CLOSED;
736                 }
737
738                 return $serverdata;
739         }
740
741         /**
742          * Detect server type by using the nodeinfo data
743          *
744          * @param string                  $url        address of the server
745          * @param ICanHandleHttpResponses $httpResult
746          *
747          * @return array Server data
748          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
749          */
750         private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult)
751         {
752                 if (!$httpResult->isSuccess()) {
753                         return [];
754                 }
755
756                 $nodeinfo = json_decode($httpResult->getBody(), true);
757
758                 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
759                         return [];
760                 }
761
762                 $nodeinfo1_url = '';
763                 $nodeinfo2_url = '';
764
765                 foreach ($nodeinfo['links'] as $link) {
766                         if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
767                                 Logger::info('Invalid nodeinfo format', ['url' => $url]);
768                                 continue;
769                         }
770                         if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
771                                 $nodeinfo1_url = $link['href'];
772                         } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
773                                 $nodeinfo2_url = $link['href'];
774                         }
775                 }
776
777                 if ($nodeinfo1_url . $nodeinfo2_url == '') {
778                         return [];
779                 }
780
781                 $server = [];
782
783                 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
784                 if (!empty($nodeinfo2_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
785                         $server = self::parseNodeinfo2($nodeinfo2_url);
786                 }
787
788                 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
789                 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
790                         $server = self::parseNodeinfo1($nodeinfo1_url);
791                 }
792
793                 return $server;
794         }
795
796         /**
797          * Parses Nodeinfo 1
798          *
799          * @param string $nodeinfo_url address of the nodeinfo path
800          * @return array Server data
801          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
802          */
803         private static function parseNodeinfo1(string $nodeinfo_url)
804         {
805                 $curlResult = DI::httpClient()->get($nodeinfo_url);
806
807                 if (!$curlResult->isSuccess()) {
808                         return [];
809                 }
810
811                 $nodeinfo = json_decode($curlResult->getBody(), true);
812
813                 if (!is_array($nodeinfo)) {
814                         return [];
815                 }
816
817                 $server = ['detection-method' => self::DETECT_NODEINFO_1,
818                         'register_policy' => Register::CLOSED];
819
820                 if (!empty($nodeinfo['openRegistrations'])) {
821                         $server['register_policy'] = Register::OPEN;
822                 }
823
824                 if (is_array($nodeinfo['software'])) {
825                         if (!empty($nodeinfo['software']['name'])) {
826                                 $server['platform'] = strtolower($nodeinfo['software']['name']);
827                         }
828
829                         if (!empty($nodeinfo['software']['version'])) {
830                                 $server['version'] = $nodeinfo['software']['version'];
831                                 // Version numbers on Nodeinfo are presented with additional info, e.g.:
832                                 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
833                                 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
834                         }
835                 }
836
837                 if (!empty($nodeinfo['metadata']['nodeName'])) {
838                         $server['site_name'] = $nodeinfo['metadata']['nodeName'];
839                 }
840
841                 if (!empty($nodeinfo['usage']['users']['total'])) {
842                         $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
843                 }
844
845                 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
846                         $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
847                 }
848
849                 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
850                         $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
851                 }
852
853                 if (!empty($nodeinfo['usage']['localPosts'])) {
854                         $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
855                 }
856
857                 if (!empty($nodeinfo['usage']['localComments'])) {
858                         $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
859                 }
860
861                 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
862                         $protocols = [];
863                         foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
864                                 $protocols[$protocol] = true;
865                         }
866
867                         if (!empty($protocols['friendica'])) {
868                                 $server['network'] = Protocol::DFRN;
869                         } elseif (!empty($protocols['activitypub'])) {
870                                 $server['network'] = Protocol::ACTIVITYPUB;
871                         } elseif (!empty($protocols['diaspora'])) {
872                                 $server['network'] = Protocol::DIASPORA;
873                         } elseif (!empty($protocols['ostatus'])) {
874                                 $server['network'] = Protocol::OSTATUS;
875                         } elseif (!empty($protocols['gnusocial'])) {
876                                 $server['network'] = Protocol::OSTATUS;
877                         } elseif (!empty($protocols['zot'])) {
878                                 $server['network'] = Protocol::ZOT;
879                         }
880                 }
881
882                 if (empty($server)) {
883                         return [];
884                 }
885
886                 return $server;
887         }
888
889         /**
890          * Parses Nodeinfo 2
891          *
892          * @see https://git.feneas.org/jaywink/nodeinfo2
893          * @param string $nodeinfo_url address of the nodeinfo path
894          * @return array Server data
895          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
896          */
897         private static function parseNodeinfo2(string $nodeinfo_url)
898         {
899                 $curlResult = DI::httpClient()->get($nodeinfo_url);
900                 if (!$curlResult->isSuccess()) {
901                         return [];
902                 }
903
904                 $nodeinfo = json_decode($curlResult->getBody(), true);
905
906                 if (!is_array($nodeinfo)) {
907                         return [];
908                 }
909
910                 $server = ['detection-method' => self::DETECT_NODEINFO_2,
911                         'register_policy' => Register::CLOSED];
912
913                 if (!empty($nodeinfo['openRegistrations'])) {
914                         $server['register_policy'] = Register::OPEN;
915                 }
916
917                 if (is_array($nodeinfo['software'])) {
918                         if (!empty($nodeinfo['software']['name'])) {
919                                 $server['platform'] = strtolower($nodeinfo['software']['name']);
920                         }
921
922                         if (!empty($nodeinfo['software']['version'])) {
923                                 $server['version'] = $nodeinfo['software']['version'];
924                                 // Version numbers on Nodeinfo are presented with additional info, e.g.:
925                                 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
926                                 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
927                         }
928                 }
929
930                 if (!empty($nodeinfo['metadata']['nodeName'])) {
931                         $server['site_name'] = $nodeinfo['metadata']['nodeName'];
932                 }
933
934                 if (!empty($nodeinfo['usage']['users']['total'])) {
935                         $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
936                 }
937
938                 if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
939                         $server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
940                 }
941
942                 if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
943                         $server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
944                 }
945
946                 if (!empty($nodeinfo['usage']['localPosts'])) {
947                         $server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
948                 }
949
950                 if (!empty($nodeinfo['usage']['localComments'])) {
951                         $server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
952                 }
953
954                 if (!empty($nodeinfo['protocols'])) {
955                         $protocols = [];
956                         foreach ($nodeinfo['protocols'] as $protocol) {
957                                 if (is_string($protocol)) {
958                                         $protocols[$protocol] = true;
959                                 }
960                         }
961
962                         if (!empty($protocols['dfrn'])) {
963                                 $server['network'] = Protocol::DFRN;
964                         } elseif (!empty($protocols['activitypub'])) {
965                                 $server['network'] = Protocol::ACTIVITYPUB;
966                         } elseif (!empty($protocols['diaspora'])) {
967                                 $server['network'] = Protocol::DIASPORA;
968                         } elseif (!empty($protocols['ostatus'])) {
969                                 $server['network'] = Protocol::OSTATUS;
970                         } elseif (!empty($protocols['gnusocial'])) {
971                                 $server['network'] = Protocol::OSTATUS;
972                         } elseif (!empty($protocols['zot'])) {
973                                 $server['network'] = Protocol::ZOT;
974                         }
975                 }
976
977                 if (empty($server)) {
978                         return [];
979                 }
980
981                 return $server;
982         }
983
984         /**
985          * Fetch server information from a 'siteinfo.json' file on the given server
986          *
987          * @param string $url        URL of the given server
988          * @param array  $serverdata array with server data
989          *
990          * @return array server data
991          */
992         private static function fetchSiteinfo(string $url, array $serverdata)
993         {
994                 $curlResult = DI::httpClient()->get($url . '/siteinfo.json');
995                 if (!$curlResult->isSuccess()) {
996                         return $serverdata;
997                 }
998
999                 $data = json_decode($curlResult->getBody(), true);
1000                 if (empty($data)) {
1001                         return $serverdata;
1002                 }
1003
1004                 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1005                         $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
1006                 }
1007
1008                 if (!empty($data['url'])) {
1009                         $serverdata['platform'] = strtolower($data['platform']);
1010                         $serverdata['version'] = $data['version'];
1011                 }
1012
1013                 if (!empty($data['plugins'])) {
1014                         if (in_array('pubcrawl', $data['plugins'])) {
1015                                 $serverdata['network'] = Protocol::ACTIVITYPUB;
1016                         } elseif (in_array('diaspora', $data['plugins'])) {
1017                                 $serverdata['network'] = Protocol::DIASPORA;
1018                         } elseif (in_array('gnusoc', $data['plugins'])) {
1019                                 $serverdata['network'] = Protocol::OSTATUS;
1020                         } else {
1021                                 $serverdata['network'] = Protocol::ZOT;
1022                         }
1023                 }
1024
1025                 if (!empty($data['site_name'])) {
1026                         $serverdata['site_name'] = $data['site_name'];
1027                 }
1028
1029                 if (!empty($data['channels_total'])) {
1030                         $serverdata['registered-users'] = max($data['channels_total'], 1);
1031                 }
1032
1033                 if (!empty($data['channels_active_monthly'])) {
1034                         $serverdata['active-month-users'] = max($data['channels_active_monthly'], 0);
1035                 }
1036
1037                 if (!empty($data['channels_active_halfyear'])) {
1038                         $serverdata['active-halfyear-users'] = max($data['channels_active_halfyear'], 0);
1039                 }
1040
1041                 if (!empty($data['local_posts'])) {
1042                         $serverdata['local-posts'] = max($data['local_posts'], 0);
1043                 }
1044
1045                 if (!empty($data['local_comments'])) {
1046                         $serverdata['local-comments'] = max($data['local_comments'], 0);
1047                 }
1048
1049                 if (!empty($data['register_policy'])) {
1050                         switch ($data['register_policy']) {
1051                                 case 'REGISTER_OPEN':
1052                                         $serverdata['register_policy'] = Register::OPEN;
1053                                         break;
1054
1055                                 case 'REGISTER_APPROVE':
1056                                         $serverdata['register_policy'] = Register::APPROVE;
1057                                         break;
1058
1059                                 case 'REGISTER_CLOSED':
1060                                 default:
1061                                         $serverdata['register_policy'] = Register::CLOSED;
1062                                         break;
1063                         }
1064                 }
1065
1066                 return $serverdata;
1067         }
1068
1069         /**
1070          * Checks if the server contains a valid host meta file
1071          *
1072          * @param string $url URL of the given server
1073          *
1074          * @return boolean 'true' if the server seems to be vital
1075          */
1076         private static function validHostMeta(string $url)
1077         {
1078                 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
1079                 $curlResult = DI::httpClient()->get($url . '/.well-known/host-meta', [HttpClientOptions::TIMEOUT => $xrd_timeout]);
1080                 if (!$curlResult->isSuccess()) {
1081                         return false;
1082                 }
1083
1084                 $xrd = XML::parseString($curlResult->getBody());
1085                 if (!is_object($xrd)) {
1086                         return false;
1087                 }
1088
1089                 $elements = XML::elementToArray($xrd);
1090                 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
1091                         return false;
1092                 }
1093
1094                 $valid = false;
1095                 foreach ($elements['xrd']['link'] as $link) {
1096                         // When there is more than a single "link" element, the array looks slightly different
1097                         if (!empty($link['@attributes'])) {
1098                                 $link = $link['@attributes'];
1099                         }
1100
1101                         if (empty($link['rel']) || empty($link['template'])) {
1102                                 continue;
1103                         }
1104
1105                         if ($link['rel'] == 'lrdd') {
1106                                 // When the webfinger host is the same like the system host, it should be ok.
1107                                 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
1108                         }
1109                 }
1110
1111                 return $valid;
1112         }
1113
1114         /**
1115          * Detect the network of the given server via their known contacts
1116          *
1117          * @param string $url        URL of the given server
1118          * @param array  $serverdata array with server data
1119          *
1120          * @return array server data
1121          */
1122         private static function detectNetworkViaContacts(string $url, array $serverdata)
1123         {
1124                 $contacts = [];
1125
1126                 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $serverdata['nurl']]]);
1127                 while ($apcontact = DBA::fetch($apcontacts)) {
1128                         $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1129                 }
1130                 DBA::close($apcontacts);
1131
1132                 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $serverdata['nurl']]]);
1133                 while ($pcontact = DBA::fetch($pcontacts)) {
1134                         $contacts[$pcontact['nurl']] = $pcontact['url'];
1135                 }
1136                 DBA::close($pcontacts);
1137
1138                 if (empty($contacts)) {
1139                         return $serverdata;
1140                 }
1141
1142                 $time = time();
1143                 foreach ($contacts as $contact) {
1144                         $probed = Contact::getByURL($contact, true);
1145                         if (!empty($probed) && !$probed['failed'] && in_array($probed['network'], Protocol::FEDERATED)) {
1146                                 $serverdata['network'] = $probed['network'];
1147                                 break;
1148                         } elseif ((time() - $time) > 10) {
1149                                 // To reduce the stress on remote systems we probe a maximum of 10 seconds
1150                                 break;
1151                         }
1152                 }
1153
1154                 return $serverdata;
1155         }
1156
1157         /**
1158          * Checks if the given server does have a '/poco' endpoint.
1159          * This is used for the 'PortableContact' functionality,
1160          * which is used by both Friendica and Hubzilla.
1161          *
1162          * @param string $url        URL of the given server
1163          * @param array  $serverdata array with server data
1164          *
1165          * @return array server data
1166          */
1167         private static function checkPoCo(string $url, array $serverdata)
1168         {
1169                 $serverdata['poco'] = '';
1170
1171                 $curlResult = DI::httpClient()->get($url . '/poco');
1172                 if (!$curlResult->isSuccess()) {
1173                         return $serverdata;
1174                 }
1175
1176                 $data = json_decode($curlResult->getBody(), true);
1177                 if (empty($data)) {
1178                         return $serverdata;
1179                 }
1180
1181                 if (!empty($data['totalResults'])) {
1182                         $registeredUsers = $serverdata['registered-users'] ?? 0;
1183                         $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1184                         $serverdata['directory-type'] = self::DT_POCO;
1185                         $serverdata['poco'] = $url . '/poco';
1186                 }
1187
1188                 return $serverdata;
1189         }
1190
1191         /**
1192          * Checks if the given server does have a Mastodon style directory endpoint.
1193          *
1194          * @param string $url        URL of the given server
1195          * @param array  $serverdata array with server data
1196          *
1197          * @return array server data
1198          */
1199         public static function checkMastodonDirectory(string $url, array $serverdata)
1200         {
1201                 $curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1');
1202                 if (!$curlResult->isSuccess()) {
1203                         return $serverdata;
1204                 }
1205
1206                 $data = json_decode($curlResult->getBody(), true);
1207                 if (empty($data)) {
1208                         return $serverdata;
1209                 }
1210
1211                 if (count($data) == 1) {
1212                         $serverdata['directory-type'] = self::DT_MASTODON;
1213                 }
1214
1215                 return $serverdata;
1216         }
1217
1218         /**
1219          * Detects Peertube via their known endpoint
1220          *
1221          * @param string $url        URL of the given server
1222          * @param array  $serverdata array with server data
1223          *
1224          * @return array server data
1225          */
1226         private static function detectPeertube(string $url, array $serverdata)
1227         {
1228                 $curlResult = DI::httpClient()->get($url . '/api/v1/config');
1229
1230                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1231                         return $serverdata;
1232                 }
1233
1234                 $data = json_decode($curlResult->getBody(), true);
1235                 if (empty($data)) {
1236                         return $serverdata;
1237                 }
1238
1239                 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1240                         $serverdata['platform'] = 'peertube';
1241                         $serverdata['version'] = $data['serverVersion'];
1242                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1243
1244                         if (!empty($data['instance']['name'])) {
1245                                 $serverdata['site_name'] = $data['instance']['name'];
1246                         }
1247
1248                         if (!empty($data['instance']['shortDescription'])) {
1249                                 $serverdata['info'] = $data['instance']['shortDescription'];
1250                         }
1251
1252                         if (!empty($data['signup'])) {
1253                                 if (!empty($data['signup']['allowed'])) {
1254                                         $serverdata['register_policy'] = Register::OPEN;
1255                                 }
1256                         }
1257
1258                         if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1259                                 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1260                         }
1261                 }
1262
1263                 return $serverdata;
1264         }
1265
1266         /**
1267          * Detects the version number of a given server when it was a NextCloud installation
1268          *
1269          * @param string $url        URL of the given server
1270          * @param array  $serverdata array with server data
1271          *
1272          * @return array server data
1273          */
1274         private static function detectNextcloud(string $url, array $serverdata)
1275         {
1276                 $curlResult = DI::httpClient()->get($url . '/status.php');
1277
1278                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1279                         return $serverdata;
1280                 }
1281
1282                 $data = json_decode($curlResult->getBody(), true);
1283                 if (empty($data)) {
1284                         return $serverdata;
1285                 }
1286
1287                 if (!empty($data['version'])) {
1288                         $serverdata['platform'] = 'nextcloud';
1289                         $serverdata['version'] = $data['version'];
1290                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1291
1292                         if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1293                                 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1294                         }
1295                 }
1296
1297                 return $serverdata;
1298         }
1299
1300         private static function fetchWeeklyUsage(string $url, array $serverdata) {
1301                 $curlResult = DI::httpClient()->get($url . '/api/v1/instance/activity');
1302
1303                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1304                         return $serverdata;
1305                 }
1306
1307                 $data = json_decode($curlResult->getBody(), true);
1308                 if (empty($data)) {
1309                         return $serverdata;
1310                 }
1311
1312                 $current_week = [];
1313                 foreach ($data as $week) {
1314                         // Use only data from a full week
1315                         if (empty($week['week']) || (time() - $week['week']) < 7 * 24 * 60 * 60) {
1316                                 continue;
1317                         }
1318
1319                         // Most likely the data is sorted correctly. But we better are safe than sorry
1320                         if (empty($current_week['week']) || ($current_week['week'] < $week['week'])) {
1321                                 $current_week = $week;
1322                         } 
1323                 }
1324
1325                 if (!empty($current_week['logins'])) {
1326                         $serverdata['active-week-users'] = max($current_week['logins'], 0);
1327                 }
1328
1329                 return $serverdata;
1330         }
1331
1332         /**
1333          * Detects data from a given server url if it was a mastodon alike system
1334          *
1335          * @param string $url        URL of the given server
1336          * @param array  $serverdata array with server data
1337          *
1338          * @return array server data
1339          */
1340         private static function detectMastodonAlikes(string $url, array $serverdata)
1341         {
1342                 $curlResult = DI::httpClient()->get($url . '/api/v1/instance');
1343
1344                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1345                         return $serverdata;
1346                 }
1347
1348                 $data = json_decode($curlResult->getBody(), true);
1349                 if (empty($data)) {
1350                         return $serverdata;
1351                 }
1352
1353                 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1354                         $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1355                 }
1356
1357                 if (!empty($data['version'])) {
1358                         $serverdata['platform'] = 'mastodon';
1359                         $serverdata['version'] = $data['version'] ?? '';
1360                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1361                 }
1362
1363                 if (!empty($data['title'])) {
1364                         $serverdata['site_name'] = $data['title'];
1365                 }
1366
1367                 if (!empty($data['title']) && empty($serverdata['platform']) && empty($serverdata['network'])) {
1368                         $serverdata['platform'] = 'mastodon';
1369                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1370                 }
1371
1372                 if (!empty($data['description'])) {
1373                         $serverdata['info'] = trim($data['description']);
1374                 }
1375
1376                 if (!empty($data['stats']['user_count'])) {
1377                         $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1378                 }
1379
1380                 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1381                         $serverdata['platform'] = strtolower($matches[1]);
1382                         $serverdata['version'] = $matches[2];
1383                 }
1384
1385                 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1386                         $serverdata['platform'] = 'pleroma';
1387                         $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1388                 }
1389
1390                 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1391                         $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1392                         $serverdata['platform'] = 'pleroma';
1393                 }
1394
1395                 return $serverdata;
1396         }
1397
1398         /**
1399          * Detects data from typical Hubzilla endpoints
1400          *
1401          * @param string $url        URL of the given server
1402          * @param array  $serverdata array with server data
1403          *
1404          * @return array server data
1405          */
1406         private static function detectHubzilla(string $url, array $serverdata)
1407         {
1408                 $curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json');
1409                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1410                         return $serverdata;
1411                 }
1412
1413                 $data = json_decode($curlResult->getBody(), true);
1414                 if (empty($data) || empty($data['site'])) {
1415                         return $serverdata;
1416                 }
1417
1418                 if (!empty($data['site']['name'])) {
1419                         $serverdata['site_name'] = $data['site']['name'];
1420                 }
1421
1422                 if (!empty($data['site']['platform'])) {
1423                         $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1424                         $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1425                         $serverdata['network'] = Protocol::ZOT;
1426                 }
1427
1428                 if (!empty($data['site']['hubzilla'])) {
1429                         $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1430                         $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1431                         $serverdata['network'] = Protocol::ZOT;
1432                 }
1433
1434                 if (!empty($data['site']['redmatrix'])) {
1435                         if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1436                                 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1437                         } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1438                                 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1439                         }
1440
1441                         $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1442                         $serverdata['network'] = Protocol::ZOT;
1443                 }
1444
1445                 $private = false;
1446                 $inviteonly = false;
1447                 $closed = false;
1448
1449                 if (!empty($data['site']['closed'])) {
1450                         $closed = self::toBoolean($data['site']['closed']);
1451                 }
1452
1453                 if (!empty($data['site']['private'])) {
1454                         $private = self::toBoolean($data['site']['private']);
1455                 }
1456
1457                 if (!empty($data['site']['inviteonly'])) {
1458                         $inviteonly = self::toBoolean($data['site']['inviteonly']);
1459                 }
1460
1461                 if (!$closed && !$private and $inviteonly) {
1462                         $serverdata['register_policy'] = Register::APPROVE;
1463                 } elseif (!$closed && !$private) {
1464                         $serverdata['register_policy'] = Register::OPEN;
1465                 } else {
1466                         $serverdata['register_policy'] = Register::CLOSED;
1467                 }
1468
1469                 if (!empty($serverdata['network']) && in_array($serverdata['detection-method'],
1470                         [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1471                         $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1472                 }
1473
1474                 return $serverdata;
1475         }
1476
1477         /**
1478          * Converts input value to a boolean value
1479          *
1480          * @param string|integer $val
1481          *
1482          * @return boolean
1483          */
1484         private static function toBoolean($val)
1485         {
1486                 if (($val == 'true') || ($val == 1)) {
1487                         return true;
1488                 } elseif (($val == 'false') || ($val == 0)) {
1489                         return false;
1490                 }
1491
1492                 return $val;
1493         }
1494
1495         /**
1496          * Detect if the URL belongs to a pump.io server
1497          *
1498          * @param string $url        URL of the given server
1499          * @param array  $serverdata array with server data
1500          *
1501          * @return array server data
1502          */
1503         private static function detectPumpIO(string $url, array $serverdata)
1504         {
1505                 $curlResult = DI::httpClient()->get($url . '/.well-known/host-meta.json');
1506                 if (!$curlResult->isSuccess()) {
1507                         return $serverdata;
1508                 }
1509
1510                 $data = json_decode($curlResult->getBody(), true);
1511                 if (empty($data['links'])) {
1512                         return $serverdata;
1513
1514                 }
1515
1516                 // We are looking for some endpoints that are typical for pump.io
1517                 $trust = 0;
1518                 foreach ($data['links'] as $link) {
1519                         if (empty($link['rel'])) {
1520                                 continue;
1521                         }
1522                         if (in_array($link['rel'], ['registration_endpoint', 'dialback', 'http://apinamespace.org/activitypub/whoami'])) {
1523                                 ++$trust;
1524                         }
1525                 }
1526
1527                 if ($trust == 3) {
1528                         $serverdata['detection-method'] = self::DETECT_PUMPIO;
1529
1530                         $serverdata['platform'] = 'pumpio';
1531                         $serverdata['version']  = '';
1532                         $serverdata['network']  = Protocol::PUMPIO;
1533
1534                         $servers = $curlResult->getHeader('Server');
1535                         foreach ($servers as $server) {
1536                                 if (preg_match("#pump.io/(.*)\s#U", $server, $matches)) {
1537                                         $serverdata['version']  = $matches[1];
1538                                 }
1539                         }
1540                 }
1541
1542                 return $serverdata;
1543         }
1544
1545         /**
1546          * Detect if the URL belongs to a GNU Social server
1547          *
1548          * @param string $url        URL of the given server
1549          * @param array  $serverdata array with server data
1550          *
1551          * @return array server data
1552          */
1553         private static function detectGNUSocial(string $url, array $serverdata)
1554         {
1555                 // Test for GNU Social
1556                 $curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json');
1557                 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1558                         ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1559                         $serverdata['platform'] = 'gnusocial';
1560                         // Remove junk that some GNU Social servers return
1561                         $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1562                         $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1563                         $serverdata['version'] = trim($serverdata['version'], '"');
1564                         $serverdata['network'] = Protocol::OSTATUS;
1565
1566                         if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1567                                 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1568                         }
1569
1570                         return $serverdata;
1571                 }
1572
1573                 // Test for Statusnet
1574                 $curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json');
1575                 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1576                         ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1577
1578                         // Remove junk that some GNU Social servers return
1579                         $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1580                         $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1581                         $serverdata['version'] = trim($serverdata['version'], '"');
1582
1583                         if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1584                                 $serverdata['platform'] = 'pleroma';
1585                                 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1586                                 $serverdata['network'] = Protocol::ACTIVITYPUB;
1587                         } else {
1588                                 $serverdata['platform'] = 'statusnet';
1589                                 $serverdata['network'] = Protocol::OSTATUS;
1590                         }
1591
1592                         if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1593                                 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1594                         }
1595                 }
1596
1597                 return $serverdata;
1598         }
1599
1600         /**
1601          * Detect if the URL belongs to a Friendica server
1602          *
1603          * @param string $url        URL of the given server
1604          * @param array  $serverdata array with server data
1605          *
1606          * @return array server data
1607          */
1608         private static function detectFriendica(string $url, array $serverdata)
1609         {
1610                 $curlResult = DI::httpClient()->get($url . '/friendica/json');
1611                 if (!$curlResult->isSuccess()) {
1612                         $curlResult = DI::httpClient()->get($url . '/friendika/json');
1613                         $friendika = true;
1614                         $platform = 'Friendika';
1615                 } else {
1616                         $friendika = false;
1617                         $platform = 'Friendica';
1618                 }
1619
1620                 if (!$curlResult->isSuccess()) {
1621                         return $serverdata;
1622                 }
1623
1624                 $data = json_decode($curlResult->getBody(), true);
1625                 if (empty($data) || empty($data['version'])) {
1626                         return $serverdata;
1627                 }
1628
1629                 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1630                         $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1631                 }
1632
1633                 $serverdata['network'] = Protocol::DFRN;
1634                 $serverdata['version'] = $data['version'];
1635
1636                 if (!empty($data['no_scrape_url'])) {
1637                         $serverdata['noscrape'] = $data['no_scrape_url'];
1638                 }
1639
1640                 if (!empty($data['site_name'])) {
1641                         $serverdata['site_name'] = $data['site_name'];
1642                 }
1643
1644                 if (!empty($data['info'])) {
1645                         $serverdata['info'] = trim($data['info']);
1646                 }
1647
1648                 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1649                 switch ($register_policy) {
1650                         case 'REGISTER_OPEN':
1651                                 $serverdata['register_policy'] = Register::OPEN;
1652                                 break;
1653
1654                         case 'REGISTER_APPROVE':
1655                                 $serverdata['register_policy'] = Register::APPROVE;
1656                                 break;
1657
1658                         case 'REGISTER_CLOSED':
1659                         case 'REGISTER_INVITATION':
1660                                 $serverdata['register_policy'] = Register::CLOSED;
1661                                 break;
1662                         default:
1663                                 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
1664                                 $serverdata['register_policy'] = Register::CLOSED;
1665                                 break;
1666                 }
1667
1668                 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
1669
1670                 return $serverdata;
1671         }
1672
1673         /**
1674          * Analyses the landing page of a given server for hints about type and system of that server
1675          *
1676          * @param object $curlResult result of curl execution
1677          * @param array  $serverdata array with server data
1678          * @param string $url        Server URL
1679          *
1680          * @return array server data
1681          */
1682         private static function analyseRootBody($curlResult, array $serverdata, string $url)
1683         {
1684                 if (empty($curlResult->getBody())) {
1685                         return $serverdata;
1686                 }
1687
1688                 // Using only body information we cannot safely detect a lot of systems.
1689                 // So we define a list of platforms that we can detect safely.
1690                 $valid_platforms = ['friendica', 'friendika', 'diaspora', 'mastodon', 'hubzilla', 'misskey', 'peertube', 'wordpress', 'write.as'];
1691
1692                 $doc = new DOMDocument();
1693                 @$doc->loadHTML($curlResult->getBody());
1694                 $xpath = new DOMXPath($doc);
1695
1696                 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
1697                 if (!empty($title)) {
1698                         $serverdata['site_name'] = $title;
1699                 }
1700
1701                 $list = $xpath->query('//meta[@name]');
1702
1703                 foreach ($list as $node) {
1704                         $attr = [];
1705                         if ($node->attributes->length) {
1706                                 foreach ($node->attributes as $attribute) {
1707                                         $value = trim($attribute->value);
1708                                         if (empty($value)) {
1709                                                 continue;
1710                                         }
1711
1712                                         $attr[$attribute->name] = $value;
1713                                 }
1714
1715                                 if (empty($attr['name']) || empty($attr['content'])) {
1716                                         continue;
1717                                 }
1718                         }
1719
1720                         if ($attr['name'] == 'description') {
1721                                 $serverdata['info'] = $attr['content'];
1722                         }
1723
1724                         if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
1725                                 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad'])) {
1726                                 $serverdata['platform'] = strtolower($attr['content']);
1727                                 if (in_array($attr['content'], ['Misskey', 'Write.as'])) {
1728                                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1729                                 }
1730                         }
1731                         if (($attr['name'] == 'generator') && (empty($serverdata['platform']) || (substr(strtolower($attr['content']), 0, 9) == 'wordpress'))) {
1732                                 $serverdata['platform'] = strtolower($attr['content']);
1733                                 $version_part = explode(' ', $attr['content']);
1734
1735                                 if (count($version_part) == 2) {
1736                                         if (in_array($version_part[0], ['WordPress'])) {
1737                                                 $serverdata['platform'] = 'wordpress';
1738                                                 $serverdata['version'] = $version_part[1];
1739
1740                                                 // We still do need a reliable test if some AP plugin is activated
1741                                                 // By now we just check in a later process for some known contacts
1742                                                 $serverdata['network'] = Protocol::FEED;
1743
1744                                                 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1745                                                         $serverdata['detection-method'] = self::DETECT_BODY;
1746                                                 }
1747                                         }
1748                                         if (in_array($version_part[0], ['Friendika', 'Friendica'])) {
1749                                                 $serverdata['platform'] = strtolower($version_part[0]);
1750                                                 $serverdata['version'] = $version_part[1];
1751                                                 $serverdata['network'] = Protocol::DFRN;
1752                                         }
1753                                 }
1754                         }
1755                 }
1756
1757                 $list = $xpath->query('//meta[@property]');
1758
1759                 foreach ($list as $node) {
1760                         $attr = [];
1761                         if ($node->attributes->length) {
1762                                 foreach ($node->attributes as $attribute) {
1763                                         $value = trim($attribute->value);
1764                                         if (empty($value)) {
1765                                                 continue;
1766                                         }
1767
1768                                         $attr[$attribute->name] = $value;
1769                                 }
1770
1771                                 if (empty($attr['property']) || empty($attr['content'])) {
1772                                         continue;
1773                                 }
1774                         }
1775
1776                         if ($attr['property'] == 'og:site_name') {
1777                                 $serverdata['site_name'] = $attr['content'];
1778                         }
1779
1780                         if ($attr['property'] == 'og:description') {
1781                                 $serverdata['info'] = $attr['content'];
1782                         }
1783
1784                         if ($attr['property'] == 'og:platform') {
1785                                 $serverdata['platform'] = strtolower($attr['content']);
1786
1787                                 if (in_array($attr['content'], ['PeerTube'])) {
1788                                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1789                                 }
1790                         }
1791
1792                         if ($attr['property'] == 'generator') {
1793                                 $serverdata['platform'] = strtolower($attr['content']);
1794
1795                                 if (in_array($attr['content'], ['hubzilla'])) {
1796                                         // We later check which compatible protocol modules are loaded.
1797                                         $serverdata['network'] = Protocol::ZOT;
1798                                 }
1799                         }
1800                 }
1801
1802                 if (!empty($serverdata['platform']) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_BODY]) && !in_array($serverdata['platform'], $valid_platforms)) {
1803                         $serverdata['network'] = Protocol::PHANTOM;
1804                         $serverdata['version'] = '';
1805                         $serverdata['detection-method'] = self::DETECT_MANUAL;
1806                 } elseif (!empty($serverdata['network']) && ($serverdata['detection-method'] == self::DETECT_MANUAL)) {
1807                         $serverdata['detection-method'] = self::DETECT_BODY;
1808                 }
1809
1810                 return $serverdata;
1811         }
1812
1813         /**
1814          * Analyses the header data of a given server for hints about type and system of that server
1815          *
1816          * @param object $curlResult result of curl execution
1817          * @param array  $serverdata array with server data
1818          *
1819          * @return array server data
1820          */
1821         private static function analyseRootHeader($curlResult, array $serverdata)
1822         {
1823                 if ($curlResult->getHeader('server') == 'Mastodon') {
1824                         $serverdata['platform'] = 'mastodon';
1825                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1826                 } elseif ($curlResult->inHeader('x-diaspora-version')) {
1827                         $serverdata['platform'] = 'diaspora';
1828                         $serverdata['network'] = Protocol::DIASPORA;
1829                         $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
1830                 } elseif ($curlResult->inHeader('x-friendica-version')) {
1831                         $serverdata['platform'] = 'friendica';
1832                         $serverdata['network'] = Protocol::DFRN;
1833                         $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
1834                 } else {
1835                         return $serverdata;
1836                 }
1837
1838                 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1839                         $serverdata['detection-method'] = self::DETECT_HEADER;
1840                 }
1841
1842                 return $serverdata;
1843         }
1844
1845         /**
1846          * Test if the body contains valid content
1847          *
1848          * @param string $body
1849          * @return boolean
1850          */
1851         private static function invalidBody(string $body)
1852         {
1853                 // Currently we only test for a HTML element.
1854                 // Possibly we enhance this in the future.
1855                 return !strpos($body, '>');
1856         }
1857
1858         /**
1859          * Update GServer entries
1860          */
1861         public static function discover()
1862         {
1863                 // Update the server list
1864                 self::discoverFederation();
1865
1866                 $no_of_queries = 5;
1867
1868                 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
1869
1870                 if ($requery_days == 0) {
1871                         $requery_days = 7;
1872                 }
1873
1874                 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
1875
1876                 $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
1877                         ["NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
1878                         ['order' => ['RAND()']]);
1879
1880                 while ($gserver = DBA::fetch($gservers)) {
1881                         Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1882                         Worker::add(PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
1883
1884                         Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1885                         Worker::add(PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
1886
1887                         $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1888                         DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);
1889
1890                         if (--$no_of_queries == 0) {
1891                                 break;
1892                         }
1893                 }
1894
1895                 DBA::close($gservers);
1896         }
1897
1898         /**
1899          * Discover federated servers
1900          */
1901         private static function discoverFederation()
1902         {
1903                 $last = DI::config()->get('poco', 'last_federation_discovery');
1904
1905                 if ($last) {
1906                         $next = $last + (24 * 60 * 60);
1907
1908                         if ($next > time()) {
1909                                 return;
1910                         }
1911                 }
1912
1913                 // Discover federated servers
1914                 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
1915                 foreach ($protocols as $protocol) {
1916                         $query = '{nodes(protocol:"' . $protocol . '"){host}}';
1917                         $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query));
1918                         if (!empty($curlResult)) {
1919                                 $data = json_decode($curlResult, true);
1920                                 if (!empty($data['data']['nodes'])) {
1921                                         foreach ($data['data']['nodes'] as $server) {
1922                                                 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
1923                                                 self::add('https://' . $server['host'], true);
1924                                         }
1925                                 }
1926                         }
1927                 }
1928
1929                 // Disvover Mastodon servers
1930                 $accesstoken = DI::config()->get('system', 'instances_social_key');
1931
1932                 if (!empty($accesstoken)) {
1933                         $api = 'https://instances.social/api/1.0/instances/list?count=0';
1934                         $curlResult = DI::httpClient()->get($api, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
1935
1936                         if ($curlResult->isSuccess()) {
1937                                 $servers = json_decode($curlResult->getBody(), true);
1938
1939                                 foreach ($servers['instances'] as $server) {
1940                                         $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
1941                                         self::add($url);
1942                                 }
1943                         }
1944                 }
1945
1946                 DI::config()->set('poco', 'last_federation_discovery', time());
1947         }
1948
1949         /**
1950          * Set the protocol for the given server
1951          *
1952          * @param int $gsid     Server id
1953          * @param int $protocol Protocol id
1954          * @return void
1955          * @throws Exception
1956          */
1957         public static function setProtocol(int $gsid, int $protocol)
1958         {
1959                 if (empty($gsid)) {
1960                         return;
1961                 }
1962
1963                 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
1964                 if (!DBA::isResult($gserver)) {
1965                         return;
1966                 }
1967
1968                 $old = $gserver['protocol'];
1969
1970                 if (!is_null($old)) {
1971                         /*
1972                         The priority for the protocols is:
1973                                 1. ActivityPub
1974                                 2. DFRN via Diaspora
1975                                 3. Legacy DFRN
1976                                 4. Diaspora
1977                                 5. OStatus
1978                         */
1979
1980                         // We don't need to change it when nothing is to be changed
1981                         if ($old == $protocol) {
1982                                 return;
1983                         }
1984
1985                         // We don't want to mark a server as OStatus when it had been marked with any other protocol before
1986                         if ($protocol == Post\DeliveryData::OSTATUS) {
1987                                 return;
1988                         }
1989
1990                         // If the server is marked as ActivityPub then we won't change it to anything different
1991                         if ($old == Post\DeliveryData::ACTIVITYPUB) {
1992                                 return;
1993                         }
1994
1995                         // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
1996                         if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
1997                                 return;
1998                         }
1999
2000                         // Don't change it to Diaspora when it is a legacy DFRN server
2001                         if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
2002                                 return;
2003                         }
2004                 }
2005
2006                 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url'], 'callstack' => System::callstack(20)]);
2007                 DBA::update('gserver', ['protocol' => $protocol], ['id' => $gsid]);
2008         }
2009
2010         /**
2011          * Fetch the protocol of the given server
2012          *
2013          * @param int $gsid Server id
2014          * @return int
2015          * @throws Exception
2016          */
2017         public static function getProtocol(int $gsid)
2018         {
2019                 if (empty($gsid)) {
2020                         return null;
2021                 }
2022
2023                 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
2024                 if (DBA::isResult($gserver)) {
2025                         return $gserver['protocol'];
2026                 }
2027
2028                 return null;
2029         }
2030 }