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