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