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