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