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