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