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