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