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