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