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