]> git.mxchange.org Git - friendica.git/blob - src/Model/GServer.php
Merge pull request #9621 from MrPetovan/bug/9611-bbcode-convert-html-purify
[friendica.git] / src / Model / GServer.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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 Friendica\Core\Logger;
27 use Friendica\Core\Protocol;
28 use Friendica\Core\System;
29 use Friendica\Core\Worker;
30 use Friendica\Database\Database;
31 use Friendica\Database\DBA;
32 use Friendica\DI;
33 use Friendica\Module\Register;
34 use Friendica\Network\CurlResult;
35 use Friendica\Protocol\Relay;
36 use Friendica\Util\DateTimeFormat;
37 use Friendica\Util\Network;
38 use Friendica\Util\Strings;
39 use Friendica\Util\XML;
40
41 /**
42  * This class handles GServer related functions
43  */
44 class GServer
45 {
46         // Directory types
47         const DT_NONE = 0;
48         const DT_POCO = 1;
49         const DT_MASTODON = 2;
50
51         // Methods to detect server types
52
53         // Non endpoint specific methods
54         const DETECT_MANUAL = 0;
55         const DETECT_HEADER = 1;
56         const DETECT_BODY = 2;
57
58         // Implementation specific endpoints
59         const DETECT_FRIENDIKA = 10;
60         const DETECT_FRIENDICA = 11;
61         const DETECT_STATUSNET = 12;
62         const DETECT_GNUSOCIAL = 13;
63         const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix
64         const DETECT_SITEINFO_JSON = 15; // Newer Hubzilla
65         const DETECT_MASTODON_API = 16;
66         const DETECT_STATUS_PHP = 17; // Nextcloud
67
68         // Standardized endpoints
69         const DETECT_STATISTICS_JSON = 100;
70         const DETECT_NODEINFO_1 = 101;
71         const DETECT_NODEINFO_2 = 102;
72
73         /**
74          * Check for the existance of a server and adds it in the background if not existant
75          *
76          * @param string $url
77          * @param boolean $only_nodeinfo
78          * @return void
79          */
80         public static function add(string $url, bool $only_nodeinfo = false)
81         {
82                 if (self::getID($url, false)) {
83                         return;
84                 }
85
86                 Worker::add(PRIORITY_LOW, 'UpdateGServer', $url, $only_nodeinfo);
87         }
88
89         /**
90          * Get the ID for the given server URL
91          *
92          * @param string $url
93          * @param boolean $no_check Don't check if the server hadn't been found
94          * @return int gserver id
95          */
96         public static function getID(string $url, bool $no_check = false)
97         {
98                 if (empty($url)) {
99                         return null;
100                 }
101
102                 $url = self::cleanURL($url);
103
104                 $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
105                 if (DBA::isResult($gserver)) {
106                         Logger::info('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
107                         return $gserver['id'];
108                 }
109
110                 if ($no_check || !self::check($url)) {
111                         return null;
112                 }
113         
114                 return self::getID($url, true);
115         }
116
117         /**
118          * Checks if the given server is reachable
119          *
120          * @param string  $profile URL of the given profile
121          * @param string  $server  URL of the given server (If empty, taken from profile)
122          * @param string  $network Network value that is used, when detection failed
123          * @param boolean $force   Force an update.
124          *
125          * @return boolean 'true' if server seems vital
126          */
127         public static function reachable(string $profile, string $server = '', string $network = '', bool $force = false)
128         {
129                 if ($server == '') {
130                         $contact = Contact::getByURL($profile, null, ['baseurl']);
131                         if (!empty($contact['baseurl'])) {
132                                 $server = $contact['baseurl'];
133                         }
134                 }
135
136                 if ($server == '') {
137                         return true;
138                 }
139
140                 return self::check($server, $network, $force);
141         }
142
143         public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '')
144         {
145                 // On successful contact process check again next week
146                 if ($success) {
147                         return DateTimeFormat::utc('now +7 day');
148                 }
149
150                 $now = strtotime(DateTimeFormat::utcNow());
151
152                 if ($created > $last_contact) {
153                         $contact_time = strtotime($created);
154                 } else {
155                         $contact_time = strtotime($last_contact);
156                 }
157
158                 // If the last contact was less than 6 hours before then try again in 6 hours
159                 if (($now - $contact_time) < (60 * 60 * 6)) {
160                         return DateTimeFormat::utc('now +6 hour');
161                 }
162
163                 // If the last contact was less than 12 hours before then try again in 12 hours
164                 if (($now - $contact_time) < (60 * 60 * 12)) {
165                         return DateTimeFormat::utc('now +12 hour');
166                 }
167
168                 // If the last contact was less than 24 hours before then try tomorrow again
169                 if (($now - $contact_time) < (60 * 60 * 24)) {
170                         return DateTimeFormat::utc('now +1 day');
171                 }
172                 
173                 // If the last contact was less than a week before then try again in a week
174                 if (($now - $contact_time) < (60 * 60 * 24 * 7)) {
175                         return DateTimeFormat::utc('now +1 week');
176                 }
177
178                 // If the last contact was less than two weeks before then try again in two week
179                 if (($now - $contact_time) < (60 * 60 * 24 * 14)) {
180                         return DateTimeFormat::utc('now +2 week');
181                 }
182
183                 // If the last contact was less than a month before then try again in a month
184                 if (($now - $contact_time) < (60 * 60 * 24 * 30)) {
185                         return DateTimeFormat::utc('now +1 month');
186                 }
187
188                 // The system hadn't been successul contacted for more than a month, so try again in three months
189                 return DateTimeFormat::utc('now +3 month');
190         }
191
192         /**
193          * Checks the state of the given server.
194          *
195          * @param string  $server_url    URL of the given server
196          * @param string  $network       Network value that is used, when detection failed
197          * @param boolean $force         Force an update.
198          * @param boolean $only_nodeinfo Only use nodeinfo for server detection
199          *
200          * @return boolean 'true' if server seems vital
201          */
202         public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false)
203         {
204                 $server_url = self::cleanURL($server_url);
205                 if ($server_url == '') {
206                         return false;
207                 }
208
209                 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
210                 if (DBA::isResult($gserver)) {
211                         if ($gserver['created'] <= DBA::NULL_DATETIME) {
212                                 $fields = ['created' => DateTimeFormat::utcNow()];
213                                 $condition = ['nurl' => Strings::normaliseLink($server_url)];
214                                 DBA::update('gserver', $fields, $condition);
215                         }
216
217                         if (!$force && (strtotime($gserver['next_contact']) > time())) {
218                                 Logger::info('No update needed', ['server' => $server_url]);
219                                 return (!$gserver['failed']);
220                         }
221                         Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]);
222                 } else {
223                         Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
224                 }
225
226                 return self::detect($server_url, $network, $only_nodeinfo);
227         }
228
229         /**
230          * Set failed server status
231          *
232          * @param string $url
233          */
234         public static function setFailure(string $url)
235         {
236                 $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($url)]);
237                 if (DBA::isResult($gserver)) {
238                         $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
239                         DBA::update('gserver', ['failed' => true, 'last_failure' => DateTimeFormat::utcNow(),
240                         'next_contact' => $next_update, 'detection-method' => null],
241                         ['nurl' => Strings::normaliseLink($url)]);
242                         Logger::info('Set failed status for existing server', ['url' => $url]);
243                         return;
244                 }
245                 DBA::insert('gserver', ['url' => $url, 'nurl' => Strings::normaliseLink($url),
246                         'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
247                         'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
248                 Logger::info('Set failed status for new server', ['url' => $url]);
249         }
250
251         /**
252          * Remove unwanted content from the given URL
253          *
254          * @param string $url
255          * @return string cleaned URL
256          */
257         public static function cleanURL(string $url)
258         {
259                 $url = trim($url, '/');
260                 $url = str_replace('/index.php', '', $url);
261
262                 $urlparts = parse_url($url);
263                 unset($urlparts['user']);
264                 unset($urlparts['pass']);
265                 unset($urlparts['query']);
266                 unset($urlparts['fragment']);
267                 return Network::unparseURL($urlparts);
268         }
269
270         /**
271          * Return the base URL
272          *
273          * @param string $url
274          * @return string base URL
275          */
276         private static function getBaseURL(string $url)
277         {
278                 $urlparts = parse_url(self::cleanURL($url));
279                 unset($urlparts['path']);
280                 return Network::unparseURL($urlparts);
281         }
282
283         /**
284          * Detect server data (type, protocol, version number, ...)
285          * The detected data is then updated or inserted in the gserver table.
286          *
287          * @param string  $url           URL of the given server
288          * @param string  $network       Network value that is used, when detection failed
289          * @param boolean $only_nodeinfo Only use nodeinfo for server detection
290          *
291          * @return boolean 'true' if server could be detected
292          */
293         public static function detect(string $url, string $network = '', bool $only_nodeinfo = false)
294         {
295                 Logger::info('Detect server type', ['server' => $url]);
296                 $serverdata = ['detection-method' => self::DETECT_MANUAL];
297
298                 $original_url = $url;
299
300                 // Remove URL content that is not supposed to exist for a server url
301                 $url = self::cleanURL($url);
302
303                 // Get base URL
304                 $baseurl = self::getBaseURL($url);
305
306                 // If the URL missmatches, then we mark the old entry as failure
307                 if ($url != $original_url) {
308                         /// @todo What to do with "next_contact" here?
309                         DBA::update('gserver', ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()],
310                                 ['nurl' => Strings::normaliseLink($original_url)]);
311                 }
312
313                 // When a nodeinfo is present, we don't need to dig further
314                 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
315                 $curlResult = DI::httpRequest()->get($url . '/.well-known/nodeinfo', ['timeout' => $xrd_timeout]);
316                 if ($curlResult->isTimeout()) {
317                         self::setFailure($url);
318                         return false;
319                 }
320
321                 $nodeinfo = self::fetchNodeinfo($url, $curlResult);
322                 if ($only_nodeinfo && empty($nodeinfo)) {
323                         Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
324                         self::setFailure($url);
325                         return false;
326                 }
327
328                 // When nodeinfo isn't present, we use the older 'statistics.json' endpoint
329                 if (empty($nodeinfo)) {
330                         $nodeinfo = self::fetchStatistics($url);
331                 }
332
333                 // If that didn't work out well, we use some protocol specific endpoints
334                 // For Friendica and Zot based networks we have to dive deeper to reveal more details
335                 if (empty($nodeinfo['network']) || in_array($nodeinfo['network'], [Protocol::DFRN, Protocol::ZOT])) {
336                         if (!empty($nodeinfo['detection-method'])) {
337                                 $serverdata['detection-method'] = $nodeinfo['detection-method'];
338                         }
339
340                         // Fetch the landing page, possibly it reveals some data
341                         if (empty($nodeinfo['network'])) {
342                                 if ($baseurl == $url) {
343                                         $basedata = $serverdata;
344                                 } else {
345                                         $basedata = ['detection-method' => self::DETECT_MANUAL];
346                                 }
347
348                                 $curlResult = DI::httpRequest()->get($baseurl, ['timeout' => $xrd_timeout]);
349                                 if ($curlResult->isSuccess()) {
350                                         $basedata = self::analyseRootHeader($curlResult, $basedata);
351                                         $basedata = self::analyseRootBody($curlResult, $basedata, $baseurl);
352                                 }
353
354                                 if (!$curlResult->isSuccess() || empty($curlResult->getBody()) || self::invalidBody($curlResult->getBody())) {
355                                         self::setFailure($url);
356                                         return false;
357                                 }
358
359                                 if ($baseurl == $url) {
360                                         $serverdata = $basedata;
361                                 } else {
362                                         // When the base path doesn't seem to contain a social network we try the complete path.
363                                         // Most detectable system have to be installed in the root directory.
364                                         // We checked the base to avoid false positives.
365                                         $curlResult = DI::httpRequest()->get($url, ['timeout' => $xrd_timeout]);
366                                         if ($curlResult->isSuccess()) {
367                                                 $urldata = self::analyseRootHeader($curlResult, $serverdata);
368                                                 $urldata = self::analyseRootBody($curlResult, $urldata, $url);
369
370                                                 $comparebase = $basedata;
371                                                 unset($comparebase['info']);
372                                                 unset($comparebase['site_name']);
373                                                 $compareurl = $urldata;
374                                                 unset($compareurl['info']);
375                                                 unset($compareurl['site_name']);
376
377                                                 // We assume that no one will install the identical system in the root and a subfolder
378                                                 if (!empty(array_diff($comparebase, $compareurl))) {
379                                                         $serverdata = $urldata;
380                                                 }
381                                         }
382                                 }
383                         }
384
385                         if (empty($serverdata['network']) || ($serverdata['network'] == Protocol::ACTIVITYPUB)) {
386                                 $serverdata = self::detectMastodonAlikes($url, $serverdata);
387                         }
388
389                         // All following checks are done for systems that always have got a "host-meta" endpoint.
390                         // With this check we don't have to waste time and ressources for dead systems.
391                         // Also this hopefully prevents us from receiving abuse messages.
392                         if (empty($serverdata['network']) && !self::validHostMeta($url)) {
393                                 self::setFailure($url);
394                                 return false;
395                         }
396
397                         if (empty($serverdata['network']) || in_array($serverdata['network'], [Protocol::DFRN, Protocol::ACTIVITYPUB])) {
398                                 $serverdata = self::detectFriendica($url, $serverdata);
399                         }
400
401                         // the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
402                         if (empty($serverdata['network']) || ($serverdata['network'] == Protocol::ZOT)) {
403                                 $serverdata = self::fetchSiteinfo($url, $serverdata);
404                         }
405
406                         // The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations
407                         if (empty($serverdata['network'])) {
408                                 $serverdata = self::detectHubzilla($url, $serverdata);
409                         }
410
411                         if (empty($serverdata['network'])) {
412                                 $serverdata = self::detectNextcloud($url, $serverdata);
413                         }
414
415                         if (empty($serverdata['network'])) {
416                                 $serverdata = self::detectGNUSocial($url, $serverdata);
417                         }
418
419                         $serverdata = array_merge($nodeinfo, $serverdata);
420                 } else {
421                         $serverdata = $nodeinfo;
422                 }
423
424                 // Detect the directory type
425                 $serverdata['directory-type'] = self::DT_NONE;
426                 $serverdata = self::checkPoCo($url, $serverdata);
427                 $serverdata = self::checkMastodonDirectory($url, $serverdata);
428
429                 // We can't detect the network type. Possibly it is some system that we don't know yet
430                 if (empty($serverdata['network'])) {
431                         $serverdata['network'] = Protocol::PHANTOM;
432                 }
433
434                 // When we hadn't been able to detect the network type, we use the hint from the parameter
435                 if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
436                         $serverdata['network'] = $network;
437                 }
438
439                 $serverdata['url'] = $url;
440                 $serverdata['nurl'] = Strings::normaliseLink($url);
441
442                 // We take the highest number that we do find
443                 $registeredUsers = $serverdata['registered-users'] ?? 0;
444
445                 // On an active server there has to be at least a single user
446                 if (($serverdata['network'] != Protocol::PHANTOM) && ($registeredUsers == 0)) {
447                         $registeredUsers = 1;
448                 }
449
450                 if ($serverdata['network'] == Protocol::PHANTOM) {
451                         $serverdata['registered-users'] = $registeredUsers;
452                         $serverdata = self::detectNetworkViaContacts($url, $serverdata);
453                 }
454
455                 $serverdata['next_contact'] = self::getNextUpdateDate(true);
456
457                 $serverdata['last_contact'] = DateTimeFormat::utcNow();
458                 $serverdata['failed'] = false;
459
460                 $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
461                 if (!DBA::isResult($gserver)) {
462                         $serverdata['created'] = DateTimeFormat::utcNow();
463                         $ret = DBA::insert('gserver', $serverdata);
464                         $id = DBA::lastInsertId();
465                 } else {
466                         // Don't override the network with 'unknown' when there had been a valid entry before
467                         if (($serverdata['network'] == Protocol::PHANTOM) && !empty($gserver['network'])) {
468                                 unset($serverdata['network']);
469                         }
470
471                         $ret = DBA::update('gserver', $serverdata, ['nurl' => $serverdata['nurl']]);
472                         $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
473                         if (DBA::isResult($gserver)) {
474                                 $id = $gserver['id'];
475                         }
476                 }
477
478                 if (!empty($serverdata['network']) && !empty($id) && ($serverdata['network'] != Protocol::PHANTOM)) {
479                         $apcontacts = DBA::count('apcontact', ['gsid' => $id]);
480                         $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id]);
481                         $max_users = max($apcontacts, $contacts, $registeredUsers);
482                         if ($max_users > $registeredUsers) {
483                                 Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
484                                 DBA::update('gserver', ['registered-users' => $max_users], ['id' => $id]);
485                         }
486                 }
487
488                 if (!empty($serverdata['network']) && in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
489                         self::discoverRelay($url);
490                 }
491
492                 return $ret;
493         }
494
495         /**
496          * Fetch relay data from a given server url
497          *
498          * @param string $server_url address of the server
499          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
500          */
501         private static function discoverRelay(string $server_url)
502         {
503                 Logger::info('Discover relay data', ['server' => $server_url]);
504
505                 $curlResult = DI::httpRequest()->get($server_url . '/.well-known/x-social-relay');
506                 if (!$curlResult->isSuccess()) {
507                         return;
508                 }
509
510                 $data = json_decode($curlResult->getBody(), true);
511                 if (!is_array($data)) {
512                         return;
513                 }
514
515                 // Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
516                 $data['subscribe'] = (bool)$data['subscribe'] ?? false;
517
518                 if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
519                         $data['scope'] = '';
520                         $data['subscribe'] = false;
521                         $data['tags'] = [];
522                 }
523
524                 $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
525                 if (!DBA::isResult($gserver)) {
526                         return;
527                 }
528
529                 if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
530                         $fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
531                         DBA::update('gserver', $fields, ['id' => $gserver['id']]);
532                 }
533
534                 DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
535
536                 if ($data['scope'] == 'tags') {
537                         // Avoid duplicates
538                         $tags = [];
539                         foreach ($data['tags'] as $tag) {
540                                 $tag = mb_strtolower($tag);
541                                 if (strlen($tag) < 100) {
542                                         $tags[$tag] = $tag;
543                                 }
544                         }
545
546                         foreach ($tags as $tag) {
547                                 DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
548                         }
549                 }
550
551                 // Create or update the relay contact
552                 $fields = [];
553                 if (isset($data['protocols'])) {
554                         if (isset($data['protocols']['diaspora'])) {
555                                 $fields['network'] = Protocol::DIASPORA;
556
557                                 if (isset($data['protocols']['diaspora']['receive'])) {
558                                         $fields['batch'] = $data['protocols']['diaspora']['receive'];
559                                 } elseif (is_string($data['protocols']['diaspora'])) {
560                                         $fields['batch'] = $data['protocols']['diaspora'];
561                                 }
562                         }
563
564                         if (isset($data['protocols']['dfrn'])) {
565                                 $fields['network'] = Protocol::DFRN;
566
567                                 if (isset($data['protocols']['dfrn']['receive'])) {
568                                         $fields['batch'] = $data['protocols']['dfrn']['receive'];
569                                 } elseif (is_string($data['protocols']['dfrn'])) {
570                                         $fields['batch'] = $data['protocols']['dfrn'];
571                                 }
572                         }
573
574                         if (isset($data['protocols']['activitypub'])) {
575                                 $fields['network'] = Protocol::ACTIVITYPUB;
576
577                                 if (!empty($data['protocols']['activitypub']['actor'])) {
578                                         $fields['url'] = $data['protocols']['activitypub']['actor'];
579                                 }
580                                 if (!empty($data['protocols']['activitypub']['receive'])) {
581                                         $fields['batch'] = $data['protocols']['activitypub']['receive'];
582                                 }
583                         }
584                 }
585
586                 Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
587
588                 Relay::updateContact($gserver, $fields);
589         }
590
591         /**
592          * Fetch server data from '/statistics.json' on the given server
593          *
594          * @param string $url URL of the given server
595          *
596          * @return array server data
597          */
598         private static function fetchStatistics(string $url)
599         {
600                 $curlResult = DI::httpRequest()->get($url . '/statistics.json');
601                 if (!$curlResult->isSuccess()) {
602                         return [];
603                 }
604
605                 $data = json_decode($curlResult->getBody(), true);
606                 if (empty($data)) {
607                         return [];
608                 }
609
610                 $serverdata = ['detection-method' => self::DETECT_STATISTICS_JSON];
611
612                 if (!empty($data['version'])) {
613                         $serverdata['version'] = $data['version'];
614                         // Version numbers on statistics.json are presented with additional info, e.g.:
615                         // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
616                         $serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
617                 }
618
619                 if (!empty($data['name'])) {
620                         $serverdata['site_name'] = $data['name'];
621                 }
622
623                 if (!empty($data['network'])) {
624                         $serverdata['platform'] = strtolower($data['network']);
625
626                         if ($serverdata['platform'] == 'diaspora') {
627                                 $serverdata['network'] = Protocol::DIASPORA;
628                         } elseif ($serverdata['platform'] == 'friendica') {
629                                 $serverdata['network'] = Protocol::DFRN;
630                         } elseif ($serverdata['platform'] == 'hubzilla') {
631                                 $serverdata['network'] = Protocol::ZOT;
632                         } elseif ($serverdata['platform'] == 'redmatrix') {
633                                 $serverdata['network'] = Protocol::ZOT;
634                         }
635                 }
636
637
638                 if (!empty($data['registrations_open'])) {
639                         $serverdata['register_policy'] = Register::OPEN;
640                 } else {
641                         $serverdata['register_policy'] = Register::CLOSED;
642                 }
643
644                 return $serverdata;
645         }
646
647         /**
648          * Detect server type by using the nodeinfo data
649          *
650          * @param string     $url        address of the server
651          * @param CurlResult $curlResult
652          * @return array Server data
653          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
654          */
655         private static function fetchNodeinfo(string $url, CurlResult $curlResult)
656         {
657                 if (!$curlResult->isSuccess()) {
658                         return [];
659                 }
660
661                 $nodeinfo = json_decode($curlResult->getBody(), true);
662
663                 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
664                         return [];
665                 }
666
667                 $nodeinfo1_url = '';
668                 $nodeinfo2_url = '';
669
670                 foreach ($nodeinfo['links'] as $link) {
671                         if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
672                                 Logger::info('Invalid nodeinfo format', ['url' => $url]);
673                                 continue;
674                         }
675                         if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
676                                 $nodeinfo1_url = $link['href'];
677                         } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
678                                 $nodeinfo2_url = $link['href'];
679                         }
680                 }
681
682                 if ($nodeinfo1_url . $nodeinfo2_url == '') {
683                         return [];
684                 }
685
686                 $server = [];
687
688                 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
689                 if (!empty($nodeinfo2_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
690                         $server = self::parseNodeinfo2($nodeinfo2_url);
691                 }
692
693                 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
694                 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
695                         $server = self::parseNodeinfo1($nodeinfo1_url);
696                 }
697
698                 return $server;
699         }
700
701         /**
702          * Parses Nodeinfo 1
703          *
704          * @param string $nodeinfo_url address of the nodeinfo path
705          * @return array Server data
706          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
707          */
708         private static function parseNodeinfo1(string $nodeinfo_url)
709         {
710                 $curlResult = DI::httpRequest()->get($nodeinfo_url);
711
712                 if (!$curlResult->isSuccess()) {
713                         return [];
714                 }
715
716                 $nodeinfo = json_decode($curlResult->getBody(), true);
717
718                 if (!is_array($nodeinfo)) {
719                         return [];
720                 }
721
722                 $server = ['detection-method' => self::DETECT_NODEINFO_1,
723                         'register_policy' => Register::CLOSED];
724
725                 if (!empty($nodeinfo['openRegistrations'])) {
726                         $server['register_policy'] = Register::OPEN;
727                 }
728
729                 if (is_array($nodeinfo['software'])) {
730                         if (!empty($nodeinfo['software']['name'])) {
731                                 $server['platform'] = strtolower($nodeinfo['software']['name']);
732                         }
733
734                         if (!empty($nodeinfo['software']['version'])) {
735                                 $server['version'] = $nodeinfo['software']['version'];
736                                 // Version numbers on Nodeinfo are presented with additional info, e.g.:
737                                 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
738                                 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
739                         }
740                 }
741
742                 if (!empty($nodeinfo['metadata']['nodeName'])) {
743                         $server['site_name'] = $nodeinfo['metadata']['nodeName'];
744                 }
745
746                 if (!empty($nodeinfo['usage']['users']['total'])) {
747                         $server['registered-users'] = $nodeinfo['usage']['users']['total'];
748                 }
749
750                 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
751                         $protocols = [];
752                         foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
753                                 $protocols[$protocol] = true;
754                         }
755
756                         if (!empty($protocols['friendica'])) {
757                                 $server['network'] = Protocol::DFRN;
758                         } elseif (!empty($protocols['activitypub'])) {
759                                 $server['network'] = Protocol::ACTIVITYPUB;
760                         } elseif (!empty($protocols['diaspora'])) {
761                                 $server['network'] = Protocol::DIASPORA;
762                         } elseif (!empty($protocols['ostatus'])) {
763                                 $server['network'] = Protocol::OSTATUS;
764                         } elseif (!empty($protocols['gnusocial'])) {
765                                 $server['network'] = Protocol::OSTATUS;
766                         } elseif (!empty($protocols['zot'])) {
767                                 $server['network'] = Protocol::ZOT;
768                         }
769                 }
770
771                 if (empty($server)) {
772                         return [];
773                 }
774
775                 return $server;
776         }
777
778         /**
779          * Parses Nodeinfo 2
780          *
781          * @param string $nodeinfo_url address of the nodeinfo path
782          * @return array Server data
783          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
784          */
785         private static function parseNodeinfo2(string $nodeinfo_url)
786         {
787                 $curlResult = DI::httpRequest()->get($nodeinfo_url);
788                 if (!$curlResult->isSuccess()) {
789                         return [];
790                 }
791
792                 $nodeinfo = json_decode($curlResult->getBody(), true);
793
794                 if (!is_array($nodeinfo)) {
795                         return [];
796                 }
797
798                 $server = ['detection-method' => self::DETECT_NODEINFO_2,
799                         'register_policy' => Register::CLOSED];
800
801                 if (!empty($nodeinfo['openRegistrations'])) {
802                         $server['register_policy'] = Register::OPEN;
803                 }
804
805                 if (is_array($nodeinfo['software'])) {
806                         if (!empty($nodeinfo['software']['name'])) {
807                                 $server['platform'] = strtolower($nodeinfo['software']['name']);
808                         }
809
810                         if (!empty($nodeinfo['software']['version'])) {
811                                 $server['version'] = $nodeinfo['software']['version'];
812                                 // Version numbers on Nodeinfo are presented with additional info, e.g.:
813                                 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
814                                 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
815                         }
816                 }
817
818                 if (!empty($nodeinfo['metadata']['nodeName'])) {
819                         $server['site_name'] = $nodeinfo['metadata']['nodeName'];
820                 }
821
822                 if (!empty($nodeinfo['usage']['users']['total'])) {
823                         $server['registered-users'] = $nodeinfo['usage']['users']['total'];
824                 }
825
826                 if (!empty($nodeinfo['protocols'])) {
827                         $protocols = [];
828                         foreach ($nodeinfo['protocols'] as $protocol) {
829                                 $protocols[$protocol] = true;
830                         }
831
832                         if (!empty($protocols['dfrn'])) {
833                                 $server['network'] = Protocol::DFRN;
834                         } elseif (!empty($protocols['activitypub'])) {
835                                 $server['network'] = Protocol::ACTIVITYPUB;
836                         } elseif (!empty($protocols['diaspora'])) {
837                                 $server['network'] = Protocol::DIASPORA;
838                         } elseif (!empty($protocols['ostatus'])) {
839                                 $server['network'] = Protocol::OSTATUS;
840                         } elseif (!empty($protocols['gnusocial'])) {
841                                 $server['network'] = Protocol::OSTATUS;
842                         } elseif (!empty($protocols['zot'])) {
843                                 $server['network'] = Protocol::ZOT;
844                         }
845                 }
846
847                 if (empty($server)) {
848                         return [];
849                 }
850
851                 return $server;
852         }
853
854         /**
855          * Fetch server information from a 'siteinfo.json' file on the given server
856          *
857          * @param string $url        URL of the given server
858          * @param array  $serverdata array with server data
859          *
860          * @return array server data
861          */
862         private static function fetchSiteinfo(string $url, array $serverdata)
863         {
864                 $curlResult = DI::httpRequest()->get($url . '/siteinfo.json');
865                 if (!$curlResult->isSuccess()) {
866                         return $serverdata;
867                 }
868
869                 $data = json_decode($curlResult->getBody(), true);
870                 if (empty($data)) {
871                         return $serverdata;
872                 }
873
874                 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
875                         $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
876                 }
877
878                 if (!empty($data['url'])) {
879                         $serverdata['platform'] = strtolower($data['platform']);
880                         $serverdata['version'] = $data['version'];
881                 }
882
883                 if (!empty($data['plugins'])) {
884                         if (in_array('pubcrawl', $data['plugins'])) {
885                                 $serverdata['network'] = Protocol::ACTIVITYPUB;
886                         } elseif (in_array('diaspora', $data['plugins'])) {
887                                 $serverdata['network'] = Protocol::DIASPORA;
888                         } elseif (in_array('gnusoc', $data['plugins'])) {
889                                 $serverdata['network'] = Protocol::OSTATUS;
890                         } else {
891                                 $serverdata['network'] = Protocol::ZOT;
892                         }
893                 }
894
895                 if (!empty($data['site_name'])) {
896                         $serverdata['site_name'] = $data['site_name'];
897                 }
898
899                 if (!empty($data['channels_total'])) {
900                         $serverdata['registered-users'] = $data['channels_total'];
901                 }
902
903                 if (!empty($data['register_policy'])) {
904                         switch ($data['register_policy']) {
905                                 case 'REGISTER_OPEN':
906                                         $serverdata['register_policy'] = Register::OPEN;
907                                         break;
908
909                                 case 'REGISTER_APPROVE':
910                                         $serverdata['register_policy'] = Register::APPROVE;
911                                         break;
912
913                                 case 'REGISTER_CLOSED':
914                                 default:
915                                         $serverdata['register_policy'] = Register::CLOSED;
916                                         break;
917                         }
918                 }
919
920                 return $serverdata;
921         }
922
923         /**
924          * Checks if the server contains a valid host meta file
925          *
926          * @param string $url URL of the given server
927          *
928          * @return boolean 'true' if the server seems to be vital
929          */
930         private static function validHostMeta(string $url)
931         {
932                 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
933                 $curlResult = DI::httpRequest()->get($url . '/.well-known/host-meta', ['timeout' => $xrd_timeout]);
934                 if (!$curlResult->isSuccess()) {
935                         return false;
936                 }
937
938                 $xrd = XML::parseString($curlResult->getBody());
939                 if (!is_object($xrd)) {
940                         return false;
941                 }
942
943                 $elements = XML::elementToArray($xrd);
944                 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
945                         return false;
946                 }
947
948                 $valid = false;
949                 foreach ($elements['xrd']['link'] as $link) {
950                         // When there is more than a single "link" element, the array looks slightly different
951                         if (!empty($link['@attributes'])) {
952                                 $link = $link['@attributes'];
953                         }
954
955                         if (empty($link['rel']) || empty($link['template'])) {
956                                 continue;
957                         }
958
959                         if ($link['rel'] == 'lrdd') {
960                                 // When the webfinger host is the same like the system host, it should be ok.
961                                 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
962                         }
963                 }
964
965                 return $valid;
966         }
967
968         /**
969          * Detect the network of the given server via their known contacts
970          *
971          * @param string $url        URL of the given server
972          * @param array  $serverdata array with server data
973          *
974          * @return array server data
975          */
976         private static function detectNetworkViaContacts(string $url, array $serverdata)
977         {
978                 $contacts = [];
979
980                 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $serverdata['nurl']]]);
981                 while ($apcontact = DBA::fetch($apcontacts)) {
982                         $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
983                 }
984                 DBA::close($apcontacts);
985
986                 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $serverdata['nurl']]]);
987                 while ($pcontact = DBA::fetch($pcontacts)) {
988                         $contacts[$pcontact['nurl']] = $pcontact['url'];
989                 }
990                 DBA::close($pcontacts);
991
992                 if (empty($contacts)) {
993                         return $serverdata;
994                 }
995
996                 foreach ($contacts as $contact) {
997                         $probed = Contact::getByURL($contact);
998                         if (!empty($probed) && in_array($probed['network'], Protocol::FEDERATED)) {
999                                 $serverdata['network'] = $probed['network'];
1000                                 break;
1001                         }
1002                 }
1003
1004                 $serverdata['registered-users'] = max($serverdata['registered-users'], count($contacts));
1005
1006                 return $serverdata;
1007         }
1008
1009         /**
1010          * Checks if the given server does have a '/poco' endpoint.
1011          * This is used for the 'PortableContact' functionality,
1012          * which is used by both Friendica and Hubzilla.
1013          *
1014          * @param string $url        URL of the given server
1015          * @param array  $serverdata array with server data
1016          *
1017          * @return array server data
1018          */
1019         private static function checkPoCo(string $url, array $serverdata)
1020         {
1021                 $serverdata['poco'] = '';
1022
1023                 $curlResult = DI::httpRequest()->get($url . '/poco');
1024                 if (!$curlResult->isSuccess()) {
1025                         return $serverdata;
1026                 }
1027
1028                 $data = json_decode($curlResult->getBody(), true);
1029                 if (empty($data)) {
1030                         return $serverdata;
1031                 }
1032
1033                 if (!empty($data['totalResults'])) {
1034                         $registeredUsers = $serverdata['registered-users'] ?? 0;
1035                         $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers);
1036                         $serverdata['directory-type'] = self::DT_POCO;
1037                         $serverdata['poco'] = $url . '/poco';
1038                 }
1039
1040                 return $serverdata;
1041         }
1042
1043         /**
1044          * Checks if the given server does have a Mastodon style directory endpoint.
1045          *
1046          * @param string $url        URL of the given server
1047          * @param array  $serverdata array with server data
1048          *
1049          * @return array server data
1050          */
1051         public static function checkMastodonDirectory(string $url, array $serverdata)
1052         {
1053                 $curlResult = DI::httpRequest()->get($url . '/api/v1/directory?limit=1');
1054                 if (!$curlResult->isSuccess()) {
1055                         return $serverdata;
1056                 }
1057
1058                 $data = json_decode($curlResult->getBody(), true);
1059                 if (empty($data)) {
1060                         return $serverdata;
1061                 }
1062
1063                 if (count($data) == 1) {
1064                         $serverdata['directory-type'] = self::DT_MASTODON;
1065                 }
1066
1067                 return $serverdata;
1068         }
1069
1070         /**
1071          * Detects the version number of a given server when it was a NextCloud installation
1072          *
1073          * @param string $url        URL of the given server
1074          * @param array  $serverdata array with server data
1075          *
1076          * @return array server data
1077          */
1078         private static function detectNextcloud(string $url, array $serverdata)
1079         {
1080                 $curlResult = DI::httpRequest()->get($url . '/status.php');
1081
1082                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1083                         return $serverdata;
1084                 }
1085
1086                 $data = json_decode($curlResult->getBody(), true);
1087                 if (empty($data)) {
1088                         return $serverdata;
1089                 }
1090
1091                 if (!empty($data['version'])) {
1092                         $serverdata['platform'] = 'nextcloud';
1093                         $serverdata['version'] = $data['version'];
1094                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1095
1096                         if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1097                                 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1098                         }
1099                 }
1100
1101                 return $serverdata;
1102         }
1103
1104         /**
1105          * Detects data from a given server url if it was a mastodon alike system
1106          *
1107          * @param string $url        URL of the given server
1108          * @param array  $serverdata array with server data
1109          *
1110          * @return array server data
1111          */
1112         private static function detectMastodonAlikes(string $url, array $serverdata)
1113         {
1114                 $curlResult = DI::httpRequest()->get($url . '/api/v1/instance');
1115
1116                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1117                         return $serverdata;
1118                 }
1119
1120                 $data = json_decode($curlResult->getBody(), true);
1121                 if (empty($data)) {
1122                         return $serverdata;
1123                 }
1124
1125                 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1126                         $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1127                 }
1128
1129                 if (!empty($data['version'])) {
1130                         $serverdata['platform'] = 'mastodon';
1131                         $serverdata['version'] = $data['version'] ?? '';
1132                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1133                 }
1134
1135                 if (!empty($data['title'])) {
1136                         $serverdata['site_name'] = $data['title'];
1137                 }
1138
1139                 if (!empty($data['title']) && empty($serverdata['platform']) && empty($serverdata['network'])) {
1140                         $serverdata['platform'] = 'mastodon';
1141                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1142                 }
1143
1144                 if (!empty($data['description'])) {
1145                         $serverdata['info'] = trim($data['description']);
1146                 }
1147
1148                 if (!empty($data['stats']['user_count'])) {
1149                         $serverdata['registered-users'] = $data['stats']['user_count'];
1150                 }
1151
1152                 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1153                         $serverdata['platform'] = strtolower($matches[1]);
1154                         $serverdata['version'] = $matches[2];
1155                 }
1156
1157                 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1158                         $serverdata['platform'] = 'pleroma';
1159                         $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1160                 }
1161
1162                 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1163                         $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1164                         $serverdata['platform'] = 'pleroma';
1165                 }
1166
1167                 return $serverdata;
1168         }
1169
1170         /**
1171          * Detects data from typical Hubzilla endpoints
1172          *
1173          * @param string $url        URL of the given server
1174          * @param array  $serverdata array with server data
1175          *
1176          * @return array server data
1177          */
1178         private static function detectHubzilla(string $url, array $serverdata)
1179         {
1180                 $curlResult = DI::httpRequest()->get($url . '/api/statusnet/config.json');
1181                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1182                         return $serverdata;
1183                 }
1184
1185                 $data = json_decode($curlResult->getBody(), true);
1186                 if (empty($data) || empty($data['site'])) {
1187                         return $serverdata;
1188                 }
1189
1190                 if (!empty($data['site']['name'])) {
1191                         $serverdata['site_name'] = $data['site']['name'];
1192                 }
1193
1194                 if (!empty($data['site']['platform'])) {
1195                         $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1196                         $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1197                         $serverdata['network'] = Protocol::ZOT;
1198                 }
1199
1200                 if (!empty($data['site']['hubzilla'])) {
1201                         $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1202                         $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1203                         $serverdata['network'] = Protocol::ZOT;
1204                 }
1205
1206                 if (!empty($data['site']['redmatrix'])) {
1207                         if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1208                                 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1209                         } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1210                                 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1211                         }
1212
1213                         $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1214                         $serverdata['network'] = Protocol::ZOT;
1215                 }
1216
1217                 $private = false;
1218                 $inviteonly = false;
1219                 $closed = false;
1220
1221                 if (!empty($data['site']['closed'])) {
1222                         $closed = self::toBoolean($data['site']['closed']);
1223                 }
1224
1225                 if (!empty($data['site']['private'])) {
1226                         $private = self::toBoolean($data['site']['private']);
1227                 }
1228
1229                 if (!empty($data['site']['inviteonly'])) {
1230                         $inviteonly = self::toBoolean($data['site']['inviteonly']);
1231                 }
1232
1233                 if (!$closed && !$private and $inviteonly) {
1234                         $serverdata['register_policy'] = Register::APPROVE;
1235                 } elseif (!$closed && !$private) {
1236                         $serverdata['register_policy'] = Register::OPEN;
1237                 } else {
1238                         $serverdata['register_policy'] = Register::CLOSED;
1239                 }
1240
1241                 if (!empty($serverdata['network']) && in_array($serverdata['detection-method'],
1242                         [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1243                         $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1244                 }
1245
1246                 return $serverdata;
1247         }
1248
1249         /**
1250          * Converts input value to a boolean value
1251          *
1252          * @param string|integer $val
1253          *
1254          * @return boolean
1255          */
1256         private static function toBoolean($val)
1257         {
1258                 if (($val == 'true') || ($val == 1)) {
1259                         return true;
1260                 } elseif (($val == 'false') || ($val == 0)) {
1261                         return false;
1262                 }
1263
1264                 return $val;
1265         }
1266
1267         /**
1268          * Detect if the URL belongs to a GNU Social server
1269          *
1270          * @param string $url        URL of the given server
1271          * @param array  $serverdata array with server data
1272          *
1273          * @return array server data
1274          */
1275         private static function detectGNUSocial(string $url, array $serverdata)
1276         {
1277                 // Test for GNU Social
1278                 $curlResult = DI::httpRequest()->get($url . '/api/gnusocial/version.json');
1279                 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1280                         ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1281                         $serverdata['platform'] = 'gnusocial';
1282                         // Remove junk that some GNU Social servers return
1283                         $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1284                         $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1285                         $serverdata['version'] = trim($serverdata['version'], '"');
1286                         $serverdata['network'] = Protocol::OSTATUS;
1287
1288                         if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1289                                 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1290                         }
1291         
1292                         return $serverdata;
1293                 }
1294
1295                 // Test for Statusnet
1296                 $curlResult = DI::httpRequest()->get($url . '/api/statusnet/version.json');
1297                 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1298                         ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1299
1300                         // Remove junk that some GNU Social servers return
1301                         $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1302                         $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1303                         $serverdata['version'] = trim($serverdata['version'], '"');
1304
1305                         if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1306                                 $serverdata['platform'] = 'pleroma';
1307                                 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1308                                 $serverdata['network'] = Protocol::ACTIVITYPUB;
1309                         } else {
1310                                 $serverdata['platform'] = 'statusnet';
1311                                 $serverdata['network'] = Protocol::OSTATUS;
1312                         }
1313
1314                         if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1315                                 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1316                         }
1317                 }
1318
1319                 return $serverdata;
1320         }
1321
1322         /**
1323          * Detect if the URL belongs to a Friendica server
1324          *
1325          * @param string $url        URL of the given server
1326          * @param array  $serverdata array with server data
1327          *
1328          * @return array server data
1329          */
1330         private static function detectFriendica(string $url, array $serverdata)
1331         {
1332                 $curlResult = DI::httpRequest()->get($url . '/friendica/json');
1333                 if (!$curlResult->isSuccess()) {
1334                         $curlResult = DI::httpRequest()->get($url . '/friendika/json');
1335                         $friendika = true;
1336                         $platform = 'Friendika';
1337                 } else {
1338                         $friendika = false;
1339                         $platform = 'Friendica';
1340                 }
1341
1342                 if (!$curlResult->isSuccess()) {
1343                         return $serverdata;
1344                 }
1345
1346                 $data = json_decode($curlResult->getBody(), true);
1347                 if (empty($data) || empty($data['version'])) {
1348                         return $serverdata;
1349                 }
1350
1351                 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {                 
1352                         $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1353                 }
1354
1355                 $serverdata['network'] = Protocol::DFRN;
1356                 $serverdata['version'] = $data['version'];
1357
1358                 if (!empty($data['no_scrape_url'])) {
1359                         $serverdata['noscrape'] = $data['no_scrape_url'];
1360                 }
1361
1362                 if (!empty($data['site_name'])) {
1363                         $serverdata['site_name'] = $data['site_name'];
1364                 }
1365
1366                 if (!empty($data['info'])) {
1367                         $serverdata['info'] = trim($data['info']);
1368                 }
1369
1370                 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1371                 switch ($register_policy) {
1372                         case 'REGISTER_OPEN':
1373                                 $serverdata['register_policy'] = Register::OPEN;
1374                                 break;
1375
1376                         case 'REGISTER_APPROVE':
1377                                 $serverdata['register_policy'] = Register::APPROVE;
1378                                 break;
1379
1380                         case 'REGISTER_CLOSED':
1381                         case 'REGISTER_INVITATION':
1382                                 $serverdata['register_policy'] = Register::CLOSED;
1383                                 break;
1384                         default:
1385                                 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
1386                                 $serverdata['register_policy'] = Register::CLOSED;
1387                                 break;
1388                 }
1389
1390                 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
1391
1392                 return $serverdata;
1393         }
1394
1395         /**
1396          * Analyses the landing page of a given server for hints about type and system of that server
1397          *
1398          * @param object $curlResult result of curl execution
1399          * @param array  $serverdata array with server data
1400          * @param string $url        Server URL
1401          *
1402          * @return array server data
1403          */
1404         private static function analyseRootBody($curlResult, array $serverdata, string $url)
1405         {
1406                 $doc = new DOMDocument();
1407                 @$doc->loadHTML($curlResult->getBody());
1408                 $xpath = new DOMXPath($doc);
1409
1410                 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
1411                 if (!empty($title)) {
1412                         $serverdata['site_name'] = $title;
1413                 }
1414
1415                 $list = $xpath->query('//meta[@name]');
1416
1417                 foreach ($list as $node) {
1418                         $attr = [];
1419                         if ($node->attributes->length) {
1420                                 foreach ($node->attributes as $attribute) {
1421                                         $value = trim($attribute->value);
1422                                         if (empty($value)) {
1423                                                 continue;
1424                                         }
1425
1426                                         $attr[$attribute->name] = $value;
1427                                 }
1428
1429                                 if (empty($attr['name']) || empty($attr['content'])) {
1430                                         continue;
1431                                 }
1432                         }
1433
1434                         if ($attr['name'] == 'description') {
1435                                 $serverdata['info'] = $attr['content'];
1436                         }
1437
1438                         if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
1439                                 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad'])) {
1440                                 $serverdata['platform'] = strtolower($attr['content']);
1441                                 if (in_array($attr['content'], ['Misskey', 'Write.as'])) {
1442                                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1443                                 }
1444                         }
1445                         if (($attr['name'] == 'generator') && (empty($serverdata['platform']) || (substr(strtolower($attr['content']), 0, 9) == 'wordpress'))) {
1446                                 $serverdata['platform'] = strtolower($attr['content']);
1447                                 $version_part = explode(' ', $attr['content']);
1448
1449                                 if (count($version_part) == 2) {
1450                                         if (in_array($version_part[0], ['WordPress'])) {
1451                                                 $serverdata['platform'] = strtolower($version_part[0]);
1452                                                 $serverdata['version'] = $version_part[1];
1453
1454                                                 // We still do need a reliable test if some AP plugin is activated
1455                                                 if (DBA::exists('apcontact', ['baseurl' => $url])) {
1456                                                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1457                                                 } else {
1458                                                         $serverdata['network'] = Protocol::FEED;
1459                                                 }
1460
1461                                                 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1462                                                         $serverdata['detection-method'] = self::DETECT_BODY;
1463                                                 }
1464                                         }
1465                                         if (in_array($version_part[0], ['Friendika', 'Friendica'])) {
1466                                                 $serverdata['platform'] = strtolower($version_part[0]);
1467                                                 $serverdata['version'] = $version_part[1];
1468                                                 $serverdata['network'] = Protocol::DFRN;
1469                                         }
1470                                 }
1471                         }
1472                 }
1473
1474                 $list = $xpath->query('//meta[@property]');
1475
1476                 foreach ($list as $node) {
1477                         $attr = [];
1478                         if ($node->attributes->length) {
1479                                 foreach ($node->attributes as $attribute) {
1480                                         $value = trim($attribute->value);
1481                                         if (empty($value)) {
1482                                                 continue;
1483                                         }
1484
1485                                         $attr[$attribute->name] = $value;
1486                                 }
1487
1488                                 if (empty($attr['property']) || empty($attr['content'])) {
1489                                         continue;
1490                                 }
1491                         }
1492
1493                         if ($attr['property'] == 'og:site_name') {
1494                                 $serverdata['site_name'] = $attr['content'];
1495                         }
1496
1497                         if ($attr['property'] == 'og:description') {
1498                                 $serverdata['info'] = $attr['content'];
1499                         }
1500
1501                         if ($attr['property'] == 'og:platform') {
1502                                 $serverdata['platform'] = strtolower($attr['content']);
1503
1504                                 if (in_array($attr['content'], ['PeerTube'])) {
1505                                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1506                                 }
1507                         }
1508
1509                         if ($attr['property'] == 'generator') {
1510                                 $serverdata['platform'] = strtolower($attr['content']);
1511
1512                                 if (in_array($attr['content'], ['hubzilla'])) {
1513                                         // We later check which compatible protocol modules are loaded.
1514                                         $serverdata['network'] = Protocol::ZOT;
1515                                 }
1516                         }
1517                 }
1518
1519                 if (!empty($serverdata['network']) && ($serverdata['detection-method'] == self::DETECT_MANUAL)) {
1520                         $serverdata['detection-method'] = self::DETECT_BODY;
1521                 }
1522
1523                 return $serverdata;
1524         }
1525
1526         /**
1527          * Analyses the header data of a given server for hints about type and system of that server
1528          *
1529          * @param object $curlResult result of curl execution
1530          * @param array  $serverdata array with server data
1531          *
1532          * @return array server data
1533          */
1534         private static function analyseRootHeader($curlResult, array $serverdata)
1535         {
1536                 if ($curlResult->getHeader('server') == 'Mastodon') {
1537                         $serverdata['platform'] = 'mastodon';
1538                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1539                 } elseif ($curlResult->inHeader('x-diaspora-version')) {
1540                         $serverdata['platform'] = 'diaspora';
1541                         $serverdata['network'] = Protocol::DIASPORA;
1542                         $serverdata['version'] = $curlResult->getHeader('x-diaspora-version');
1543                 } elseif ($curlResult->inHeader('x-friendica-version')) {
1544                         $serverdata['platform'] = 'friendica';
1545                         $serverdata['network'] = Protocol::DFRN;
1546                         $serverdata['version'] = $curlResult->getHeader('x-friendica-version');
1547                 } else {
1548                         return $serverdata;
1549                 }
1550
1551                 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1552                         $serverdata['detection-method'] = self::DETECT_HEADER;
1553                 }
1554
1555                 return $serverdata;
1556         }
1557
1558         /**
1559          * Test if the body contains valid content
1560          *
1561          * @param string $body
1562          * @return boolean
1563          */
1564         private static function invalidBody(string $body)
1565         {
1566                 // Currently we only test for a HTML element.
1567                 // Possibly we enhance this in the future.
1568                 return !strpos($body, '>');
1569         }
1570
1571         /**
1572          * Update GServer entries
1573          */
1574         public static function discover()
1575         {
1576                 // Update the server list
1577                 self::discoverFederation();
1578
1579                 $no_of_queries = 5;
1580
1581                 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
1582
1583                 if ($requery_days == 0) {
1584                         $requery_days = 7;
1585                 }
1586
1587                 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
1588
1589                 $gservers = DBA::p("SELECT `id`, `url`, `nurl`, `network`, `poco`, `directory-type`
1590                         FROM `gserver`
1591                         WHERE NOT `failed`
1592                         AND `directory-type` != ?
1593                         AND `last_poco_query` < ?
1594                         ORDER BY RAND()", self::DT_NONE, $last_update
1595                 );
1596
1597                 while ($gserver = DBA::fetch($gservers)) {
1598                         Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1599                         Worker::add(PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
1600
1601                         Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1602                         Worker::add(PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
1603
1604                         $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1605                         DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);
1606         
1607                         if (--$no_of_queries == 0) {
1608                                 break;
1609                         }
1610                 }
1611
1612                 DBA::close($gservers);
1613         }
1614
1615         /**
1616          * Discover federated servers
1617          */
1618         private static function discoverFederation()
1619         {
1620                 $last = DI::config()->get('poco', 'last_federation_discovery');
1621
1622                 if ($last) {
1623                         $next = $last + (24 * 60 * 60);
1624
1625                         if ($next > time()) {
1626                                 return;
1627                         }
1628                 }
1629
1630                 // Discover federated servers
1631                 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
1632                 foreach ($protocols as $protocol) {
1633                         $query = '{nodes(protocol:"' . $protocol . '"){host}}';
1634                         $curlResult = DI::httpRequest()->fetch('https://the-federation.info/graphql?query=' . urlencode($query));
1635                         if (!empty($curlResult)) {
1636                                 $data = json_decode($curlResult, true);
1637                                 if (!empty($data['data']['nodes'])) {
1638                                         foreach ($data['data']['nodes'] as $server) {
1639                                                 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
1640                                                 self::add('https://' . $server['host'], true);
1641                                         }
1642                                 }
1643                         }
1644                 }
1645
1646                 // Disvover Mastodon servers
1647                 $accesstoken = DI::config()->get('system', 'instances_social_key');
1648
1649                 if (!empty($accesstoken)) {
1650                         $api = 'https://instances.social/api/1.0/instances/list?count=0';
1651                         $header = ['Authorization: Bearer '.$accesstoken];
1652                         $curlResult = DI::httpRequest()->get($api, ['header' => $header]);
1653
1654                         if ($curlResult->isSuccess()) {
1655                                 $servers = json_decode($curlResult->getBody(), true);
1656
1657                                 foreach ($servers['instances'] as $server) {
1658                                         $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
1659                                         self::add($url);
1660                                 }
1661                         }
1662                 }
1663
1664                 DI::config()->set('poco', 'last_federation_discovery', time());
1665         }
1666 }