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