]> git.mxchange.org Git - friendica.git/blob - src/Model/GServer.php
Fixup HTTP headers for httpClient requests
[friendica.git] / src / Model / GServer.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
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\IHTTPResult;
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 IHTTPResult $httpResult
676          *
677          * @return array Server data
678          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
679          */
680         private static function fetchNodeinfo(string $url, IHTTPResult $httpResult)
681         {
682                 if (!$httpResult->isSuccess()) {
683                         return [];
684                 }
685
686                 $nodeinfo = json_decode($httpResult->getBody(), true);
687
688                 if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
689                         return [];
690                 }
691
692                 $nodeinfo1_url = '';
693                 $nodeinfo2_url = '';
694
695                 foreach ($nodeinfo['links'] as $link) {
696                         if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
697                                 Logger::info('Invalid nodeinfo format', ['url' => $url]);
698                                 continue;
699                         }
700                         if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
701                                 $nodeinfo1_url = $link['href'];
702                         } elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
703                                 $nodeinfo2_url = $link['href'];
704                         }
705                 }
706
707                 if ($nodeinfo1_url . $nodeinfo2_url == '') {
708                         return [];
709                 }
710
711                 $server = [];
712
713                 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
714                 if (!empty($nodeinfo2_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
715                         $server = self::parseNodeinfo2($nodeinfo2_url);
716                 }
717
718                 // When the nodeinfo url isn't on the same host, then there is obviously something wrong
719                 if (empty($server) && !empty($nodeinfo1_url) && (parse_url($url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
720                         $server = self::parseNodeinfo1($nodeinfo1_url);
721                 }
722
723                 return $server;
724         }
725
726         /**
727          * Parses Nodeinfo 1
728          *
729          * @param string $nodeinfo_url address of the nodeinfo path
730          * @return array Server data
731          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
732          */
733         private static function parseNodeinfo1(string $nodeinfo_url)
734         {
735                 $curlResult = DI::httpRequest()->get($nodeinfo_url);
736
737                 if (!$curlResult->isSuccess()) {
738                         return [];
739                 }
740
741                 $nodeinfo = json_decode($curlResult->getBody(), true);
742
743                 if (!is_array($nodeinfo)) {
744                         return [];
745                 }
746
747                 $server = ['detection-method' => self::DETECT_NODEINFO_1,
748                         'register_policy' => Register::CLOSED];
749
750                 if (!empty($nodeinfo['openRegistrations'])) {
751                         $server['register_policy'] = Register::OPEN;
752                 }
753
754                 if (is_array($nodeinfo['software'])) {
755                         if (!empty($nodeinfo['software']['name'])) {
756                                 $server['platform'] = strtolower($nodeinfo['software']['name']);
757                         }
758
759                         if (!empty($nodeinfo['software']['version'])) {
760                                 $server['version'] = $nodeinfo['software']['version'];
761                                 // Version numbers on Nodeinfo are presented with additional info, e.g.:
762                                 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
763                                 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
764                         }
765                 }
766
767                 if (!empty($nodeinfo['metadata']['nodeName'])) {
768                         $server['site_name'] = $nodeinfo['metadata']['nodeName'];
769                 }
770
771                 if (!empty($nodeinfo['usage']['users']['total'])) {
772                         $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
773                 }
774
775                 if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
776                         $protocols = [];
777                         foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
778                                 $protocols[$protocol] = true;
779                         }
780
781                         if (!empty($protocols['friendica'])) {
782                                 $server['network'] = Protocol::DFRN;
783                         } elseif (!empty($protocols['activitypub'])) {
784                                 $server['network'] = Protocol::ACTIVITYPUB;
785                         } elseif (!empty($protocols['diaspora'])) {
786                                 $server['network'] = Protocol::DIASPORA;
787                         } elseif (!empty($protocols['ostatus'])) {
788                                 $server['network'] = Protocol::OSTATUS;
789                         } elseif (!empty($protocols['gnusocial'])) {
790                                 $server['network'] = Protocol::OSTATUS;
791                         } elseif (!empty($protocols['zot'])) {
792                                 $server['network'] = Protocol::ZOT;
793                         }
794                 }
795
796                 if (empty($server)) {
797                         return [];
798                 }
799
800                 return $server;
801         }
802
803         /**
804          * Parses Nodeinfo 2
805          *
806          * @see https://git.feneas.org/jaywink/nodeinfo2
807          * @param string $nodeinfo_url address of the nodeinfo path
808          * @return array Server data
809          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
810          */
811         private static function parseNodeinfo2(string $nodeinfo_url)
812         {
813                 $curlResult = DI::httpRequest()->get($nodeinfo_url);
814                 if (!$curlResult->isSuccess()) {
815                         return [];
816                 }
817
818                 $nodeinfo = json_decode($curlResult->getBody(), true);
819
820                 if (!is_array($nodeinfo)) {
821                         return [];
822                 }
823
824                 $server = ['detection-method' => self::DETECT_NODEINFO_2,
825                         'register_policy' => Register::CLOSED];
826
827                 if (!empty($nodeinfo['openRegistrations'])) {
828                         $server['register_policy'] = Register::OPEN;
829                 }
830
831                 if (is_array($nodeinfo['software'])) {
832                         if (!empty($nodeinfo['software']['name'])) {
833                                 $server['platform'] = strtolower($nodeinfo['software']['name']);
834                         }
835
836                         if (!empty($nodeinfo['software']['version'])) {
837                                 $server['version'] = $nodeinfo['software']['version'];
838                                 // Version numbers on Nodeinfo are presented with additional info, e.g.:
839                                 // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
840                                 $server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
841                         }
842                 }
843
844                 if (!empty($nodeinfo['metadata']['nodeName'])) {
845                         $server['site_name'] = $nodeinfo['metadata']['nodeName'];
846                 }
847
848                 if (!empty($nodeinfo['usage']['users']['total'])) {
849                         $server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
850                 }
851
852                 if (!empty($nodeinfo['protocols'])) {
853                         $protocols = [];
854                         foreach ($nodeinfo['protocols'] as $protocol) {
855                                 if (is_string($protocol)) {
856                                         $protocols[$protocol] = true;
857                                 }
858                         }
859
860                         if (!empty($protocols['dfrn'])) {
861                                 $server['network'] = Protocol::DFRN;
862                         } elseif (!empty($protocols['activitypub'])) {
863                                 $server['network'] = Protocol::ACTIVITYPUB;
864                         } elseif (!empty($protocols['diaspora'])) {
865                                 $server['network'] = Protocol::DIASPORA;
866                         } elseif (!empty($protocols['ostatus'])) {
867                                 $server['network'] = Protocol::OSTATUS;
868                         } elseif (!empty($protocols['gnusocial'])) {
869                                 $server['network'] = Protocol::OSTATUS;
870                         } elseif (!empty($protocols['zot'])) {
871                                 $server['network'] = Protocol::ZOT;
872                         }
873                 }
874
875                 if (empty($server)) {
876                         return [];
877                 }
878
879                 return $server;
880         }
881
882         /**
883          * Fetch server information from a 'siteinfo.json' file on the given server
884          *
885          * @param string $url        URL of the given server
886          * @param array  $serverdata array with server data
887          *
888          * @return array server data
889          */
890         private static function fetchSiteinfo(string $url, array $serverdata)
891         {
892                 $curlResult = DI::httpRequest()->get($url . '/siteinfo.json');
893                 if (!$curlResult->isSuccess()) {
894                         return $serverdata;
895                 }
896
897                 $data = json_decode($curlResult->getBody(), true);
898                 if (empty($data)) {
899                         return $serverdata;
900                 }
901
902                 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
903                         $serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
904                 }
905
906                 if (!empty($data['url'])) {
907                         $serverdata['platform'] = strtolower($data['platform']);
908                         $serverdata['version'] = $data['version'];
909                 }
910
911                 if (!empty($data['plugins'])) {
912                         if (in_array('pubcrawl', $data['plugins'])) {
913                                 $serverdata['network'] = Protocol::ACTIVITYPUB;
914                         } elseif (in_array('diaspora', $data['plugins'])) {
915                                 $serverdata['network'] = Protocol::DIASPORA;
916                         } elseif (in_array('gnusoc', $data['plugins'])) {
917                                 $serverdata['network'] = Protocol::OSTATUS;
918                         } else {
919                                 $serverdata['network'] = Protocol::ZOT;
920                         }
921                 }
922
923                 if (!empty($data['site_name'])) {
924                         $serverdata['site_name'] = $data['site_name'];
925                 }
926
927                 if (!empty($data['channels_total'])) {
928                         $serverdata['registered-users'] = max($data['channels_total'], 1);
929                 }
930
931                 if (!empty($data['register_policy'])) {
932                         switch ($data['register_policy']) {
933                                 case 'REGISTER_OPEN':
934                                         $serverdata['register_policy'] = Register::OPEN;
935                                         break;
936
937                                 case 'REGISTER_APPROVE':
938                                         $serverdata['register_policy'] = Register::APPROVE;
939                                         break;
940
941                                 case 'REGISTER_CLOSED':
942                                 default:
943                                         $serverdata['register_policy'] = Register::CLOSED;
944                                         break;
945                         }
946                 }
947
948                 return $serverdata;
949         }
950
951         /**
952          * Checks if the server contains a valid host meta file
953          *
954          * @param string $url URL of the given server
955          *
956          * @return boolean 'true' if the server seems to be vital
957          */
958         private static function validHostMeta(string $url)
959         {
960                 $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
961                 $curlResult = DI::httpRequest()->get($url . '/.well-known/host-meta', ['timeout' => $xrd_timeout]);
962                 if (!$curlResult->isSuccess()) {
963                         return false;
964                 }
965
966                 $xrd = XML::parseString($curlResult->getBody());
967                 if (!is_object($xrd)) {
968                         return false;
969                 }
970
971                 $elements = XML::elementToArray($xrd);
972                 if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
973                         return false;
974                 }
975
976                 $valid = false;
977                 foreach ($elements['xrd']['link'] as $link) {
978                         // When there is more than a single "link" element, the array looks slightly different
979                         if (!empty($link['@attributes'])) {
980                                 $link = $link['@attributes'];
981                         }
982
983                         if (empty($link['rel']) || empty($link['template'])) {
984                                 continue;
985                         }
986
987                         if ($link['rel'] == 'lrdd') {
988                                 // When the webfinger host is the same like the system host, it should be ok.
989                                 $valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
990                         }
991                 }
992
993                 return $valid;
994         }
995
996         /**
997          * Detect the network of the given server via their known contacts
998          *
999          * @param string $url        URL of the given server
1000          * @param array  $serverdata array with server data
1001          *
1002          * @return array server data
1003          */
1004         private static function detectNetworkViaContacts(string $url, array $serverdata)
1005         {
1006                 $contacts = [];
1007
1008                 $apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $serverdata['nurl']]]);
1009                 while ($apcontact = DBA::fetch($apcontacts)) {
1010                         $contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
1011                 }
1012                 DBA::close($apcontacts);
1013
1014                 $pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $serverdata['nurl']]]);
1015                 while ($pcontact = DBA::fetch($pcontacts)) {
1016                         $contacts[$pcontact['nurl']] = $pcontact['url'];
1017                 }
1018                 DBA::close($pcontacts);
1019
1020                 if (empty($contacts)) {
1021                         return $serverdata;
1022                 }
1023
1024                 foreach ($contacts as $contact) {
1025                         $probed = Contact::getByURL($contact);
1026                         if (!empty($probed) && in_array($probed['network'], Protocol::FEDERATED)) {
1027                                 $serverdata['network'] = $probed['network'];
1028                                 break;
1029                         }
1030                 }
1031
1032                 $serverdata['registered-users'] = max($serverdata['registered-users'], count($contacts), 1);
1033
1034                 return $serverdata;
1035         }
1036
1037         /**
1038          * Checks if the given server does have a '/poco' endpoint.
1039          * This is used for the 'PortableContact' functionality,
1040          * which is used by both Friendica and Hubzilla.
1041          *
1042          * @param string $url        URL of the given server
1043          * @param array  $serverdata array with server data
1044          *
1045          * @return array server data
1046          */
1047         private static function checkPoCo(string $url, array $serverdata)
1048         {
1049                 $serverdata['poco'] = '';
1050
1051                 $curlResult = DI::httpRequest()->get($url . '/poco');
1052                 if (!$curlResult->isSuccess()) {
1053                         return $serverdata;
1054                 }
1055
1056                 $data = json_decode($curlResult->getBody(), true);
1057                 if (empty($data)) {
1058                         return $serverdata;
1059                 }
1060
1061                 if (!empty($data['totalResults'])) {
1062                         $registeredUsers = $serverdata['registered-users'] ?? 0;
1063                         $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
1064                         $serverdata['directory-type'] = self::DT_POCO;
1065                         $serverdata['poco'] = $url . '/poco';
1066                 }
1067
1068                 return $serverdata;
1069         }
1070
1071         /**
1072          * Checks if the given server does have a Mastodon style directory endpoint.
1073          *
1074          * @param string $url        URL of the given server
1075          * @param array  $serverdata array with server data
1076          *
1077          * @return array server data
1078          */
1079         public static function checkMastodonDirectory(string $url, array $serverdata)
1080         {
1081                 $curlResult = DI::httpRequest()->get($url . '/api/v1/directory?limit=1');
1082                 if (!$curlResult->isSuccess()) {
1083                         return $serverdata;
1084                 }
1085
1086                 $data = json_decode($curlResult->getBody(), true);
1087                 if (empty($data)) {
1088                         return $serverdata;
1089                 }
1090
1091                 if (count($data) == 1) {
1092                         $serverdata['directory-type'] = self::DT_MASTODON;
1093                 }
1094
1095                 return $serverdata;
1096         }
1097
1098         /**
1099          * Detects Peertube via their known endpoint
1100          *
1101          * @param string $url        URL of the given server
1102          * @param array  $serverdata array with server data
1103          *
1104          * @return array server data
1105          */
1106         private static function detectPeertube(string $url, array $serverdata)
1107         {
1108                 $curlResult = DI::httpRequest()->get($url . '/api/v1/config');
1109
1110                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1111                         return $serverdata;
1112                 }
1113
1114                 $data = json_decode($curlResult->getBody(), true);
1115                 if (empty($data)) {
1116                         return $serverdata;
1117                 }
1118
1119                 if (!empty($data['instance']) && !empty($data['serverVersion'])) {
1120                         $serverdata['platform'] = 'peertube';
1121                         $serverdata['version'] = $data['serverVersion'];
1122                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1123
1124                         if (!empty($data['instance']['name'])) {
1125                                 $serverdata['site_name'] = $data['instance']['name'];
1126                         }
1127
1128                         if (!empty($data['instance']['shortDescription'])) {
1129                                 $serverdata['info'] = $data['instance']['shortDescription'];
1130                         }
1131
1132                         if (!empty($data['signup'])) {
1133                                 if (!empty($data['signup']['allowed'])) {
1134                                         $serverdata['register_policy'] = Register::OPEN;
1135                                 }
1136                         }
1137
1138                         if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1139                                 $serverdata['detection-method'] = self::DETECT_V1_CONFIG;
1140                         }
1141                 }
1142
1143                 return $serverdata;
1144         }
1145
1146         /**
1147          * Detects the version number of a given server when it was a NextCloud installation
1148          *
1149          * @param string $url        URL of the given server
1150          * @param array  $serverdata array with server data
1151          *
1152          * @return array server data
1153          */
1154         private static function detectNextcloud(string $url, array $serverdata)
1155         {
1156                 $curlResult = DI::httpRequest()->get($url . '/status.php');
1157
1158                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1159                         return $serverdata;
1160                 }
1161
1162                 $data = json_decode($curlResult->getBody(), true);
1163                 if (empty($data)) {
1164                         return $serverdata;
1165                 }
1166
1167                 if (!empty($data['version'])) {
1168                         $serverdata['platform'] = 'nextcloud';
1169                         $serverdata['version'] = $data['version'];
1170                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1171
1172                         if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1173                                 $serverdata['detection-method'] = self::DETECT_STATUS_PHP;
1174                         }
1175                 }
1176
1177                 return $serverdata;
1178         }
1179
1180         /**
1181          * Detects data from a given server url if it was a mastodon alike system
1182          *
1183          * @param string $url        URL of the given server
1184          * @param array  $serverdata array with server data
1185          *
1186          * @return array server data
1187          */
1188         private static function detectMastodonAlikes(string $url, array $serverdata)
1189         {
1190                 $curlResult = DI::httpRequest()->get($url . '/api/v1/instance');
1191
1192                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1193                         return $serverdata;
1194                 }
1195
1196                 $data = json_decode($curlResult->getBody(), true);
1197                 if (empty($data)) {
1198                         return $serverdata;
1199                 }
1200
1201                 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1202                         $serverdata['detection-method'] = self::DETECT_MASTODON_API;
1203                 }
1204
1205                 if (!empty($data['version'])) {
1206                         $serverdata['platform'] = 'mastodon';
1207                         $serverdata['version'] = $data['version'] ?? '';
1208                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1209                 }
1210
1211                 if (!empty($data['title'])) {
1212                         $serverdata['site_name'] = $data['title'];
1213                 }
1214
1215                 if (!empty($data['title']) && empty($serverdata['platform']) && empty($serverdata['network'])) {
1216                         $serverdata['platform'] = 'mastodon';
1217                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1218                 }
1219
1220                 if (!empty($data['description'])) {
1221                         $serverdata['info'] = trim($data['description']);
1222                 }
1223
1224                 if (!empty($data['stats']['user_count'])) {
1225                         $serverdata['registered-users'] = max($data['stats']['user_count'], 1);
1226                 }
1227
1228                 if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
1229                         $serverdata['platform'] = strtolower($matches[1]);
1230                         $serverdata['version'] = $matches[2];
1231                 }
1232
1233                 if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
1234                         $serverdata['platform'] = 'pleroma';
1235                         $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1236                 }
1237
1238                 if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
1239                         $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
1240                         $serverdata['platform'] = 'pleroma';
1241                 }
1242
1243                 return $serverdata;
1244         }
1245
1246         /**
1247          * Detects data from typical Hubzilla endpoints
1248          *
1249          * @param string $url        URL of the given server
1250          * @param array  $serverdata array with server data
1251          *
1252          * @return array server data
1253          */
1254         private static function detectHubzilla(string $url, array $serverdata)
1255         {
1256                 $curlResult = DI::httpRequest()->get($url . '/api/statusnet/config.json');
1257                 if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
1258                         return $serverdata;
1259                 }
1260
1261                 $data = json_decode($curlResult->getBody(), true);
1262                 if (empty($data) || empty($data['site'])) {
1263                         return $serverdata;
1264                 }
1265
1266                 if (!empty($data['site']['name'])) {
1267                         $serverdata['site_name'] = $data['site']['name'];
1268                 }
1269
1270                 if (!empty($data['site']['platform'])) {
1271                         $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
1272                         $serverdata['version'] = $data['site']['platform']['STD_VERSION'];
1273                         $serverdata['network'] = Protocol::ZOT;
1274                 }
1275
1276                 if (!empty($data['site']['hubzilla'])) {
1277                         $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
1278                         $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
1279                         $serverdata['network'] = Protocol::ZOT;
1280                 }
1281
1282                 if (!empty($data['site']['redmatrix'])) {
1283                         if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
1284                                 $serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
1285                         } elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
1286                                 $serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
1287                         }
1288
1289                         $serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
1290                         $serverdata['network'] = Protocol::ZOT;
1291                 }
1292
1293                 $private = false;
1294                 $inviteonly = false;
1295                 $closed = false;
1296
1297                 if (!empty($data['site']['closed'])) {
1298                         $closed = self::toBoolean($data['site']['closed']);
1299                 }
1300
1301                 if (!empty($data['site']['private'])) {
1302                         $private = self::toBoolean($data['site']['private']);
1303                 }
1304
1305                 if (!empty($data['site']['inviteonly'])) {
1306                         $inviteonly = self::toBoolean($data['site']['inviteonly']);
1307                 }
1308
1309                 if (!$closed && !$private and $inviteonly) {
1310                         $serverdata['register_policy'] = Register::APPROVE;
1311                 } elseif (!$closed && !$private) {
1312                         $serverdata['register_policy'] = Register::OPEN;
1313                 } else {
1314                         $serverdata['register_policy'] = Register::CLOSED;
1315                 }
1316
1317                 if (!empty($serverdata['network']) && in_array($serverdata['detection-method'],
1318                         [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1319                         $serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
1320                 }
1321
1322                 return $serverdata;
1323         }
1324
1325         /**
1326          * Converts input value to a boolean value
1327          *
1328          * @param string|integer $val
1329          *
1330          * @return boolean
1331          */
1332         private static function toBoolean($val)
1333         {
1334                 if (($val == 'true') || ($val == 1)) {
1335                         return true;
1336                 } elseif (($val == 'false') || ($val == 0)) {
1337                         return false;
1338                 }
1339
1340                 return $val;
1341         }
1342
1343         /**
1344          * Detect if the URL belongs to a GNU Social server
1345          *
1346          * @param string $url        URL of the given server
1347          * @param array  $serverdata array with server data
1348          *
1349          * @return array server data
1350          */
1351         private static function detectGNUSocial(string $url, array $serverdata)
1352         {
1353                 // Test for GNU Social
1354                 $curlResult = DI::httpRequest()->get($url . '/api/gnusocial/version.json');
1355                 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1356                         ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1357                         $serverdata['platform'] = 'gnusocial';
1358                         // Remove junk that some GNU Social servers return
1359                         $serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
1360                         $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1361                         $serverdata['version'] = trim($serverdata['version'], '"');
1362                         $serverdata['network'] = Protocol::OSTATUS;
1363
1364                         if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1365                                 $serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
1366                         }
1367         
1368                         return $serverdata;
1369                 }
1370
1371                 // Test for Statusnet
1372                 $curlResult = DI::httpRequest()->get($url . '/api/statusnet/version.json');
1373                 if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
1374                         ($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
1375
1376                         // Remove junk that some GNU Social servers return
1377                         $serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
1378                         $serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
1379                         $serverdata['version'] = trim($serverdata['version'], '"');
1380
1381                         if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
1382                                 $serverdata['platform'] = 'pleroma';
1383                                 $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
1384                                 $serverdata['network'] = Protocol::ACTIVITYPUB;
1385                         } else {
1386                                 $serverdata['platform'] = 'statusnet';
1387                                 $serverdata['network'] = Protocol::OSTATUS;
1388                         }
1389
1390                         if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {
1391                                 $serverdata['detection-method'] = self::DETECT_STATUSNET;
1392                         }
1393                 }
1394
1395                 return $serverdata;
1396         }
1397
1398         /**
1399          * Detect if the URL belongs to a Friendica server
1400          *
1401          * @param string $url        URL of the given server
1402          * @param array  $serverdata array with server data
1403          *
1404          * @return array server data
1405          */
1406         private static function detectFriendica(string $url, array $serverdata)
1407         {
1408                 $curlResult = DI::httpRequest()->get($url . '/friendica/json');
1409                 if (!$curlResult->isSuccess()) {
1410                         $curlResult = DI::httpRequest()->get($url . '/friendika/json');
1411                         $friendika = true;
1412                         $platform = 'Friendika';
1413                 } else {
1414                         $friendika = false;
1415                         $platform = 'Friendica';
1416                 }
1417
1418                 if (!$curlResult->isSuccess()) {
1419                         return $serverdata;
1420                 }
1421
1422                 $data = json_decode($curlResult->getBody(), true);
1423                 if (empty($data) || empty($data['version'])) {
1424                         return $serverdata;
1425                 }
1426
1427                 if (in_array($serverdata['detection-method'], [self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_MANUAL])) {                 
1428                         $serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
1429                 }
1430
1431                 $serverdata['network'] = Protocol::DFRN;
1432                 $serverdata['version'] = $data['version'];
1433
1434                 if (!empty($data['no_scrape_url'])) {
1435                         $serverdata['noscrape'] = $data['no_scrape_url'];
1436                 }
1437
1438                 if (!empty($data['site_name'])) {
1439                         $serverdata['site_name'] = $data['site_name'];
1440                 }
1441
1442                 if (!empty($data['info'])) {
1443                         $serverdata['info'] = trim($data['info']);
1444                 }
1445
1446                 $register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
1447                 switch ($register_policy) {
1448                         case 'REGISTER_OPEN':
1449                                 $serverdata['register_policy'] = Register::OPEN;
1450                                 break;
1451
1452                         case 'REGISTER_APPROVE':
1453                                 $serverdata['register_policy'] = Register::APPROVE;
1454                                 break;
1455
1456                         case 'REGISTER_CLOSED':
1457                         case 'REGISTER_INVITATION':
1458                                 $serverdata['register_policy'] = Register::CLOSED;
1459                                 break;
1460                         default:
1461                                 Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
1462                                 $serverdata['register_policy'] = Register::CLOSED;
1463                                 break;
1464                 }
1465
1466                 $serverdata['platform'] = strtolower($data['platform'] ?? $platform);
1467
1468                 return $serverdata;
1469         }
1470
1471         /**
1472          * Analyses the landing page of a given server for hints about type and system of that server
1473          *
1474          * @param object $curlResult result of curl execution
1475          * @param array  $serverdata array with server data
1476          * @param string $url        Server URL
1477          *
1478          * @return array server data
1479          */
1480         private static function analyseRootBody($curlResult, array $serverdata, string $url)
1481         {
1482                 if (empty($curlResult->getBody())) {
1483                         return $serverdata;
1484                 }
1485
1486                 $doc = new DOMDocument();
1487                 @$doc->loadHTML($curlResult->getBody());
1488                 $xpath = new DOMXPath($doc);
1489
1490                 $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
1491                 if (!empty($title)) {
1492                         $serverdata['site_name'] = $title;
1493                 }
1494
1495                 $list = $xpath->query('//meta[@name]');
1496
1497                 foreach ($list as $node) {
1498                         $attr = [];
1499                         if ($node->attributes->length) {
1500                                 foreach ($node->attributes as $attribute) {
1501                                         $value = trim($attribute->value);
1502                                         if (empty($value)) {
1503                                                 continue;
1504                                         }
1505
1506                                         $attr[$attribute->name] = $value;
1507                                 }
1508
1509                                 if (empty($attr['name']) || empty($attr['content'])) {
1510                                         continue;
1511                                 }
1512                         }
1513
1514                         if ($attr['name'] == 'description') {
1515                                 $serverdata['info'] = $attr['content'];
1516                         }
1517
1518                         if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
1519                                 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad'])) {
1520                                 $serverdata['platform'] = strtolower($attr['content']);
1521                                 if (in_array($attr['content'], ['Misskey', 'Write.as'])) {
1522                                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1523                                 }
1524                         }
1525                         if (($attr['name'] == 'generator') && (empty($serverdata['platform']) || (substr(strtolower($attr['content']), 0, 9) == 'wordpress'))) {
1526                                 $serverdata['platform'] = strtolower($attr['content']);
1527                                 $version_part = explode(' ', $attr['content']);
1528
1529                                 if (count($version_part) == 2) {
1530                                         if (in_array($version_part[0], ['WordPress'])) {
1531                                                 $serverdata['platform'] = 'wordpress';
1532                                                 $serverdata['version'] = $version_part[1];
1533
1534                                                 // We still do need a reliable test if some AP plugin is activated
1535                                                 if (DBA::exists('apcontact', ['baseurl' => $url])) {
1536                                                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1537                                                 } else {
1538                                                         $serverdata['network'] = Protocol::FEED;
1539                                                 }
1540
1541                                                 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1542                                                         $serverdata['detection-method'] = self::DETECT_BODY;
1543                                                 }
1544                                         }
1545                                         if (in_array($version_part[0], ['Friendika', 'Friendica'])) {
1546                                                 $serverdata['platform'] = strtolower($version_part[0]);
1547                                                 $serverdata['version'] = $version_part[1];
1548                                                 $serverdata['network'] = Protocol::DFRN;
1549                                         }
1550                                 }
1551                         }
1552                 }
1553
1554                 $list = $xpath->query('//meta[@property]');
1555
1556                 foreach ($list as $node) {
1557                         $attr = [];
1558                         if ($node->attributes->length) {
1559                                 foreach ($node->attributes as $attribute) {
1560                                         $value = trim($attribute->value);
1561                                         if (empty($value)) {
1562                                                 continue;
1563                                         }
1564
1565                                         $attr[$attribute->name] = $value;
1566                                 }
1567
1568                                 if (empty($attr['property']) || empty($attr['content'])) {
1569                                         continue;
1570                                 }
1571                         }
1572
1573                         if ($attr['property'] == 'og:site_name') {
1574                                 $serverdata['site_name'] = $attr['content'];
1575                         }
1576
1577                         if ($attr['property'] == 'og:description') {
1578                                 $serverdata['info'] = $attr['content'];
1579                         }
1580
1581                         if ($attr['property'] == 'og:platform') {
1582                                 $serverdata['platform'] = strtolower($attr['content']);
1583
1584                                 if (in_array($attr['content'], ['PeerTube'])) {
1585                                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1586                                 }
1587                         }
1588
1589                         if ($attr['property'] == 'generator') {
1590                                 $serverdata['platform'] = strtolower($attr['content']);
1591
1592                                 if (in_array($attr['content'], ['hubzilla'])) {
1593                                         // We later check which compatible protocol modules are loaded.
1594                                         $serverdata['network'] = Protocol::ZOT;
1595                                 }
1596                         }
1597                 }
1598
1599                 if (!empty($serverdata['network']) && ($serverdata['detection-method'] == self::DETECT_MANUAL)) {
1600                         $serverdata['detection-method'] = self::DETECT_BODY;
1601                 }
1602
1603                 return $serverdata;
1604         }
1605
1606         /**
1607          * Analyses the header data of a given server for hints about type and system of that server
1608          *
1609          * @param object $curlResult result of curl execution
1610          * @param array  $serverdata array with server data
1611          *
1612          * @return array server data
1613          */
1614         private static function analyseRootHeader($curlResult, array $serverdata)
1615         {
1616                 if ($curlResult->getHeader('server') == 'Mastodon') {
1617                         $serverdata['platform'] = 'mastodon';
1618                         $serverdata['network'] = Protocol::ACTIVITYPUB;
1619                 } elseif ($curlResult->inHeader('x-diaspora-version')) {
1620                         $serverdata['platform'] = 'diaspora';
1621                         $serverdata['network'] = Protocol::DIASPORA;
1622                         $serverdata['version'] = $curlResult->getHeader('x-diaspora-version');
1623                 } elseif ($curlResult->inHeader('x-friendica-version')) {
1624                         $serverdata['platform'] = 'friendica';
1625                         $serverdata['network'] = Protocol::DFRN;
1626                         $serverdata['version'] = $curlResult->getHeader('x-friendica-version');
1627                 } else {
1628                         return $serverdata;
1629                 }
1630
1631                 if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
1632                         $serverdata['detection-method'] = self::DETECT_HEADER;
1633                 }
1634
1635                 return $serverdata;
1636         }
1637
1638         /**
1639          * Test if the body contains valid content
1640          *
1641          * @param string $body
1642          * @return boolean
1643          */
1644         private static function invalidBody(string $body)
1645         {
1646                 // Currently we only test for a HTML element.
1647                 // Possibly we enhance this in the future.
1648                 return !strpos($body, '>');
1649         }
1650
1651         /**
1652          * Update GServer entries
1653          */
1654         public static function discover()
1655         {
1656                 // Update the server list
1657                 self::discoverFederation();
1658
1659                 $no_of_queries = 5;
1660
1661                 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
1662
1663                 if ($requery_days == 0) {
1664                         $requery_days = 7;
1665                 }
1666
1667                 $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
1668
1669                 $gservers = DBA::p("SELECT `id`, `url`, `nurl`, `network`, `poco`, `directory-type`
1670                         FROM `gserver`
1671                         WHERE NOT `failed`
1672                         AND `directory-type` != ?
1673                         AND `last_poco_query` < ?
1674                         ORDER BY RAND()", self::DT_NONE, $last_update
1675                 );
1676
1677                 while ($gserver = DBA::fetch($gservers)) {
1678                         Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1679                         Worker::add(PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
1680
1681                         Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
1682                         Worker::add(PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
1683
1684                         $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
1685                         DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);
1686         
1687                         if (--$no_of_queries == 0) {
1688                                 break;
1689                         }
1690                 }
1691
1692                 DBA::close($gservers);
1693         }
1694
1695         /**
1696          * Discover federated servers
1697          */
1698         private static function discoverFederation()
1699         {
1700                 $last = DI::config()->get('poco', 'last_federation_discovery');
1701
1702                 if ($last) {
1703                         $next = $last + (24 * 60 * 60);
1704
1705                         if ($next > time()) {
1706                                 return;
1707                         }
1708                 }
1709
1710                 // Discover federated servers
1711                 $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
1712                 foreach ($protocols as $protocol) {
1713                         $query = '{nodes(protocol:"' . $protocol . '"){host}}';
1714                         $curlResult = DI::httpRequest()->fetch('https://the-federation.info/graphql?query=' . urlencode($query));
1715                         if (!empty($curlResult)) {
1716                                 $data = json_decode($curlResult, true);
1717                                 if (!empty($data['data']['nodes'])) {
1718                                         foreach ($data['data']['nodes'] as $server) {
1719                                                 // Using "only_nodeinfo" since servers that are listed on that page should always have it.
1720                                                 self::add('https://' . $server['host'], true);
1721                                         }
1722                                 }
1723                         }
1724                 }
1725
1726                 // Disvover Mastodon servers
1727                 $accesstoken = DI::config()->get('system', 'instances_social_key');
1728
1729                 if (!empty($accesstoken)) {
1730                         $api = 'https://instances.social/api/1.0/instances/list?count=0';
1731                         $curlResult = DI::httpRequest()->get($api, ['header' => ['Authorization' => ['Bearer ' . $accesstoken]]]);
1732
1733                         if ($curlResult->isSuccess()) {
1734                                 $servers = json_decode($curlResult->getBody(), true);
1735
1736                                 foreach ($servers['instances'] as $server) {
1737                                         $url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
1738                                         self::add($url);
1739                                 }
1740                         }
1741                 }
1742
1743                 DI::config()->set('poco', 'last_federation_discovery', time());
1744         }
1745
1746         /**
1747          * Set the protocol for the given server
1748          *
1749          * @param int $gsid     Server id
1750          * @param int $protocol Protocol id
1751          * @return void
1752          * @throws Exception
1753          */
1754         public static function setProtocol(int $gsid, int $protocol)
1755         {
1756                 if (empty($gsid)) {
1757                         return;
1758                 }
1759
1760                 $gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
1761                 if (!DBA::isResult($gserver)) {
1762                         return;
1763                 }
1764
1765                 $old = $gserver['protocol'];
1766
1767                 if (!is_null($old)) {
1768                         /*
1769                         The priority for the protocols is:
1770                                 1. ActivityPub
1771                                 2. DFRN via Diaspora
1772                                 3. Legacy DFRN
1773                                 4. Diaspora
1774                                 5. OStatus
1775                         */
1776
1777                         // We don't need to change it when nothing is to be changed
1778                         if ($old == $protocol) {
1779                                 return;
1780                         }
1781
1782                         // We don't want to mark a server as OStatus when it had been marked with any other protocol before
1783                         if ($protocol == Post\DeliveryData::OSTATUS) {
1784                                 return;
1785                         }
1786
1787                         // If the server is marked as ActivityPub then we won't change it to anything different
1788                         if ($old == Post\DeliveryData::ACTIVITYPUB) {
1789                                 return;
1790                         }
1791
1792                         // Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
1793                         if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
1794                                 return;
1795                         }
1796
1797                         // Don't change it to Diaspora when it is a legacy DFRN server
1798                         if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
1799                                 return;
1800                         }
1801                 }
1802
1803                 Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url'], 'callstack' => System::callstack(20)]);
1804                 DBA::update('gserver', ['protocol' => $protocol], ['id' => $gsid]);
1805         }
1806
1807         /**
1808          * Fetch the protocol of the given server
1809          *
1810          * @param int $gsid Server id
1811          * @return int
1812          * @throws Exception
1813          */
1814         public static function getProtocol(int $gsid)
1815         {
1816                 if (empty($gsid)) {
1817                         return null;
1818                 }
1819
1820                 $gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
1821                 if (DBA::isResult($gserver)) {
1822                         return $gserver['protocol'];
1823                 }
1824
1825                 return null;
1826         }
1827 }