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