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