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