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