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