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