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