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