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