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