friendica/src/Model/GServer.php

2581 lines
80 KiB
PHP
Raw Normal View History

2019-10-03 09:20:36 +00:00
<?php
/**
2023-01-01 07:52:28 +00:00
* @copyright Copyright (C) 2010-2023, the Friendica project
2020-02-09 14:45:36 +00:00
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
2019-10-03 09:20:36 +00:00
*/
2020-02-09 14:45:36 +00:00
2019-10-03 09:20:36 +00:00
namespace Friendica\Model;
use DOMDocument;
use DOMXPath;
2021-01-09 19:18:22 +00:00
use Exception;
use Friendica\Core\Logger;
2019-10-03 09:20:36 +00:00
use Friendica\Core\Protocol;
use Friendica\Core\System;
2020-01-05 02:19:02 +00:00
use Friendica\Core\Worker;
2020-11-19 19:34:48 +00:00
use Friendica\Database\Database;
2019-10-03 09:20:36 +00:00
use Friendica\Database\DBA;
use Friendica\DI;
2019-10-03 09:20:36 +00:00
use Friendica\Module\Register;
use Friendica\Network\HTTPClient\Client\HttpClientAccept;
use Friendica\Network\HTTPClient\Client\HttpClientOptions;
use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses;
2022-07-05 05:04:05 +00:00
use Friendica\Network\Probe;
use Friendica\Protocol\ActivityPub;
use Friendica\Protocol\Relay;
2019-10-03 09:20:36 +00:00
use Friendica\Util\DateTimeFormat;
2022-07-05 05:04:05 +00:00
use Friendica\Util\JsonLD;
use Friendica\Util\Network;
2019-10-03 09:20:36 +00:00
use Friendica\Util\Strings;
use Friendica\Util\XML;
2022-07-05 05:04:05 +00:00
use Friendica\Network\HTTPException;
use Friendica\Worker\UpdateGServer;
2022-07-14 05:39:25 +00:00
use GuzzleHttp\Psr7\Uri;
use Psr\Http\Message\UriInterface;
2019-10-03 09:20:36 +00:00
/**
2019-10-04 17:29:21 +00:00
* This class handles GServer related functions
2019-10-03 09:20:36 +00:00
*/
class GServer
{
2019-12-21 13:48:20 +00:00
// Directory types
const DT_NONE = 0;
const DT_POCO = 1;
const DT_MASTODON = 2;
// Methods to detect server types
// Non endpoint specific methods
const DETECT_MANUAL = 0;
const DETECT_HEADER = 1;
const DETECT_BODY = 2;
2022-07-05 05:04:05 +00:00
const DETECT_HOST_META = 3;
const DETECT_CONTACTS = 4;
const DETECT_AP_ACTOR = 5;
const DETECT_AP_COLLECTION = 6;
const DETECT_UNSPECIFIC = [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META, self::DETECT_CONTACTS, self::DETECT_AP_ACTOR];
// Implementation specific endpoints
2022-11-29 18:45:30 +00:00
// @todo Possibly add Lemmy detection via the endpoint /api/v3/site
const DETECT_FRIENDIKA = 10;
const DETECT_FRIENDICA = 11;
const DETECT_STATUSNET = 12;
const DETECT_GNUSOCIAL = 13;
const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix
const DETECT_SITEINFO_JSON = 15; // Newer Hubzilla
const DETECT_MASTODON_API = 16;
const DETECT_STATUS_PHP = 17; // Nextcloud
const DETECT_V1_CONFIG = 18;
2022-07-05 05:04:05 +00:00
const DETECT_PUMPIO = 19; // Deprecated
const DETECT_SYSTEM_ACTOR = 20; // Mistpark, Osada, Roadhouse, Zap
// Standardized endpoints
const DETECT_STATISTICS_JSON = 100;
const DETECT_NODEINFO_1 = 101;
const DETECT_NODEINFO_2 = 102;
2022-07-05 05:04:05 +00:00
const DETECT_NODEINFO_210 = 103;
2020-12-03 22:32:51 +00:00
/**
* Check for the existence of a server and adds it in the background if not existant
2020-12-03 22:32:51 +00:00
*
* @param string $url
* @param boolean $only_nodeinfo
2022-07-17 05:42:44 +00:00
*
2020-12-03 22:32:51 +00:00
* @return void
*/
public static function add(string $url, bool $only_nodeinfo = false)
{
if (self::getID($url)) {
2020-12-03 22:32:51 +00:00
return;
}
UpdateGServer::add(Worker::PRIORITY_LOW, $url, $only_nodeinfo);
2020-12-03 22:32:51 +00:00
}
/**
* Get the ID for the given server URL
*
* @param string $url
* @param boolean $no_check Don't check if the server hadn't been found
2022-07-17 05:42:44 +00:00
*
* @return int|null gserver id or NULL on empty URL or failed check
*/
2022-07-17 05:42:44 +00:00
public static function getID(string $url, bool $no_check = false): ?int
{
$url = self::cleanURL($url);
if (empty($url)) {
return null;
}
$gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
if (DBA::isResult($gserver)) {
2022-07-05 05:04:05 +00:00
Logger::debug('Got ID for URL', ['id' => $gserver['id'], 'url' => $url, 'callstack' => System::callstack(20)]);
if (Network::isUrlBlocked($url)) {
self::setBlockedById($gserver['id']);
} else {
self::setUnblockedById($gserver['id']);
}
return $gserver['id'];
}
if ($no_check || !self::check($url)) {
return null;
}
return self::getID($url, true);
}
/**
* Retrieves all the servers which base domain are matching the provided domain pattern
*
* The pattern is a simple fnmatch() pattern with ? for single wildcard and * for multiple wildcard
*
* @param string $pattern
2022-07-17 05:42:44 +00:00
*
* @return array
2022-07-17 05:42:44 +00:00
*
* @throws Exception
*/
public static function listByDomainPattern(string $pattern): array
{
$likePattern = 'http://' . strtr($pattern, ['_' => '\_', '%' => '\%', '?' => '_', '*' => '%']);
// The SUBSTRING_INDEX returns everything before the eventual third /, which effectively trims an
// eventual server path and keep only the server domain which we're matching against the pattern.
$sql = "SELECT `gserver`.*, COUNT(*) AS `contacts`
FROM `gserver`
LEFT JOIN `contact` ON `gserver`.`id` = `contact`.`gsid`
WHERE SUBSTRING_INDEX(`gserver`.`nurl`, '/', 3) LIKE ?
AND NOT `gserver`.`failed`
GROUP BY `gserver`.`id`";
$stmt = DI::dba()->p($sql, $likePattern);
return DI::dba()->toArray($stmt);
}
2022-12-31 16:01:40 +00:00
/**
* Checks if the given server array is unreachable for a long time now
*
* @param integer $gsid
* @return boolean
*/
2022-12-31 16:20:18 +00:00
private static function isDefunct(array $gserver): bool
2022-12-31 16:01:40 +00:00
{
return ($gserver['failed'] || in_array($gserver['network'], Protocol::FEDERATED)) &&
($gserver['last_contact'] >= $gserver['created']) &&
($gserver['last_contact'] < $gserver['last_failure']) &&
($gserver['last_contact'] < DateTimeFormat::utc('now - 90 days'));
}
/**
* Checks if the given server id is unreachable for a long time now
*
* @param integer $gsid
* @return boolean
*/
2022-12-31 16:20:18 +00:00
public static function isDefunctById(int $gsid): bool
2022-12-31 16:01:40 +00:00
{
$gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'last_contact', 'last_failure', 'created', 'failed', 'network'], ['id' => $gsid]);
if (empty($gserver)) {
return false;
} else {
if (strtotime($gserver['next_contact']) < time()) {
UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
2022-12-31 16:01:40 +00:00
}
2022-12-31 16:20:18 +00:00
return self::isDefunct($gserver);
2022-12-31 16:01:40 +00:00
}
}
2022-12-31 12:19:34 +00:00
/**
* Checks if the given server id is reachable
*
* @param integer $gsid
* @return boolean
*/
2022-12-31 16:20:18 +00:00
public static function isReachableById(int $gsid): bool
2022-12-31 12:19:34 +00:00
{
$gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'failed', 'network'], ['id' => $gsid]);
if (empty($gserver)) {
return true;
} else {
if (strtotime($gserver['next_contact']) < time()) {
UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
2022-12-31 12:19:34 +00:00
}
2022-12-31 12:19:34 +00:00
return !$gserver['failed'] && in_array($gserver['network'], Protocol::FEDERATED);
}
}
/**
* Checks if the given server is reachable
*
* @param array $contact Contact that should be checked
*
* @return boolean 'true' if server seems vital
*/
public static function reachable(array $contact): bool
{
if (!empty($contact['gsid'])) {
$gsid = $contact['gsid'];
} elseif (!empty($contact['baseurl'])) {
$server = $contact['baseurl'];
} elseif ($contact['network'] == Protocol::DIASPORA) {
$parts = parse_url($contact['url']);
unset($parts['path']);
$server = (string)Uri::fromParts($parts);
} else {
return true;
}
if (!empty($gsid)) {
$condition = ['id' => $gsid];
} else {
$condition = ['nurl' => Strings::normaliseLink($server)];
}
$gserver = DBA::selectFirst('gserver', ['url', 'next_contact', 'failed', 'network'], $condition);
if (empty($gserver)) {
$reachable = true;
} else {
$reachable = !$gserver['failed'] && in_array($gserver['network'], Protocol::FEDERATED);
$server = $gserver['url'];
}
if (!empty($server) && (empty($gserver) || strtotime($gserver['next_contact']) < time())) {
UpdateGServer::add(Worker::PRIORITY_LOW, $server);
}
return $reachable;
}
2022-07-17 05:42:44 +00:00
/**
* Calculate the next update day
*
* @param bool $success
* @param string $created
* @param string $last_contact
* @param bool $undetected
*
* @return string
*
* @throws Exception
*/
public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '', bool $undetected = false): string
2020-12-03 15:47:50 +00:00
{
2022-07-10 13:01:47 +00:00
// On successful contact process check again next week when it is a detected system.
// When we haven't detected the system, it could be a static website or a really old system.
2020-12-03 15:47:50 +00:00
if ($success) {
2022-07-10 13:01:47 +00:00
return DateTimeFormat::utc($undetected ? 'now +1 month' : 'now +7 day');
2020-12-03 15:47:50 +00:00
}
$now = strtotime(DateTimeFormat::utcNow());
if ($created > $last_contact) {
$contact_time = strtotime($created);
} else {
$contact_time = strtotime($last_contact);
}
// If the last contact was less than 6 hours before then try again in 6 hours
if (($now - $contact_time) < (60 * 60 * 6)) {
return DateTimeFormat::utc('now +6 hour');
}
// If the last contact was less than 12 hours before then try again in 12 hours
if (($now - $contact_time) < (60 * 60 * 12)) {
return DateTimeFormat::utc('now +12 hour');
}
// If the last contact was less than 24 hours before then try tomorrow again
if (($now - $contact_time) < (60 * 60 * 24)) {
return DateTimeFormat::utc('now +1 day');
}
2020-12-03 15:47:50 +00:00
// If the last contact was less than a week before then try again in a week
if (($now - $contact_time) < (60 * 60 * 24 * 7)) {
return DateTimeFormat::utc('now +1 week');
}
// If the last contact was less than two weeks before then try again in two week
if (($now - $contact_time) < (60 * 60 * 24 * 14)) {
return DateTimeFormat::utc('now +2 week');
}
// If the last contact was less than a month before then try again in a month
if (($now - $contact_time) < (60 * 60 * 24 * 30)) {
return DateTimeFormat::utc('now +1 month');
}
// The system hadn't been successful contacted for more than a month, so try again in three months
2020-12-03 15:47:50 +00:00
return DateTimeFormat::utc('now +3 month');
}
2019-10-04 17:29:21 +00:00
/**
* Checks the state of the given server.
*
* @param string $server_url URL of the given server
* @param string $network Network value that is used, when detection failed
* @param boolean $force Force an update.
* @param boolean $only_nodeinfo Only use nodeinfo for server detection
2019-10-04 17:29:21 +00:00
*
2019-10-05 04:22:16 +00:00
* @return boolean 'true' if server seems vital
2019-10-04 17:29:21 +00:00
*/
public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false): bool
{
$server_url = self::cleanURL($server_url);
if ($server_url == '') {
return false;
}
if (Network::isUrlBlocked($server_url)) {
Logger::info('Server is blocked', ['url' => $server_url]);
self::setBlockedByUrl($server_url);
return false;
}
$gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]);
if (DBA::isResult($gserver)) {
if ($gserver['created'] <= DBA::NULL_DATETIME) {
$fields = ['created' => DateTimeFormat::utcNow()];
$condition = ['nurl' => Strings::normaliseLink($server_url)];
self::update($fields, $condition);
}
2020-12-03 22:32:51 +00:00
if (!$force && (strtotime($gserver['next_contact']) > time())) {
2019-10-04 05:42:54 +00:00
Logger::info('No update needed', ['server' => $server_url]);
2020-12-03 22:32:51 +00:00
return (!$gserver['failed']);
}
2020-12-03 22:32:51 +00:00
Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]);
2019-10-04 05:42:54 +00:00
} else {
Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]);
}
return self::detect($server_url, $network, $only_nodeinfo);
}
2022-12-31 12:19:34 +00:00
/**
* Reset failed server status by gserver id
*
* @param int $gsid
* @param string $network
2022-12-31 12:19:34 +00:00
*/
public static function setReachableById(int $gsid, string $network)
2022-12-31 12:19:34 +00:00
{
$gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact', 'network'], ['id' => $gsid]);
if (!DBA::isResult($gserver)) {
return;
}
$blocked = Network::isUrlBlocked($gserver['url']);
if ($gserver['failed']) {
$fields = ['failed' => false, 'blocked' => $blocked, 'last_contact' => DateTimeFormat::utcNow()];
if (!empty($network) && !in_array($gserver['network'], Protocol::FEDERATED)) {
$fields['network'] = $network;
}
self::update($fields, ['id' => $gsid]);
2022-12-31 12:19:34 +00:00
Logger::info('Reset failed status for server', ['url' => $gserver['url']]);
if (strtotime($gserver['next_contact']) < time()) {
UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
2022-12-31 12:19:34 +00:00
}
} elseif ($blocked) {
self::setBlockedById($gsid);
} else {
self::setUnblockedById($gsid);
2022-12-31 12:19:34 +00:00
}
}
/**
* Set failed server status by gserver id
*
* @param int $gsid
*/
public static function setFailureById(int $gsid)
{
$gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact'], ['id' => $gsid]);
if (DBA::isResult($gserver) && !$gserver['failed']) {
self::update(['failed' => true, 'blocked' => Network::isUrlBlocked($gserver['url']), 'last_failure' => DateTimeFormat::utcNow()], ['id' => $gsid]);
2022-12-31 12:19:34 +00:00
Logger::info('Set failed status for server', ['url' => $gserver['url']]);
if (strtotime($gserver['next_contact']) < time()) {
UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
2022-12-31 12:19:34 +00:00
}
}
}
public static function setUnblockedById(int $gsid)
{
$gserver = DBA::selectFirst('gserver', ['url'], ["(`blocked` OR `blocked` IS NULL) AND `id` = ?", $gsid]);
if (DBA::isResult($gserver)) {
self::update(['blocked' => false], ['id' => $gsid]);
Logger::info('Set unblocked status for server', ['url' => $gserver['url']]);
}
}
public static function setBlockedById(int $gsid)
{
$gserver = DBA::selectFirst('gserver', ['url'], ["(NOT `blocked` OR `blocked` IS NULL) AND `id` = ?", $gsid]);
if (DBA::isResult($gserver)) {
self::update(['blocked' => true, 'failed' => true], ['id' => $gsid]);
Logger::info('Set blocked status for server', ['url' => $gserver['url']]);
}
}
public static function setBlockedByUrl(string $url)
{
$gserver = DBA::selectFirst('gserver', ['url', 'id'], ["(NOT `blocked` OR `blocked` IS NULL) AND `nurl` = ?", Strings::normaliseLink($url)]);
if (DBA::isResult($gserver)) {
self::update(['blocked' => true, 'failed' => true], ['id' => $gserver['id']]);
Logger::info('Set blocked status for server', ['url' => $gserver['url']]);
}
}
/**
* Set failed server status
*
* @param string $url
* @return void
*/
2022-12-31 16:20:18 +00:00
public static function setFailureByUrl(string $url)
{
$nurl = Strings::normaliseLink($url);
$gserver = DBA::selectFirst('gserver', [], ['nurl' => $nurl]);
2020-12-03 15:47:50 +00:00
if (DBA::isResult($gserver)) {
$next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
self::update(['url' => $url, 'failed' => true, 'blocked' => Network::isUrlBlocked($url), 'last_failure' => DateTimeFormat::utcNow(),
2022-07-05 05:04:05 +00:00
'next_contact' => $next_update, 'network' => Protocol::PHANTOM, 'detection-method' => null],
['nurl' => $nurl]);
Logger::info('Set failed status for existing server', ['url' => $url]);
2022-12-31 16:20:18 +00:00
if (self::isDefunct($gserver)) {
self::archiveContacts($gserver['id']);
2022-12-31 16:01:40 +00:00
}
return;
}
self::insert(['url' => $url, 'nurl' => $nurl,
'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
Logger::info('Set failed status for new server', ['url' => $url]);
}
/**
* Archive server related contacts and inboxes
*
* @param integer $gsid
* @return void
*/
private static function archiveContacts(int $gsid)
{
Contact::update(['archive' => true], ['gsid' => $gsid]);
DBA::update('inbox-status', ['archive' => true], ['gsid' => $gsid]);
}
2020-05-22 04:52:43 +00:00
/**
* Remove unwanted content from the given URL
*
* @param string $dirtyUrl
2022-07-17 05:42:44 +00:00
*
2020-05-22 04:52:43 +00:00
* @return string cleaned URL
* @throws Exception
* @deprecated since 2023.03 Use cleanUri instead
2020-05-22 04:52:43 +00:00
*/
public static function cleanURL(string $dirtyUrl): string
{
try {
return (string)self::cleanUri(new Uri($dirtyUrl));
} catch (\Throwable $e) {
Logger::warning('Invalid URL', ['dirtyUrl' => $dirtyUrl]);
return '';
}
}
/**
* Remove unwanted content from the given URI
*
* @param UriInterface $dirtyUri
*
* @return UriInterface cleaned URI
* @throws Exception
*/
public static function cleanUri(UriInterface $dirtyUri): string
{
return $dirtyUri
->withUserInfo('')
->withQuery('')
->withFragment('')
->withPath(
preg_replace(
'#(?:^|/)index\.php#',
'',
rtrim($dirtyUri->getPath(), '/')
)
);
}
2019-10-03 09:20:36 +00:00
/**
2019-10-03 14:48:46 +00:00
* Detect server data (type, protocol, version number, ...)
* The detected data is then updated or inserted in the gserver table.
2019-10-03 09:20:36 +00:00
*
* @param string $url URL of the given server
* @param string $network Network value that is used, when detection failed
* @param boolean $only_nodeinfo Only use nodeinfo for server detection
2019-10-03 09:20:36 +00:00
*
* @return boolean 'true' if server could be detected
*/
private static function detect(string $url, string $network = '', bool $only_nodeinfo = false): bool
2019-10-03 09:20:36 +00:00
{
2019-12-21 13:48:20 +00:00
Logger::info('Detect server type', ['server' => $url]);
2019-10-03 09:20:36 +00:00
2019-12-21 13:48:20 +00:00
$original_url = $url;
// Remove URL content that is not supposed to exist for a server url
2022-07-05 05:04:05 +00:00
$url = rtrim(self::cleanURL($url), '/');
2022-07-10 13:01:47 +00:00
if (empty($url)) {
Logger::notice('Empty URL.');
return false;
}
// If the URL mismatches, then we mark the old entry as failure
2022-07-14 05:39:25 +00:00
if (!Strings::compareLink($url, $original_url)) {
2022-12-31 16:20:18 +00:00
self::setFailureByUrl($original_url);
2023-01-22 12:33:38 +00:00
if (!self::getID($url, true) && !Network::isUrlBlocked($url)) {
2022-07-14 05:39:25 +00:00
self::detect($url, $network, $only_nodeinfo);
}
2022-07-05 05:04:05 +00:00
return false;
2019-12-21 13:48:20 +00:00
}
2022-07-14 05:39:25 +00:00
$valid_url = Network::isUrlValid($url);
if (!$valid_url) {
2022-12-31 16:20:18 +00:00
self::setFailureByUrl($url);
2019-10-03 09:20:36 +00:00
return false;
2022-07-14 05:39:25 +00:00
} else {
$valid_url = rtrim($valid_url, '/');
2019-10-03 09:20:36 +00:00
}
2022-07-14 05:39:25 +00:00
if (!Strings::compareLink($url, $valid_url)) {
// We only follow redirects when the path stays the same or the target url has no path.
// Some systems have got redirects on their landing page to a single account page. This check handles it.
if (((parse_url($url, PHP_URL_HOST) != parse_url($valid_url, PHP_URL_HOST)) && (parse_url($url, PHP_URL_PATH) == parse_url($valid_url, PHP_URL_PATH))) ||
(((parse_url($url, PHP_URL_HOST) != parse_url($valid_url, PHP_URL_HOST)) || (parse_url($url, PHP_URL_PATH) != parse_url($valid_url, PHP_URL_PATH))) && empty(parse_url($valid_url, PHP_URL_PATH)))) {
Logger::debug('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $valid_url]);
2022-12-31 16:20:18 +00:00
self::setFailureByUrl($url);
2023-01-22 12:33:38 +00:00
if (!self::getID($valid_url, true) && !Network::isUrlBlocked($valid_url)) {
2022-07-14 05:39:25 +00:00
self::detect($valid_url, $network, $only_nodeinfo);
}
return false;
}
2022-07-10 13:01:47 +00:00
2022-07-14 05:39:25 +00:00
if ((parse_url($url, PHP_URL_HOST) != parse_url($valid_url, PHP_URL_HOST)) && (parse_url($url, PHP_URL_PATH) != parse_url($valid_url, PHP_URL_PATH)) &&
(parse_url($url, PHP_URL_PATH) == '')) {
Logger::debug('Found redirect. Mark old entry as failure and redirect to the basepath.', ['old' => $url, 'new' => $valid_url]);
$parts = parse_url($valid_url);
unset($parts['path']);
$valid_url = (string)Uri::fromParts($parts);
2022-12-31 16:20:18 +00:00
self::setFailureByUrl($url);
2023-01-22 12:33:38 +00:00
if (!self::getID($valid_url, true) && !Network::isUrlBlocked($valid_url)) {
2022-07-14 05:39:25 +00:00
self::detect($valid_url, $network, $only_nodeinfo);
}
2022-07-17 05:42:44 +00:00
return false;
2022-07-14 05:39:25 +00:00
}
Logger::debug('Found redirect, but ignore it.', ['old' => $url, 'new' => $valid_url]);
2022-07-05 05:04:05 +00:00
}
2022-07-14 05:39:25 +00:00
if ((parse_url($url, PHP_URL_HOST) == parse_url($valid_url, PHP_URL_HOST)) &&
(parse_url($url, PHP_URL_PATH) == parse_url($valid_url, PHP_URL_PATH)) &&
(parse_url($url, PHP_URL_SCHEME) != parse_url($valid_url, PHP_URL_SCHEME))) {
$url = $valid_url;
}
2022-07-05 05:04:05 +00:00
$in_webroot = empty(parse_url($url, PHP_URL_PATH));
// When a nodeinfo is present, we don't need to dig further
$curlResult = DI::httpClient()->get($url . '/.well-known/x-nodeinfo2', HttpClientAccept::JSON);
if ($curlResult->isTimeout()) {
2022-12-31 16:20:18 +00:00
self::setFailureByUrl($url);
return false;
}
2019-10-03 09:20:36 +00:00
2022-07-05 05:04:05 +00:00
$serverdata = self::parseNodeinfo210($curlResult);
if (empty($serverdata)) {
$curlResult = DI::httpClient()->get($url . '/.well-known/nodeinfo', HttpClientAccept::JSON);
$serverdata = self::fetchNodeinfo($url, $curlResult);
2019-10-03 13:02:48 +00:00
}
2022-07-05 05:04:05 +00:00
if ($only_nodeinfo && empty($serverdata)) {
Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
2022-12-31 16:20:18 +00:00
self::setFailureByUrl($url);
2022-07-05 05:04:05 +00:00
return false;
} elseif (empty($serverdata)) {
$serverdata = ['detection-method' => self::DETECT_MANUAL, 'network' => Protocol::PHANTOM, 'platform' => '', 'version' => '', 'site_name' => '', 'info' => ''];
}
// When there is no Nodeinfo, then use some protocol specific endpoints
if ($serverdata['network'] == Protocol::PHANTOM) {
if ($in_webroot) {
// Fetch the landing page, possibly it reveals some data
$accept = 'application/activity+json,application/ld+json,application/json,*/*;q=0.9';
$curlResult = DI::httpClient()->get($url, $accept);
if (!$curlResult->isSuccess() && $curlResult->getReturnCode() == '406') {
$curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
$html_fetched = true;
} else {
2022-07-05 05:04:05 +00:00
$html_fetched = false;
}
if ($curlResult->isSuccess()) {
2022-07-05 05:04:05 +00:00
$json = json_decode($curlResult->getBody(), true);
2022-07-10 13:01:47 +00:00
if (!empty($json) && is_array($json)) {
2022-07-05 05:04:05 +00:00
$data = self::fetchDataFromSystemActor($json, $serverdata);
$serverdata = $data['server'];
$systemactor = $data['actor'];
2022-07-10 13:01:47 +00:00
if (!$html_fetched && !in_array($serverdata['detection-method'], [self::DETECT_SYSTEM_ACTOR, self::DETECT_AP_COLLECTION])) {
2022-07-05 05:04:05 +00:00
$curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
}
} elseif (!$html_fetched && (strlen($curlResult->getBody()) < 1000)) {
$curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML);
}
2022-07-05 05:04:05 +00:00
if ($serverdata['detection-method'] != self::DETECT_SYSTEM_ACTOR) {
$serverdata = self::analyseRootHeader($curlResult, $serverdata);
$serverdata = self::analyseRootBody($curlResult, $serverdata);
}
}
2022-07-05 05:04:05 +00:00
if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
2022-12-31 16:20:18 +00:00
self::setFailureByUrl($url);
return false;
}
2022-07-05 05:04:05 +00:00
if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
$serverdata = self::detectMastodonAlikes($url, $serverdata);
}
}
// All following checks are done for systems that always have got a "host-meta" endpoint.
// With this check we don't have to waste time and resources for dead systems.
// Also this hopefully prevents us from receiving abuse messages.
2022-07-05 05:04:05 +00:00
if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
$validHostMeta = self::validHostMeta($url);
} else {
$validHostMeta = false;
2022-03-28 10:33:06 +00:00
}
2022-07-05 05:04:05 +00:00
if ($validHostMeta) {
2022-07-10 13:01:47 +00:00
if (in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY])) {
2022-07-05 05:04:05 +00:00
$serverdata['detection-method'] = self::DETECT_HOST_META;
}
2019-10-03 09:20:36 +00:00
2022-07-05 05:04:05 +00:00
if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
$serverdata = self::detectFriendica($url, $serverdata);
}
2019-10-03 09:20:36 +00:00
2022-07-05 05:04:05 +00:00
// The following systems have to be installed in the root directory.
if ($in_webroot) {
// the 'siteinfo.json' is some specific endpoint of Hubzilla and Red
if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
$serverdata = self::fetchSiteinfo($url, $serverdata);
}
2019-10-03 09:20:36 +00:00
2022-07-05 05:04:05 +00:00
// The 'siteinfo.json' doesn't seem to be present on older Hubzilla installations, so we check other endpoints as well
if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
$serverdata = self::detectHubzilla($url, $serverdata);
}
2019-10-03 13:02:48 +00:00
2022-07-05 05:04:05 +00:00
if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
$serverdata = self::detectPeertube($url, $serverdata);
}
2022-07-05 05:04:05 +00:00
if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
$serverdata = self::detectGNUSocial($url, $serverdata);
}
}
} elseif (in_array($serverdata['platform'], ['friendica', 'friendika']) && in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_SYSTEM_ACTOR]))) {
2022-07-10 13:01:47 +00:00
$serverdata = self::detectFriendica($url, $serverdata);
2019-10-03 09:20:36 +00:00
}
2022-07-05 05:04:05 +00:00
if (($serverdata['network'] == Protocol::PHANTOM) || in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
$serverdata = self::detectNextcloud($url, $serverdata, $validHostMeta);
2019-10-03 09:20:36 +00:00
}
2022-07-05 05:04:05 +00:00
// When nodeinfo isn't present, we use the older 'statistics.json' endpoint
// Since this endpoint is only rarely used, we query it at a later time
if (in_array($serverdata['detection-method'], array_merge(self::DETECT_UNSPECIFIC, [self::DETECT_FRIENDICA, self::DETECT_CONFIG_JSON]))) {
$serverdata = self::fetchStatistics($url, $serverdata);
2022-02-05 11:25:06 +00:00
}
2019-10-03 09:20:36 +00:00
}
2019-10-04 06:33:16 +00:00
// When we hadn't been able to detect the network type, we use the hint from the parameter
if (($serverdata['network'] == Protocol::PHANTOM) && !empty($network)) {
$serverdata['network'] = $network;
}
2022-07-05 05:04:05 +00:00
// Most servers aren't installed in a subdirectory, so we declare this entry as failed
if (($serverdata['network'] == Protocol::PHANTOM) && !empty(parse_url($url, PHP_URL_PATH)) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL])) {
2022-12-31 16:20:18 +00:00
self::setFailureByUrl($url);
2022-07-05 05:04:05 +00:00
return false;
}
2019-10-03 09:20:36 +00:00
$serverdata['url'] = $url;
$serverdata['nurl'] = Strings::normaliseLink($url);
2022-07-05 05:04:05 +00:00
// We have to prevent an endless loop here.
// When a server is new, then there is no gserver entry yet.
// But in "detectNetworkViaContacts" it could happen that a contact is updated,
// and this can call this function here as well.
2022-07-10 13:01:47 +00:00
if (self::getID($url, true) && (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) ||
in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META]))) {
2019-10-04 06:33:16 +00:00
$serverdata = self::detectNetworkViaContacts($url, $serverdata);
}
2019-10-03 15:30:07 +00:00
2022-12-31 16:01:40 +00:00
if (($serverdata['network'] == Protocol::PHANTOM) && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_BODY])) {
2022-12-31 16:20:18 +00:00
self::setFailureByUrl($url);
2022-12-31 16:01:40 +00:00
return false;
}
if (empty($serverdata['version']) && in_array($serverdata['platform'], ['osada']) && in_array($serverdata['detection-method'], [self::DETECT_CONTACTS, self::DETECT_BODY])) {
$serverdata['version'] = self::getNomadVersion($url);
}
2022-07-05 05:04:05 +00:00
// Detect the directory type
$serverdata['directory-type'] = self::DT_NONE;
if (in_array($serverdata['network'], Protocol::FEDERATED)) {
$serverdata = self::checkMastodonDirectory($url, $serverdata);
if ($serverdata['directory-type'] == self::DT_NONE) {
$serverdata = self::checkPoCo($url, $serverdata);
}
}
if ($serverdata['network'] == Protocol::ACTIVITYPUB) {
$serverdata = self::fetchWeeklyUsage($url, $serverdata);
}
$serverdata['registered-users'] = $serverdata['registered-users'] ?? 0;
// Numbers above a reasonable value (10 millions) are ignored
if ($serverdata['registered-users'] > 10000000) {
$serverdata['registered-users'] = 0;
}
// On an active server there has to be at least a single user
if (!in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]) && ($serverdata['registered-users'] <= 0)) {
$serverdata['registered-users'] = 1;
} elseif (in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
$serverdata['registered-users'] = 0;
}
2022-07-10 13:01:47 +00:00
$serverdata['next_contact'] = self::getNextUpdateDate(true, '', '', in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED]));
2019-10-03 14:48:46 +00:00
$serverdata['last_contact'] = DateTimeFormat::utcNow();
$serverdata['failed'] = false;
$serverdata['blocked'] = false;
2019-10-03 14:48:46 +00:00
2019-10-04 06:33:16 +00:00
$gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
if (!DBA::isResult($gserver)) {
2019-10-03 09:20:36 +00:00
$serverdata['created'] = DateTimeFormat::utcNow();
2022-08-28 19:27:21 +00:00
$ret = self::insert($serverdata);
$id = DBA::lastInsertId();
2019-10-03 09:20:36 +00:00
} else {
$ret = self::update($serverdata, ['nurl' => $serverdata['nurl']]);
$gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]);
if (DBA::isResult($gserver)) {
$id = $gserver['id'];
}
}
// Count the number of known contacts from this server
if (!empty($id) && !in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) {
$apcontacts = DBA::count('apcontact', ['gsid' => $id]);
$contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]);
$max_users = max($apcontacts, $contacts);
if ($max_users > $serverdata['registered-users']) {
Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
self::update(['registered-users' => $max_users], ['id' => $id]);
}
if (empty($serverdata['active-month-users'])) {
$contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 30 days')]);
if ($contacts > 0) {
Logger::info('Update monthly users', ['id' => $id, 'url' => $serverdata['nurl'], 'monthly-users' => $contacts]);
self::update(['active-month-users' => $contacts], ['id' => $id]);
}
}
2022-07-05 05:04:05 +00:00
if (empty($serverdata['active-halfyear-users'])) {
$contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 180 days')]);
if ($contacts > 0) {
Logger::info('Update halfyear users', ['id' => $id, 'url' => $serverdata['nurl'], 'halfyear-users' => $contacts]);
self::update(['active-halfyear-users' => $contacts], ['id' => $id]);
}
}
2019-10-03 09:20:36 +00:00
}
2022-07-05 05:04:05 +00:00
if (in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
self::discoverRelay($url);
}
2022-07-05 05:04:05 +00:00
if (!empty($systemactor)) {
$contact = Contact::getByURL($systemactor, true, ['gsid', 'baseurl', 'id', 'network', 'url', 'name']);
Logger::debug('Fetched system actor', ['url' => $url, 'gsid' => $id, 'contact' => $contact]);
}
2019-10-03 14:48:46 +00:00
return $ret;
2019-10-03 09:20:36 +00:00
}
/**
2019-10-04 17:29:21 +00:00
* Fetch relay data from a given server url
*
* @param string $server_url address of the server
2022-07-17 05:42:44 +00:00
*
* @return void
2022-07-17 05:42:44 +00:00
*
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
2020-05-17 13:59:05 +00:00
private static function discoverRelay(string $server_url)
{
Logger::info('Discover relay data', ['server' => $server_url]);
$curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay', HttpClientAccept::JSON);
if (!$curlResult->isSuccess()) {
return;
}
$data = json_decode($curlResult->getBody(), true);
if (!is_array($data)) {
return;
}
// Sanitize incoming data, see https://github.com/friendica/friendica/issues/8565
$data['subscribe'] = (bool)($data['subscribe'] ?? false);
if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) {
$data['scope'] = '';
$data['subscribe'] = false;
$data['tags'] = [];
}
$gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]);
if (!DBA::isResult($gserver)) {
return;
}
if (($gserver['relay-subscribe'] != $data['subscribe']) || ($gserver['relay-scope'] != $data['scope'])) {
$fields = ['relay-subscribe' => $data['subscribe'], 'relay-scope' => $data['scope']];
self::update($fields, ['id' => $gserver['id']]);
}
DBA::delete('gserver-tag', ['gserver-id' => $gserver['id']]);
if ($data['scope'] == 'tags') {
// Avoid duplicates
$tags = [];
foreach ($data['tags'] as $tag) {
$tag = mb_strtolower($tag);
if (strlen($tag) < 100) {
$tags[$tag] = $tag;
}
}
foreach ($tags as $tag) {
2020-11-19 19:34:48 +00:00
DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], Database::INSERT_IGNORE);
}
}
// Create or update the relay contact
$fields = [];
if (isset($data['protocols'])) {
if (isset($data['protocols']['diaspora'])) {
$fields['network'] = Protocol::DIASPORA;
if (isset($data['protocols']['diaspora']['receive'])) {
$fields['batch'] = $data['protocols']['diaspora']['receive'];
} elseif (is_string($data['protocols']['diaspora'])) {
$fields['batch'] = $data['protocols']['diaspora'];
}
}
if (isset($data['protocols']['dfrn'])) {
$fields['network'] = Protocol::DFRN;
if (isset($data['protocols']['dfrn']['receive'])) {
$fields['batch'] = $data['protocols']['dfrn']['receive'];
} elseif (is_string($data['protocols']['dfrn'])) {
$fields['batch'] = $data['protocols']['dfrn'];
}
}
if (isset($data['protocols']['activitypub'])) {
$fields['network'] = Protocol::ACTIVITYPUB;
if (!empty($data['protocols']['activitypub']['actor'])) {
$fields['url'] = $data['protocols']['activitypub']['actor'];
}
if (!empty($data['protocols']['activitypub']['receive'])) {
$fields['batch'] = $data['protocols']['activitypub']['receive'];
}
}
}
Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
Relay::updateContact($gserver, $fields);
}
2019-10-04 17:29:21 +00:00
/**
* Fetch server data from '/statistics.json' on the given server
*
* @param string $url URL of the given server
2022-07-17 05:42:44 +00:00
*
2019-10-04 17:29:21 +00:00
* @return array server data
*/
2022-07-17 05:42:44 +00:00
private static function fetchStatistics(string $url, array $serverdata): array
2019-10-03 13:02:48 +00:00
{
$curlResult = DI::httpClient()->get($url . '/statistics.json', HttpClientAccept::JSON);
2019-10-03 13:02:48 +00:00
if (!$curlResult->isSuccess()) {
2022-07-05 05:04:05 +00:00
return $serverdata;
2019-10-03 13:02:48 +00:00
}
$data = json_decode($curlResult->getBody(), true);
if (empty($data)) {
2022-07-05 05:04:05 +00:00
return $serverdata;
2019-10-03 13:02:48 +00:00
}
2022-07-05 05:04:05 +00:00
// Some AP enabled systems return activity data that we don't expect here.
if (strpos($curlResult->getContentType(), 'application/activity+json') !== false) {
return $serverdata;
}
$valid = false;
$old_serverdata = $serverdata;
$serverdata['detection-method'] = self::DETECT_STATISTICS_JSON;
2019-10-03 13:02:48 +00:00
if (!empty($data['version'])) {
2022-07-05 05:04:05 +00:00
$valid = true;
2019-10-03 13:02:48 +00:00
$serverdata['version'] = $data['version'];
// Version numbers on statistics.json are presented with additional info, e.g.:
// 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
$serverdata['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $serverdata['version']);
}
if (!empty($data['name'])) {
2022-07-05 05:04:05 +00:00
$valid = true;
2019-10-03 13:02:48 +00:00
$serverdata['site_name'] = $data['name'];
}
if (!empty($data['network'])) {
2022-07-05 05:04:05 +00:00
$valid = true;
2020-01-12 21:07:40 +00:00
$serverdata['platform'] = strtolower($data['network']);
2019-10-03 13:02:48 +00:00
2020-01-12 21:07:40 +00:00
if ($serverdata['platform'] == 'diaspora') {
2019-10-03 13:02:48 +00:00
$serverdata['network'] = Protocol::DIASPORA;
2020-01-12 21:07:40 +00:00
} elseif ($serverdata['platform'] == 'friendica') {
2019-10-03 13:02:48 +00:00
$serverdata['network'] = Protocol::DFRN;
2019-10-03 14:48:46 +00:00
} elseif ($serverdata['platform'] == 'hubzilla') {
$serverdata['network'] = Protocol::ZOT;
2019-10-03 13:02:48 +00:00
} elseif ($serverdata['platform'] == 'redmatrix') {
$serverdata['network'] = Protocol::ZOT;
}
}
if (!empty($data['total_users'])) {
2022-07-05 05:04:05 +00:00
$valid = true;
$serverdata['registered-users'] = max($data['total_users'], 1);
}
if (!empty($data['active_users_monthly'])) {
2022-07-05 05:04:05 +00:00
$valid = true;
$serverdata['active-month-users'] = max($data['active_users_monthly'], 0);
}
if (!empty($data['active_users_halfyear'])) {
2022-07-05 05:04:05 +00:00
$valid = true;
$serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0);
}
if (!empty($data['local_posts'])) {
2022-07-05 05:04:05 +00:00
$valid = true;
$serverdata['local-posts'] = max($data['local_posts'], 0);
}
2019-10-03 13:02:48 +00:00
if (!empty($data['registrations_open'])) {
$serverdata['register_policy'] = Register::OPEN;
} else {
$serverdata['register_policy'] = Register::CLOSED;
}
2022-07-05 05:04:05 +00:00
if (!$valid) {
return $old_serverdata;
}
2019-10-03 13:02:48 +00:00
return $serverdata;
}
2019-10-03 09:20:36 +00:00
/**
2019-10-04 17:29:21 +00:00
* Detect server type by using the nodeinfo data
2019-10-03 09:20:36 +00:00
*
* @param string $url address of the server
* @param ICanHandleHttpResponses $httpResult
*
2019-10-03 09:20:36 +00:00
* @return array Server data
2022-07-17 05:42:44 +00:00
*
2019-10-03 09:20:36 +00:00
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult): array
2019-10-03 09:20:36 +00:00
{
if (!$httpResult->isSuccess()) {
return [];
}
$nodeinfo = json_decode($httpResult->getBody(), true);
2019-10-03 09:20:36 +00:00
2019-10-03 14:48:46 +00:00
if (!is_array($nodeinfo) || empty($nodeinfo['links'])) {
2019-10-03 09:20:36 +00:00
return [];
}
$nodeinfo1_url = '';
$nodeinfo2_url = '';
foreach ($nodeinfo['links'] as $link) {
if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
Logger::info('Invalid nodeinfo format', ['url' => $url]);
continue;
}
2019-10-03 09:20:36 +00:00
if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
$nodeinfo1_url = Network::addBasePath($link['href'], $httpResult->getUrl());
2019-10-03 09:20:36 +00:00
} elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
$nodeinfo2_url = Network::addBasePath($link['href'], $httpResult->getUrl());
2019-10-03 09:20:36 +00:00
}
}
if ($nodeinfo1_url . $nodeinfo2_url == '') {
return [];
}
$server = [];
2022-07-05 05:04:05 +00:00
if (!empty($nodeinfo2_url)) {
2019-10-03 09:20:36 +00:00
$server = self::parseNodeinfo2($nodeinfo2_url);
}
2022-07-05 05:04:05 +00:00
if (empty($server) && !empty($nodeinfo1_url)) {
2019-10-03 09:20:36 +00:00
$server = self::parseNodeinfo1($nodeinfo1_url);
}
return $server;
}
/**
2019-10-04 17:29:21 +00:00
* Parses Nodeinfo 1
2019-10-03 09:20:36 +00:00
*
* @param string $nodeinfo_url address of the nodeinfo path
2022-07-17 05:42:44 +00:00
*
2019-10-03 09:20:36 +00:00
* @return array Server data
2022-07-17 05:42:44 +00:00
*
2019-10-03 09:20:36 +00:00
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
private static function parseNodeinfo1(string $nodeinfo_url): array
2019-10-03 09:20:36 +00:00
{
$curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
2019-10-03 09:20:36 +00:00
if (!$curlResult->isSuccess()) {
2019-10-05 04:50:29 +00:00
return [];
2019-10-03 09:20:36 +00:00
}
$nodeinfo = json_decode($curlResult->getBody(), true);
if (!is_array($nodeinfo)) {
2019-10-05 04:50:29 +00:00
return [];
2019-10-03 09:20:36 +00:00
}
$server = ['detection-method' => self::DETECT_NODEINFO_1,
'register_policy' => Register::CLOSED];
2019-10-03 09:20:36 +00:00
if (!empty($nodeinfo['openRegistrations'])) {
$server['register_policy'] = Register::OPEN;
}
if (is_array($nodeinfo['software'])) {
2019-10-03 14:48:46 +00:00
if (!empty($nodeinfo['software']['name'])) {
2020-01-12 21:07:40 +00:00
$server['platform'] = strtolower($nodeinfo['software']['name']);
2019-10-03 09:20:36 +00:00
}
2019-10-03 14:48:46 +00:00
if (!empty($nodeinfo['software']['version'])) {
2019-10-03 09:20:36 +00:00
$server['version'] = $nodeinfo['software']['version'];
// Version numbers on Nodeinfo are presented with additional info, e.g.:
// 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
$server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
}
}
2019-10-03 14:48:46 +00:00
if (!empty($nodeinfo['metadata']['nodeName'])) {
2019-10-03 09:20:36 +00:00
$server['site_name'] = $nodeinfo['metadata']['nodeName'];
}
if (!empty($nodeinfo['usage']['users']['total'])) {
$server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
2019-10-03 09:20:36 +00:00
}
if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
$server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
}
if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
$server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
}
if (!empty($nodeinfo['usage']['localPosts'])) {
$server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
}
if (!empty($nodeinfo['usage']['localComments'])) {
$server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
}
2019-10-03 09:20:36 +00:00
if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
$protocols = [];
foreach ($nodeinfo['protocols']['inbound'] as $protocol) {
$protocols[$protocol] = true;
}
if (!empty($protocols['friendica'])) {
$server['network'] = Protocol::DFRN;
} elseif (!empty($protocols['activitypub'])) {
$server['network'] = Protocol::ACTIVITYPUB;
} elseif (!empty($protocols['diaspora'])) {
$server['network'] = Protocol::DIASPORA;
} elseif (!empty($protocols['ostatus'])) {
$server['network'] = Protocol::OSTATUS;
} elseif (!empty($protocols['gnusocial'])) {
$server['network'] = Protocol::OSTATUS;
2019-10-03 13:02:48 +00:00
} elseif (!empty($protocols['zot'])) {
$server['network'] = Protocol::ZOT;
2019-10-03 09:20:36 +00:00
}
}
2019-10-05 04:50:29 +00:00
if (empty($server)) {
return [];
2019-10-03 09:20:36 +00:00
}
2022-07-05 05:04:05 +00:00
if (empty($server['network'])) {
$server['network'] = Protocol::PHANTOM;
}
2019-10-03 09:20:36 +00:00
return $server;
}
/**
2019-10-04 17:29:21 +00:00
* Parses Nodeinfo 2
2019-10-03 09:20:36 +00:00
*
* @see https://git.feneas.org/jaywink/nodeinfo2
2022-07-17 05:42:44 +00:00
*
2019-10-03 09:20:36 +00:00
* @param string $nodeinfo_url address of the nodeinfo path
2022-07-17 05:42:44 +00:00
*
2019-10-03 09:20:36 +00:00
* @return array Server data
2022-07-17 05:42:44 +00:00
*
2019-10-03 09:20:36 +00:00
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
private static function parseNodeinfo2(string $nodeinfo_url): array
2019-10-03 09:20:36 +00:00
{
$curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
2019-10-03 09:20:36 +00:00
if (!$curlResult->isSuccess()) {
2019-10-05 04:50:29 +00:00
return [];
2019-10-03 09:20:36 +00:00
}
$nodeinfo = json_decode($curlResult->getBody(), true);
if (!is_array($nodeinfo)) {
2019-10-05 04:50:29 +00:00
return [];
2019-10-03 09:20:36 +00:00
}
$server = [
'detection-method' => self::DETECT_NODEINFO_2,
'register_policy' => Register::CLOSED,
'platform' => 'unknown',
];
2019-10-03 09:20:36 +00:00
if (!empty($nodeinfo['openRegistrations'])) {
$server['register_policy'] = Register::OPEN;
}
2022-07-05 05:04:05 +00:00
if (!empty($nodeinfo['software'])) {
if (isset($nodeinfo['software']['name'])) {
2020-01-12 21:07:40 +00:00
$server['platform'] = strtolower($nodeinfo['software']['name']);
2019-10-03 09:20:36 +00:00
}
2022-07-05 05:04:05 +00:00
if (!empty($nodeinfo['software']['version']) && isset($server['platform'])) {
2019-10-03 09:20:36 +00:00
$server['version'] = $nodeinfo['software']['version'];
// Version numbers on Nodeinfo are presented with additional info, e.g.:
// 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
$server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
// qoto advertises itself as Mastodon
if (($server['platform'] == 'mastodon') && substr($nodeinfo['software']['version'], -5) == '-qoto') {
$server['platform'] = 'qoto';
}
2019-10-03 09:20:36 +00:00
}
}
2019-10-03 14:48:46 +00:00
if (!empty($nodeinfo['metadata']['nodeName'])) {
2019-10-03 09:20:36 +00:00
$server['site_name'] = $nodeinfo['metadata']['nodeName'];
}
if (!empty($nodeinfo['usage']['users']['total'])) {
$server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
2019-10-03 09:20:36 +00:00
}
if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
$server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
}
if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
$server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
}
if (!empty($nodeinfo['usage']['localPosts'])) {
$server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
}
if (!empty($nodeinfo['usage']['localComments'])) {
$server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
}
2019-10-03 09:20:36 +00:00
if (!empty($nodeinfo['protocols'])) {
$protocols = [];
foreach ($nodeinfo['protocols'] as $protocol) {
if (is_string($protocol)) {
$protocols[$protocol] = true;
}
2019-10-03 09:20:36 +00:00
}
2019-12-21 13:48:20 +00:00
if (!empty($protocols['dfrn'])) {
2019-10-03 09:20:36 +00:00
$server['network'] = Protocol::DFRN;
} elseif (!empty($protocols['activitypub'])) {
$server['network'] = Protocol::ACTIVITYPUB;
} elseif (!empty($protocols['diaspora'])) {
$server['network'] = Protocol::DIASPORA;
} elseif (!empty($protocols['ostatus'])) {
$server['network'] = Protocol::OSTATUS;
} elseif (!empty($protocols['gnusocial'])) {
$server['network'] = Protocol::OSTATUS;
2019-10-03 13:02:48 +00:00
} elseif (!empty($protocols['zot'])) {
$server['network'] = Protocol::ZOT;
2019-10-03 09:20:36 +00:00
}
}
if (empty($server)) {
2019-10-05 04:50:29 +00:00
return [];
2019-10-03 09:20:36 +00:00
}
2022-07-05 05:04:05 +00:00
if (empty($server['network'])) {
$server['network'] = Protocol::PHANTOM;
}
return $server;
}
/**
* Parses NodeInfo2 protocol 1.0
*
* @see https://github.com/jaywink/nodeinfo2/blob/master/PROTOCOL.md
2022-07-17 05:42:44 +00:00
*
2022-07-05 05:04:05 +00:00
* @param string $nodeinfo_url address of the nodeinfo path
2022-07-17 05:42:44 +00:00
*
2022-07-05 05:04:05 +00:00
* @return array Server data
2022-07-17 05:42:44 +00:00
*
2022-07-05 05:04:05 +00:00
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
2022-07-17 05:42:44 +00:00
private static function parseNodeinfo210(ICanHandleHttpResponses $httpResult): array
2022-07-05 05:04:05 +00:00
{
if (!$httpResult->isSuccess()) {
return [];
}
$nodeinfo = json_decode($httpResult->getBody(), true);
if (!is_array($nodeinfo)) {
return [];
}
$server = ['detection-method' => self::DETECT_NODEINFO_210,
'register_policy' => Register::CLOSED];
if (!empty($nodeinfo['openRegistrations'])) {
$server['register_policy'] = Register::OPEN;
}
if (!empty($nodeinfo['server'])) {
if (!empty($nodeinfo['server']['software'])) {
$server['platform'] = strtolower($nodeinfo['server']['software']);
}
if (!empty($nodeinfo['server']['version'])) {
$server['version'] = $nodeinfo['server']['version'];
// Version numbers on Nodeinfo are presented with additional info, e.g.:
// 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
$server['version'] = preg_replace('=(.+)-(.{4,})=ism', '$1', $server['version']);
}
if (!empty($nodeinfo['server']['name'])) {
$server['site_name'] = $nodeinfo['server']['name'];
}
}
if (!empty($nodeinfo['usage']['users']['total'])) {
$server['registered-users'] = max($nodeinfo['usage']['users']['total'], 1);
}
if (!empty($nodeinfo['usage']['users']['activeMonth'])) {
$server['active-month-users'] = max($nodeinfo['usage']['users']['activeMonth'], 0);
}
if (!empty($nodeinfo['usage']['users']['activeHalfyear'])) {
$server['active-halfyear-users'] = max($nodeinfo['usage']['users']['activeHalfyear'], 0);
}
if (!empty($nodeinfo['usage']['localPosts'])) {
$server['local-posts'] = max($nodeinfo['usage']['localPosts'], 0);
}
if (!empty($nodeinfo['usage']['localComments'])) {
$server['local-comments'] = max($nodeinfo['usage']['localComments'], 0);
}
if (!empty($nodeinfo['protocols'])) {
$protocols = [];
foreach ($nodeinfo['protocols'] as $protocol) {
if (is_string($protocol)) {
$protocols[$protocol] = true;
}
}
if (!empty($protocols['dfrn'])) {
$server['network'] = Protocol::DFRN;
} elseif (!empty($protocols['activitypub'])) {
$server['network'] = Protocol::ACTIVITYPUB;
} elseif (!empty($protocols['diaspora'])) {
$server['network'] = Protocol::DIASPORA;
} elseif (!empty($protocols['ostatus'])) {
$server['network'] = Protocol::OSTATUS;
} elseif (!empty($protocols['gnusocial'])) {
$server['network'] = Protocol::OSTATUS;
} elseif (!empty($protocols['zot'])) {
$server['network'] = Protocol::ZOT;
}
}
if (empty($server) || empty($server['platform'])) {
return [];
}
if (empty($server['network'])) {
$server['network'] = Protocol::PHANTOM;
}
2019-10-03 09:20:36 +00:00
return $server;
}
2019-10-04 17:29:21 +00:00
/**
2019-10-05 04:22:16 +00:00
* Fetch server information from a 'siteinfo.json' file on the given server
2019-10-04 17:29:21 +00:00
*
* @param string $url URL of the given server
* @param array $serverdata array with server data
2022-07-17 05:42:44 +00:00
*
2019-10-04 17:29:21 +00:00
* @return array server data
*/
private static function fetchSiteinfo(string $url, array $serverdata): array
2019-10-03 09:20:36 +00:00
{
$curlResult = DI::httpClient()->get($url . '/siteinfo.json', HttpClientAccept::JSON);
2019-10-03 09:20:36 +00:00
if (!$curlResult->isSuccess()) {
return $serverdata;
}
$data = json_decode($curlResult->getBody(), true);
if (empty($data)) {
return $serverdata;
}
2022-07-05 05:04:05 +00:00
if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
$serverdata['detection-method'] = self::DETECT_SITEINFO_JSON;
}
if (!empty($data['platform'])) {
2020-01-12 21:07:40 +00:00
$serverdata['platform'] = strtolower($data['platform']);
$serverdata['version'] = $data['version'] ?? 'N/A';
2019-10-03 09:20:36 +00:00
}
if (!empty($data['plugins'])) {
if (in_array('pubcrawl', $data['plugins'])) {
$serverdata['network'] = Protocol::ACTIVITYPUB;
} elseif (in_array('diaspora', $data['plugins'])) {
$serverdata['network'] = Protocol::DIASPORA;
} elseif (in_array('gnusoc', $data['plugins'])) {
$serverdata['network'] = Protocol::OSTATUS;
} else {
$serverdata['network'] = Protocol::ZOT;
}
}
if (!empty($data['site_name'])) {
$serverdata['site_name'] = $data['site_name'];
}
if (!empty($data['channels_total'])) {
$serverdata['registered-users'] = max($data['channels_total'], 1);
2019-10-03 09:20:36 +00:00
}
if (!empty($data['channels_active_monthly'])) {
$serverdata['active-month-users'] = max($data['channels_active_monthly'], 0);
}
if (!empty($data['channels_active_halfyear'])) {
$serverdata['active-halfyear-users'] = max($data['channels_active_halfyear'], 0);
}
if (!empty($data['local_posts'])) {
$serverdata['local-posts'] = max($data['local_posts'], 0);
}
if (!empty($data['local_comments'])) {
$serverdata['local-comments'] = max($data['local_comments'], 0);
}
2019-10-03 09:20:36 +00:00
if (!empty($data['register_policy'])) {
switch ($data['register_policy']) {
2019-10-03 13:02:48 +00:00
case 'REGISTER_OPEN':
2019-10-03 09:20:36 +00:00
$serverdata['register_policy'] = Register::OPEN;
break;
2019-10-03 13:02:48 +00:00
case 'REGISTER_APPROVE':
2019-10-03 09:20:36 +00:00
$serverdata['register_policy'] = Register::APPROVE;
break;
2019-10-03 13:02:48 +00:00
case 'REGISTER_CLOSED':
2019-10-03 09:20:36 +00:00
default:
$serverdata['register_policy'] = Register::CLOSED;
break;
}
}
return $serverdata;
}
2022-07-17 05:42:44 +00:00
/**
* Fetches server data via an ActivityPub account with url of that server
*
* @param string $url URL of the given server
* @param array $serverdata array with server data
*
* @return array server data
*
* @throws Exception
*/
private static function fetchDataFromSystemActor(array $data, array $serverdata): array
2022-07-05 05:04:05 +00:00
{
if (empty($data)) {
return ['server' => $serverdata, 'actor' => ''];
}
2022-07-10 13:01:47 +00:00
$actor = JsonLD::compact($data, false);
2022-07-05 05:04:05 +00:00
if (in_array(JsonLD::fetchElement($actor, '@type'), ActivityPub\Receiver::ACCOUNT_TYPES)) {
$serverdata['network'] = Protocol::ACTIVITYPUB;
$serverdata['site_name'] = JsonLD::fetchElement($actor, 'as:name', '@value');
$serverdata['info'] = JsonLD::fetchElement($actor, 'as:summary', '@value');
if (self::isNomad($actor)) {
$serverdata['platform'] = self::getNomadName($actor['@id']);
$serverdata['version'] = self::getNomadVersion($actor['@id']);
$serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
} elseif (!empty($actor['as:generator'])) {
$generator = explode(' ', JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value'));
$serverdata['platform'] = strtolower(array_shift($generator));
$serverdata['version'] = self::getNomadVersion($actor['@id']);
2022-07-05 05:04:05 +00:00
$serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR;
} else {
$serverdata['detection-method'] = self::DETECT_AP_ACTOR;
}
return ['server' => $serverdata, 'actor' => $actor['@id']];
} elseif ((JsonLD::fetchElement($actor, '@type') == 'as:Collection')) {
// By now only Ktistec seems to provide collections this way
$serverdata['platform'] = 'ktistec';
$serverdata['network'] = Protocol::ACTIVITYPUB;
$serverdata['detection-method'] = self::DETECT_AP_COLLECTION;
$actors = JsonLD::fetchElementArray($actor, 'as:items');
if (!empty($actors) && !empty($actors[0]['@id'])) {
$actor_url = $actor['@id'] . $actors[0]['@id'];
} else {
$actor_url = '';
}
return ['server' => $serverdata, 'actor' => $actor_url];
}
return ['server' => $serverdata, 'actor' => ''];
}
/**
2023-03-18 12:27:49 +00:00
* Detect if the given actor is a nomad account
*
2023-03-18 12:27:49 +00:00
* @param array $actor
* @return boolean
*/
2023-03-18 12:27:49 +00:00
private static function isNomad(array $actor): bool
{
2023-03-18 12:27:49 +00:00
$tags = JsonLD::fetchElementArray($actor, 'as:tag');
if (empty($tags)) {
return false;
}
foreach ($tags as $tag) {
if ((($tag['as:name'] ?? '') == 'Protocol') && (($tag['sc:value'] ?? '') == 'nomad')) {
return true;
}
}
return false;
}
/**
* Fetch the name of Nomad implementation
*
* @param string $url
* @return string
*/
private static function getNomadName(string $url): string
{
$name = 'nomad';
$curlResult = DI::httpClient()->get($url . '/manifest', 'application/manifest+json');
if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
return $name;
}
$data = json_decode($curlResult->getBody(), true);
if (empty($data)) {
return $name;
}
return $data['name'] ?? $name;
}
/**
* Fetch the version of the Nomad installation
*
* @param string $url
* @return string
*/
private static function getNomadVersion(string $url): string
{
$curlResult = DI::httpClient()->get($url . '/api/z/1.0/version', HttpClientAccept::JSON);
if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
2023-03-21 06:42:29 +00:00
return '';
}
$data = json_decode($curlResult->getBody(), true);
if (empty($data)) {
2023-03-21 06:42:29 +00:00
return '';
}
2023-03-21 06:42:29 +00:00
return $data ?? '';
}
2019-10-04 17:29:21 +00:00
/**
* Checks if the server contains a valid host meta file
*
* @param string $url URL of the given server
2022-07-17 05:42:44 +00:00
*
2019-10-05 04:22:16 +00:00
* @return boolean 'true' if the server seems to be vital
2019-10-04 17:29:21 +00:00
*/
private static function validHostMeta(string $url): bool
{
$xrd_timeout = DI::config()->get('system', 'xrd_timeout');
$curlResult = DI::httpClient()->get($url . Probe::HOST_META, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
if (!$curlResult->isSuccess()) {
return false;
}
$xrd = XML::parseString($curlResult->getBody(), true);
if (!is_object($xrd)) {
return false;
}
$elements = XML::elementToArray($xrd);
if (empty($elements) || empty($elements['xrd']) || empty($elements['xrd']['link'])) {
return false;
}
$valid = false;
foreach ($elements['xrd']['link'] as $link) {
// When there is more than a single "link" element, the array looks slightly different
if (!empty($link['@attributes'])) {
$link = $link['@attributes'];
}
if (empty($link['rel']) || empty($link['template'])) {
continue;
}
if ($link['rel'] == 'lrdd') {
// When the webfinger host is the same like the system host, it should be ok.
$valid = (parse_url($url, PHP_URL_HOST) == parse_url($link['template'], PHP_URL_HOST));
}
}
return $valid;
}
2019-10-04 17:29:21 +00:00
/**
* Detect the network of the given server via their known contacts
*
* @param string $url URL of the given server
* @param array $serverdata array with server data
2022-07-17 05:42:44 +00:00
*
2019-10-04 17:29:21 +00:00
* @return array server data
*/
private static function detectNetworkViaContacts(string $url, array $serverdata): array
2019-10-04 06:33:16 +00:00
{
$contacts = [];
2019-10-04 06:33:16 +00:00
2022-07-05 05:04:05 +00:00
$nurl = Strings::normaliseLink($url);
$apcontacts = DBA::select('apcontact', ['url'], ['baseurl' => [$url, $nurl]]);
2020-04-27 14:35:50 +00:00
while ($apcontact = DBA::fetch($apcontacts)) {
$contacts[Strings::normaliseLink($apcontact['url'])] = $apcontact['url'];
2019-10-04 06:33:16 +00:00
}
DBA::close($apcontacts);
2022-07-05 05:04:05 +00:00
$pcontacts = DBA::select('contact', ['url', 'nurl'], ['uid' => 0, 'baseurl' => [$url, $nurl]]);
2020-04-27 14:35:50 +00:00
while ($pcontact = DBA::fetch($pcontacts)) {
2019-10-04 06:33:16 +00:00
$contacts[$pcontact['nurl']] = $pcontact['url'];
}
DBA::close($pcontacts);
if (empty($contacts)) {
return $serverdata;
}
2022-02-06 10:07:18 +00:00
$time = time();
2019-10-04 06:33:16 +00:00
foreach ($contacts as $contact) {
2022-07-05 05:04:05 +00:00
// Endlosschleife verhindern wegen gsid!
$data = Probe::uri($contact);
if (in_array($data['network'], Protocol::FEDERATED)) {
$serverdata['network'] = $data['network'];
if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
$serverdata['detection-method'] = self::DETECT_CONTACTS;
}
2019-10-04 06:33:16 +00:00
break;
2022-02-06 10:07:18 +00:00
} elseif ((time() - $time) > 10) {
// To reduce the stress on remote systems we probe a maximum of 10 seconds
2022-02-06 09:03:48 +00:00
break;
2019-10-04 06:33:16 +00:00
}
}
return $serverdata;
}
2019-10-04 17:29:21 +00:00
/**
2019-10-05 04:22:16 +00:00
* Checks if the given server does have a '/poco' endpoint.
* This is used for the 'PortableContact' functionality,
* which is used by both Friendica and Hubzilla.
2019-10-04 17:29:21 +00:00
*
* @param string $url URL of the given server
* @param array $serverdata array with server data
2022-07-17 05:42:44 +00:00
*
2019-10-04 17:29:21 +00:00
* @return array server data
*/
private static function checkPoCo(string $url, array $serverdata): array
2019-10-03 15:30:07 +00:00
{
2019-12-21 13:48:20 +00:00
$serverdata['poco'] = '';
$curlResult = DI::httpClient()->get($url . '/poco', HttpClientAccept::JSON);
2019-10-03 15:30:07 +00:00
if (!$curlResult->isSuccess()) {
return $serverdata;
}
$data = json_decode($curlResult->getBody(), true);
if (empty($data)) {
return $serverdata;
}
if (!empty($data['totalResults'])) {
$registeredUsers = $serverdata['registered-users'] ?? 0;
$serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
2019-12-21 13:48:20 +00:00
$serverdata['directory-type'] = self::DT_POCO;
2019-10-03 15:30:07 +00:00
$serverdata['poco'] = $url . '/poco';
2019-12-21 13:48:20 +00:00
}
return $serverdata;
}
/**
* Checks if the given server does have a Mastodon style directory endpoint.
*
* @param string $url URL of the given server
* @param array $serverdata array with server data
2022-07-17 05:42:44 +00:00
*
2019-12-21 13:48:20 +00:00
* @return array server data
*/
public static function checkMastodonDirectory(string $url, array $serverdata): array
2019-12-21 13:48:20 +00:00
{
$curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1', HttpClientAccept::JSON);
2019-12-21 13:48:20 +00:00
if (!$curlResult->isSuccess()) {
return $serverdata;
}
$data = json_decode($curlResult->getBody(), true);
if (empty($data)) {
return $serverdata;
}
if (count($data) == 1) {
$serverdata['directory-type'] = self::DT_MASTODON;
2019-10-03 15:30:07 +00:00
}
return $serverdata;
}
/**
* Detects Peertube via their known endpoint
*
* @param string $url URL of the given server
* @param array $serverdata array with server data
*
* @return array server data
*/
private static function detectPeertube(string $url, array $serverdata): array
{
$curlResult = DI::httpClient()->get($url . '/api/v1/config', HttpClientAccept::JSON);
if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
return $serverdata;
}
$data = json_decode($curlResult->getBody(), true);
if (empty($data)) {
return $serverdata;
}
if (!empty($data['instance']) && !empty($data['serverVersion'])) {
$serverdata['platform'] = 'peertube';
$serverdata['version'] = $data['serverVersion'];
$serverdata['network'] = Protocol::ACTIVITYPUB;
if (!empty($data['instance']['name'])) {
$serverdata['site_name'] = $data['instance']['name'];
}
if (!empty($data['instance']['shortDescription'])) {
$serverdata['info'] = $data['instance']['shortDescription'];
}
if (!empty($data['signup'])) {
if (!empty($data['signup']['allowed'])) {
$serverdata['register_policy'] = Register::OPEN;
}
}
2022-07-05 05:04:05 +00:00
if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
$serverdata['detection-method'] = self::DETECT_V1_CONFIG;
}
}
return $serverdata;
}
2019-10-04 17:29:21 +00:00
/**
* Detects the version number of a given server when it was a NextCloud installation
*
* @param string $url URL of the given server
* @param array $serverdata array with server data
2022-07-05 05:04:05 +00:00
* @param bool $validHostMeta
2019-10-04 17:29:21 +00:00
*
* @return array server data
*/
2022-07-17 05:42:44 +00:00
private static function detectNextcloud(string $url, array $serverdata, bool $validHostMeta): array
2019-10-03 09:20:36 +00:00
{
$curlResult = DI::httpClient()->get($url . '/status.php', HttpClientAccept::JSON);
2019-10-03 09:20:36 +00:00
if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
return $serverdata;
}
$data = json_decode($curlResult->getBody(), true);
if (empty($data)) {
return $serverdata;
}
if (!empty($data['version'])) {
$serverdata['platform'] = 'nextcloud';
$serverdata['version'] = $data['version'];
2022-07-05 05:04:05 +00:00
if ($validHostMeta) {
$serverdata['network'] = Protocol::ACTIVITYPUB;
}
if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
$serverdata['detection-method'] = self::DETECT_STATUS_PHP;
}
2019-10-03 09:20:36 +00:00
}
return $serverdata;
}
/**
* Fetches weekly usage data
*
* @param string $url URL of the given server
* @param array $serverdata array with server data
2022-07-17 05:42:44 +00:00
*
* @return array server data
*/
private static function fetchWeeklyUsage(string $url, array $serverdata): array
{
$curlResult = DI::httpClient()->get($url . '/api/v1/instance/activity', HttpClientAccept::JSON);
if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
return $serverdata;
}
$data = json_decode($curlResult->getBody(), true);
if (empty($data)) {
return $serverdata;
}
$current_week = [];
foreach ($data as $week) {
// Use only data from a full week
if (empty($week['week']) || (time() - $week['week']) < 7 * 24 * 60 * 60) {
continue;
}
// Most likely the data is sorted correctly. But we better are safe than sorry
if (empty($current_week['week']) || ($current_week['week'] < $week['week'])) {
$current_week = $week;
2022-07-05 05:04:05 +00:00
}
}
if (!empty($current_week['logins'])) {
$serverdata['active-week-users'] = max($current_week['logins'], 0);
}
return $serverdata;
}
2019-10-04 17:29:21 +00:00
/**
* Detects data from a given server url if it was a mastodon alike system
*
* @param string $url URL of the given server
* @param array $serverdata array with server data
2022-07-17 05:42:44 +00:00
*
2019-10-04 17:29:21 +00:00
* @return array server data
*/
private static function detectMastodonAlikes(string $url, array $serverdata): array
2019-10-03 09:20:36 +00:00
{
$curlResult = DI::httpClient()->get($url . '/api/v1/instance', HttpClientAccept::JSON);
2019-10-03 09:20:36 +00:00
if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
return $serverdata;
}
$data = json_decode($curlResult->getBody(), true);
if (empty($data)) {
return $serverdata;
}
2022-07-05 05:04:05 +00:00
$valid = false;
2019-10-03 13:02:48 +00:00
if (!empty($data['version'])) {
2019-10-03 09:20:36 +00:00
$serverdata['platform'] = 'mastodon';
$serverdata['version'] = $data['version'] ?? '';
2019-10-03 09:20:36 +00:00
$serverdata['network'] = Protocol::ACTIVITYPUB;
2022-07-05 05:04:05 +00:00
$valid = true;
2019-10-03 09:20:36 +00:00
}
2019-10-03 13:02:48 +00:00
if (!empty($data['title'])) {
$serverdata['site_name'] = $data['title'];
}
2022-07-05 05:04:05 +00:00
if (!empty($data['title']) && empty($serverdata['platform']) && ($serverdata['network'] == Protocol::PHANTOM)) {
2020-01-13 05:57:05 +00:00
$serverdata['platform'] = 'mastodon';
$serverdata['network'] = Protocol::ACTIVITYPUB;
2022-07-05 05:04:05 +00:00
$valid = true;
2020-01-13 05:57:05 +00:00
}
2019-10-03 13:02:48 +00:00
if (!empty($data['description'])) {
$serverdata['info'] = trim($data['description']);
}
2019-10-03 09:20:36 +00:00
if (!empty($data['stats']['user_count'])) {
$serverdata['registered-users'] = max($data['stats']['user_count'], 1);
2019-10-03 09:20:36 +00:00
}
if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
2020-01-12 21:07:40 +00:00
$serverdata['platform'] = strtolower($matches[1]);
$serverdata['version'] = $matches[2];
2022-07-05 05:04:05 +00:00
$valid = true;
}
2020-01-13 05:57:05 +00:00
if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
$serverdata['platform'] = 'pleroma';
$serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
2022-07-05 05:04:05 +00:00
$valid = true;
2020-01-13 05:57:05 +00:00
}
if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
$serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
2019-10-03 09:20:36 +00:00
$serverdata['platform'] = 'pleroma';
2022-07-05 05:04:05 +00:00
$valid = true;
}
if ($valid && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
$serverdata['detection-method'] = self::DETECT_MASTODON_API;
2019-10-03 09:20:36 +00:00
}
return $serverdata;
}
2019-10-04 17:29:21 +00:00
/**
* Detects data from typical Hubzilla endpoints
*
* @param string $url URL of the given server
* @param array $serverdata array with server data
2022-07-17 05:42:44 +00:00
*
2019-10-04 17:29:21 +00:00
* @return array server data
*/
private static function detectHubzilla(string $url, array $serverdata): array
2019-10-03 13:02:48 +00:00
{
$curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json', HttpClientAccept::JSON);
2019-10-03 13:02:48 +00:00
if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
return $serverdata;
}
$data = json_decode($curlResult->getBody(), true);
if (empty($data) || empty($data['site'])) {
2019-10-03 13:02:48 +00:00
return $serverdata;
}
if (!empty($data['site']['name'])) {
$serverdata['site_name'] = $data['site']['name'];
}
if (!empty($data['site']['platform'])) {
2020-01-12 21:07:40 +00:00
$serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']);
2019-10-03 13:02:48 +00:00
$serverdata['version'] = $data['site']['platform']['STD_VERSION'];
$serverdata['network'] = Protocol::ZOT;
}
2019-10-03 14:48:46 +00:00
if (!empty($data['site']['hubzilla'])) {
2020-01-12 21:07:40 +00:00
$serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']);
2019-10-03 13:02:48 +00:00
$serverdata['version'] = $data['site']['hubzilla']['RED_VERSION'];
$serverdata['network'] = Protocol::ZOT;
}
2019-10-03 14:48:46 +00:00
if (!empty($data['site']['redmatrix'])) {
if (!empty($data['site']['redmatrix']['PLATFORM_NAME'])) {
2020-01-12 21:07:40 +00:00
$serverdata['platform'] = strtolower($data['site']['redmatrix']['PLATFORM_NAME']);
2019-10-03 14:48:46 +00:00
} elseif (!empty($data['site']['redmatrix']['RED_PLATFORM'])) {
2020-01-12 21:07:40 +00:00
$serverdata['platform'] = strtolower($data['site']['redmatrix']['RED_PLATFORM']);
2019-10-03 13:02:48 +00:00
}
$serverdata['version'] = $data['site']['redmatrix']['RED_VERSION'];
$serverdata['network'] = Protocol::ZOT;
}
$private = false;
$inviteonly = false;
$closed = false;
if (!empty($data['site']['closed'])) {
$closed = self::toBoolean($data['site']['closed']);
}
if (!empty($data['site']['private'])) {
$private = self::toBoolean($data['site']['private']);
}
if (!empty($data['site']['inviteonly'])) {
$inviteonly = self::toBoolean($data['site']['inviteonly']);
}
if (!$closed && !$private and $inviteonly) {
$serverdata['register_policy'] = Register::APPROVE;
2019-10-03 13:02:48 +00:00
} elseif (!$closed && !$private) {
$serverdata['register_policy'] = Register::OPEN;
2019-10-03 13:02:48 +00:00
} else {
$serverdata['register_policy'] = Register::CLOSED;
}
2022-07-05 05:04:05 +00:00
if (($serverdata['network'] != Protocol::PHANTOM) && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
$serverdata['detection-method'] = self::DETECT_CONFIG_JSON;
2019-10-03 13:02:48 +00:00
}
return $serverdata;
}
2019-10-04 17:29:21 +00:00
/**
* Converts input value to a boolean value
*
* @param string|integer $val
2022-07-17 05:42:44 +00:00
*
2019-10-04 17:29:21 +00:00
* @return boolean
*/
private static function toBoolean($val): bool
2019-10-03 13:02:48 +00:00
{
if (($val == 'true') || ($val == 1)) {
return true;
} elseif (($val == 'false') || ($val == 0)) {
return false;
}
return $val;
}
2022-02-05 11:25:06 +00:00
2019-10-04 17:29:21 +00:00
/**
* Detect if the URL belongs to a GNU Social server
*
* @param string $url URL of the given server
* @param array $serverdata array with server data
2022-07-17 05:42:44 +00:00
*
2019-10-04 17:29:21 +00:00
* @return array server data
*/
private static function detectGNUSocial(string $url, array $serverdata): array
2019-10-03 09:20:36 +00:00
{
// Test for GNU Social
$curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json', HttpClientAccept::JSON);
2019-10-03 09:20:36 +00:00
if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
$serverdata['platform'] = 'gnusocial';
2019-10-03 09:20:36 +00:00
// Remove junk that some GNU Social servers return
$serverdata['version'] = str_replace(chr(239) . chr(187) . chr(191), '', $curlResult->getBody());
2020-01-12 12:50:00 +00:00
$serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
2019-10-03 09:20:36 +00:00
$serverdata['version'] = trim($serverdata['version'], '"');
$serverdata['network'] = Protocol::OSTATUS;
2022-07-05 05:04:05 +00:00
if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
$serverdata['detection-method'] = self::DETECT_GNUSOCIAL;
}
return $serverdata;
2019-10-03 09:20:36 +00:00
}
// Test for Statusnet
$curlResult = DI::httpClient()->get($url . '/api/statusnet/version.json', HttpClientAccept::JSON);
2019-10-03 09:20:36 +00:00
if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
2020-01-12 12:50:00 +00:00
2019-10-03 09:20:36 +00:00
// Remove junk that some GNU Social servers return
$serverdata['version'] = str_replace(chr(239).chr(187).chr(191), '', $curlResult->getBody());
2020-01-12 12:50:00 +00:00
$serverdata['version'] = str_replace(["\r", "\n", "\t"], '', $serverdata['version']);
2019-10-03 09:20:36 +00:00
$serverdata['version'] = trim($serverdata['version'], '"');
2020-01-12 12:50:00 +00:00
if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') {
$serverdata['platform'] = 'pleroma';
$serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
$serverdata['network'] = Protocol::ACTIVITYPUB;
} else {
$serverdata['platform'] = 'statusnet';
$serverdata['network'] = Protocol::OSTATUS;
}
2022-07-05 05:04:05 +00:00
if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
$serverdata['detection-method'] = self::DETECT_STATUSNET;
}
2019-10-03 09:20:36 +00:00
}
return $serverdata;
}
2019-10-04 17:29:21 +00:00
/**
* Detect if the URL belongs to a Friendica server
*
* @param string $url URL of the given server
* @param array $serverdata array with server data
2022-07-17 05:42:44 +00:00
*
2019-10-04 17:29:21 +00:00
* @return array server data
*/
private static function detectFriendica(string $url, array $serverdata): array
2019-10-03 09:20:36 +00:00
{
2022-03-28 10:33:06 +00:00
// There is a bug in some versions of Friendica that will return an ActivityStream actor when the content type "application/json" is requested.
// Because of this me must not use ACCEPT_JSON here.
$curlResult = DI::httpClient()->get($url . '/friendica/json');
2019-10-03 09:20:36 +00:00
if (!$curlResult->isSuccess()) {
$curlResult = DI::httpClient()->get($url . '/friendika/json');
$friendika = true;
$platform = 'Friendika';
} else {
$friendika = false;
$platform = 'Friendica';
2019-10-03 09:20:36 +00:00
}
if (!$curlResult->isSuccess()) {
return $serverdata;
}
$data = json_decode($curlResult->getBody(), true);
if (empty($data) || empty($data['version'])) {
return $serverdata;
}
2022-07-05 05:04:05 +00:00
if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) {
$serverdata['detection-method'] = $friendika ? self::DETECT_FRIENDIKA : self::DETECT_FRIENDICA;
}
2019-10-03 09:20:36 +00:00
$serverdata['network'] = Protocol::DFRN;
$serverdata['version'] = $data['version'];
if (!empty($data['no_scrape_url'])) {
$serverdata['noscrape'] = $data['no_scrape_url'];
}
if (!empty($data['site_name'])) {
$serverdata['site_name'] = $data['site_name'];
}
if (!empty($data['info'])) {
$serverdata['info'] = trim($data['info']);
}
$register_policy = ($data['register_policy'] ?? '') ?: 'REGISTER_CLOSED';
2019-10-03 09:20:36 +00:00
switch ($register_policy) {
case 'REGISTER_OPEN':
$serverdata['register_policy'] = Register::OPEN;
break;
case 'REGISTER_APPROVE':
$serverdata['register_policy'] = Register::APPROVE;
break;
case 'REGISTER_CLOSED':
case 'REGISTER_INVITATION':
$serverdata['register_policy'] = Register::CLOSED;
break;
default:
Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
$serverdata['register_policy'] = Register::CLOSED;
break;
}
$serverdata['platform'] = strtolower($data['platform'] ?? $platform);
2019-10-03 09:20:36 +00:00
return $serverdata;
}
2019-10-04 17:29:21 +00:00
/**
* Analyses the landing page of a given server for hints about type and system of that server
*
* @param object $curlResult result of curl execution
* @param array $serverdata array with server data
*
* @return array server data
*/
2022-07-18 03:48:19 +00:00
private static function analyseRootBody($curlResult, array $serverdata): array
2019-10-03 09:20:36 +00:00
{
2021-04-10 05:46:19 +00:00
if (empty($curlResult->getBody())) {
return $serverdata;
}
2022-07-18 03:48:19 +00:00
if (file_exists(__DIR__ . '/../../static/platforms.config.php')) {
require __DIR__ . '/../../static/platforms.config.php';
2022-07-05 05:04:05 +00:00
} else {
2022-07-18 03:48:19 +00:00
throw new HTTPException\InternalServerErrorException('Invalid platform file');
2022-07-05 05:04:05 +00:00
}
$platforms = array_merge($ap_platforms, $dfrn_platforms, $zap_platforms, $platforms);
2019-10-03 09:20:36 +00:00
$doc = new DOMDocument();
@$doc->loadHTML($curlResult->getBody());
$xpath = new DOMXPath($doc);
2022-07-10 13:01:47 +00:00
$assigned = false;
2019-10-03 09:20:36 +00:00
2022-07-05 05:04:05 +00:00
// We can only detect honk via some HTML element on their page
if ($xpath->query('//div[@id="honksonpage"]')->count() == 1) {
$serverdata['platform'] = 'honk';
$serverdata['network'] = Protocol::ACTIVITYPUB;
2022-07-10 13:01:47 +00:00
$assigned = true;
2022-07-05 05:04:05 +00:00
}
2019-10-03 09:20:36 +00:00
$title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()'));
if (!empty($title)) {
$serverdata['site_name'] = $title;
}
$list = $xpath->query('//meta[@name]');
foreach ($list as $node) {
$attr = [];
if ($node->attributes->length) {
foreach ($node->attributes as $attribute) {
2019-11-19 10:02:35 +00:00
$value = trim($attribute->value);
if (empty($value)) {
2019-10-03 09:20:36 +00:00
continue;
}
2019-11-19 10:02:35 +00:00
$attr[$attribute->name] = $value;
2019-10-03 09:20:36 +00:00
}
if (empty($attr['name']) || empty($attr['content'])) {
continue;
}
2019-10-03 09:20:36 +00:00
}
2019-10-03 21:39:48 +00:00
2019-10-03 09:20:36 +00:00
if ($attr['name'] == 'description') {
$serverdata['info'] = $attr['content'];
}
if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name',
2022-07-05 05:04:05 +00:00
'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad', 'generator'])) {
2022-07-10 13:01:47 +00:00
$platform = str_ireplace(array_keys($platforms), array_values($platforms), $attr['content']);
$platform = str_replace('/', ' ', $platform);
$platform_parts = explode(' ', $platform);
if ((count($platform_parts) >= 2) && in_array(strtolower($platform_parts[0]), array_values($platforms))) {
$platform = $platform_parts[0];
$serverdata['version'] = $platform_parts[1];
}
if (in_array($platform, array_values($dfrn_platforms))) {
$serverdata['network'] = Protocol::DFRN;
} elseif (in_array($platform, array_values($ap_platforms))) {
$serverdata['network'] = Protocol::ACTIVITYPUB;
} elseif (in_array($platform, array_values($zap_platforms))) {
$serverdata['network'] = Protocol::ZOT;
2019-10-03 09:20:36 +00:00
}
2022-07-05 05:04:05 +00:00
if (in_array($platform, array_values($platforms))) {
$serverdata['platform'] = $platform;
2022-07-10 13:01:47 +00:00
$assigned = true;
2022-07-05 05:04:05 +00:00
}
2019-10-03 09:20:36 +00:00
}
}
$list = $xpath->query('//meta[@property]');
foreach ($list as $node) {
$attr = [];
if ($node->attributes->length) {
foreach ($node->attributes as $attribute) {
2019-11-19 10:02:35 +00:00
$value = trim($attribute->value);
if (empty($value)) {
2019-10-03 09:20:36 +00:00
continue;
}
2019-11-19 10:02:35 +00:00
$attr[$attribute->name] = $value;
2019-10-03 09:20:36 +00:00
}
if (empty($attr['property']) || empty($attr['content'])) {
continue;
}
2019-10-03 09:20:36 +00:00
}
if ($attr['property'] == 'og:site_name') {
$serverdata['site_name'] = $attr['content'];
}
if ($attr['property'] == 'og:description') {
$serverdata['info'] = $attr['content'];
}
2022-07-05 05:04:05 +00:00
if (in_array($attr['property'], ['og:platform', 'generator'])) {
if (in_array($attr['content'], array_keys($platforms))) {
$serverdata['platform'] = $platforms[$attr['content']];
2022-07-10 13:01:47 +00:00
$assigned = true;
}
2019-10-03 09:20:36 +00:00
2022-07-05 05:04:05 +00:00
if (in_array($attr['content'], array_keys($ap_platforms))) {
$serverdata['network'] = Protocol::ACTIVITYPUB;
} elseif (in_array($attr['content'], array_values($zap_platforms))) {
$serverdata['network'] = Protocol::ZOT;
}
2019-10-03 09:20:36 +00:00
}
}
2022-07-10 13:01:47 +00:00
$list = $xpath->query('//link[@rel="me"]');
foreach ($list as $node) {
foreach ($node->attributes as $attribute) {
if (parse_url(trim($attribute->value), PHP_URL_HOST) == 'micro.blog') {
$serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
$serverdata['platform'] = 'microblog';
$serverdata['network'] = Protocol::ACTIVITYPUB;
$assigned = true;
}
}
}
if ($serverdata['platform'] != 'microblog') {
$list = $xpath->query('//link[@rel="micropub"]');
foreach ($list as $node) {
foreach ($node->attributes as $attribute) {
if (trim($attribute->value) == 'https://micro.blog/micropub') {
$serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
$serverdata['platform'] = 'microblog';
$serverdata['network'] = Protocol::ACTIVITYPUB;
$assigned = true;
}
}
}
}
if ($assigned && in_array($serverdata['detection-method'], [self::DETECT_MANUAL, self::DETECT_HEADER])) {
$serverdata['detection-method'] = self::DETECT_BODY;
}
2019-10-03 09:20:36 +00:00
return $serverdata;
}
2019-10-04 17:29:21 +00:00
/**
* Analyses the header data of a given server for hints about type and system of that server
*
* @param object $curlResult result of curl execution
* @param array $serverdata array with server data
*
* @return array server data
*/
private static function analyseRootHeader($curlResult, array $serverdata): array
2019-10-03 09:20:36 +00:00
{
if ($curlResult->getHeader('server') == 'Mastodon') {
$serverdata['platform'] = 'mastodon';
$serverdata['network'] = Protocol::ACTIVITYPUB;
2019-10-03 09:20:36 +00:00
} elseif ($curlResult->inHeader('x-diaspora-version')) {
$serverdata['platform'] = 'diaspora';
$serverdata['network'] = Protocol::DIASPORA;
$serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? '';
2019-10-03 09:20:36 +00:00
} elseif ($curlResult->inHeader('x-friendica-version')) {
$serverdata['platform'] = 'friendica';
$serverdata['network'] = Protocol::DFRN;
$serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? '';
} else {
return $serverdata;
}
if ($serverdata['detection-method'] == self::DETECT_MANUAL) {
$serverdata['detection-method'] = self::DETECT_HEADER;
2019-10-03 09:20:36 +00:00
}
2019-10-03 09:20:36 +00:00
return $serverdata;
}
2019-12-21 06:39:22 +00:00
/**
* Update GServer entries
*/
public static function discover()
{
// Update the server list
self::discoverFederation();
$no_of_queries = 5;
$requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
if ($requery_days == 0) {
$requery_days = 7;
}
$last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
$gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
["NOT `blocked` AND NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
['order' => ['RAND()']]);
while ($gserver = DBA::fetch($gservers)) {
2020-08-01 05:55:27 +00:00
Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2022-10-17 05:49:55 +00:00
Worker::add(Worker::PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
2020-08-01 05:55:27 +00:00
Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
2022-10-17 05:49:55 +00:00
Worker::add(Worker::PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
$fields = ['last_poco_query' => DateTimeFormat::utcNow()];
self::update($fields, ['nurl' => $gserver['nurl']]);
if (--$no_of_queries == 0) {
break;
}
}
DBA::close($gservers);
}
/**
* Discover federated servers
*/
private static function discoverFederation()
{
$last = DI::keyValue()->get('poco_last_federation_discovery');
if ($last) {
$next = $last + (24 * 60 * 60);
if ($next > time()) {
return;
}
}
// Discover federated servers
$protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus'];
foreach ($protocols as $protocol) {
$query = '{nodes(protocol:"' . $protocol . '"){host}}';
$curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query), HttpClientAccept::JSON);
if (!empty($curlResult)) {
$data = json_decode($curlResult, true);
if (!empty($data['data']['nodes'])) {
foreach ($data['data']['nodes'] as $server) {
// Using "only_nodeinfo" since servers that are listed on that page should always have it.
2020-12-03 22:32:51 +00:00
self::add('https://' . $server['host'], true);
}
}
}
}
// Discover Mastodon servers
$accesstoken = DI::config()->get('system', 'instances_social_key');
if (!empty($accesstoken)) {
$api = 'https://instances.social/api/1.0/instances/list?count=0';
$curlResult = DI::httpClient()->get($api, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken]]]);
if ($curlResult->isSuccess()) {
$servers = json_decode($curlResult->getBody(), true);
2022-08-28 09:12:36 +00:00
if (!empty($servers['instances'])) {
foreach ($servers['instances'] as $server) {
$url = (is_null($server['https_score']) ? 'http' : 'https') . '://' . $server['name'];
self::add($url);
}
}
}
}
DI::keyValue()->set('poco_last_federation_discovery', time());
}
2021-01-09 19:18:22 +00:00
/**
* Set the protocol for the given server
*
* @param int $gsid Server id
* @param int $protocol Protocol id
2022-07-17 05:42:44 +00:00
*
* @throws Exception
2021-01-09 19:18:22 +00:00
*/
public static function setProtocol(int $gsid, int $protocol)
2021-01-09 19:18:22 +00:00
{
if (empty($gsid)) {
return;
}
$gserver = DBA::selectFirst('gserver', ['protocol', 'url'], ['id' => $gsid]);
if (!DBA::isResult($gserver)) {
return;
}
$old = $gserver['protocol'];
if (!is_null($old)) {
/*
The priority for the protocols is:
1. ActivityPub
2. DFRN via Diaspora
3. Legacy DFRN
4. Diaspora
5. OStatus
*/
// We don't need to change it when nothing is to be changed
if ($old == $protocol) {
return;
}
// We don't want to mark a server as OStatus when it had been marked with any other protocol before
if ($protocol == Post\DeliveryData::OSTATUS) {
return;
}
// If the server is marked as ActivityPub then we won't change it to anything different
if ($old == Post\DeliveryData::ACTIVITYPUB) {
return;
}
// Don't change it to anything lower than DFRN if the new one wasn't ActivityPub
if (($old == Post\DeliveryData::DFRN) && ($protocol != Post\DeliveryData::ACTIVITYPUB)) {
return;
}
// Don't change it to Diaspora when it is a legacy DFRN server
if (($old == Post\DeliveryData::LEGACY_DFRN) && ($protocol == Post\DeliveryData::DIASPORA)) {
return;
}
}
Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url'], 'callstack' => System::callstack(20)]);
self::update(['protocol' => $protocol], ['id' => $gsid]);
2021-01-09 19:18:22 +00:00
}
/**
* Fetch the protocol of the given server
*
* @param int $gsid Server id
2022-07-17 05:42:44 +00:00
*
* @return ?int One of Post\DeliveryData protocol constants or null if unknown or gserver is missing
2022-07-17 05:42:44 +00:00
*
* @throws Exception
*/
public static function getProtocol(int $gsid): ?int
{
if (empty($gsid)) {
return null;
}
$gserver = DBA::selectFirst('gserver', ['protocol'], ['id' => $gsid]);
if (DBA::isResult($gserver)) {
return $gserver['protocol'];
}
return null;
}
/**
2022-08-28 19:27:21 +00:00
* Update rows in the gserver table.
* Enforces gserver table field maximum sizes to avoid "Data too long" database errors
*
* @param array $fields
* @param array $condition
2022-07-17 05:42:44 +00:00
*
* @return bool
2022-07-17 05:42:44 +00:00
*
* @throws Exception
*/
public static function update(array $fields, array $condition): bool
{
2022-07-12 22:23:12 +00:00
$fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
return DBA::update('gserver', $fields, $condition);
}
2022-08-28 19:27:21 +00:00
/**
* Insert a row into the gserver table.
* Enforces gserver table field maximum sizes to avoid "Data too long" database errors
*
* @param array $fields
* @param int $duplicate_mode What to do on a duplicated entry
*
* @return bool
*
* @throws Exception
*/
public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): bool
{
$fields = DI::dbaDefinition()->truncateFieldsForTable('gserver', $fields);
return DBA::insert('gserver', $fields, $duplicate_mode);
}
2019-10-03 09:20:36 +00:00
}