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