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