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