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