Code transitioning from PortableContacts.php to GServer.php

This commit is contained in:
Michael 2019-10-03 23:33:41 +00:00
parent 2009080327
commit d9a74bd5dd
6 changed files with 135 additions and 954 deletions

View file

@ -1481,7 +1481,7 @@ class Contact extends BaseObject
$data = Probe::uri($url, "", $uid); $data = Probe::uri($url, "", $uid);
// Ensure that there is a gserver entry // Ensure that there is a gserver entry
if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) { if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
PortableContact::checkServer($data['baseurl']); GServer::check($data['baseurl']);
} }
} }

View file

@ -231,7 +231,7 @@ class GContact
} }
// The server URL doesn't seem to be valid, so we don't store it. // The server URL doesn't seem to be valid, so we don't store it.
if (!PortableContact::checkServer($gcontact['server_url'], $gcontact['network'])) { if (!GServer::check($gcontact['server_url'])) {
$gcontact['server_url'] = ""; $gcontact['server_url'] = "";
} }
@ -541,7 +541,7 @@ class GContact
$j = json_decode($x); $j = json_decode($x);
if (!empty($j->entries)) { if (!empty($j->entries)) {
foreach ($j->entries as $entry) { foreach ($j->entries as $entry) {
PortableContact::checkServer($entry->url); GServer::check($entry->url);
$url = $entry->url . '/poco'; $url = $entry->url . '/poco';
if (!in_array($url, $done)) { if (!in_array($url, $done)) {

View file

@ -17,12 +17,55 @@ use Friendica\Util\DateTimeFormat;
use Friendica\Util\Strings; use Friendica\Util\Strings;
use Friendica\Util\XML; use Friendica\Util\XML;
use Friendica\Core\Logger; use Friendica\Core\Logger;
use Friendica\Protocol\PortableContact;
use Friendica\Protocol\Diaspora;
/** /**
* @brief This class handles GServer related functions * @brief This class handles GServer related functions
*/ */
class GServer class GServer
{ {
public static function check($server_url, $force = false)
{
// Unify the server address
$server_url = trim($server_url, '/');
$server_url = str_replace('/index.php', '', $server_url);
if ($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)];
DBA::update('gserver', $fields, $condition);
}
$last_contact = $gserver["last_contact"];
$last_failure = $gserver["last_failure"];
// See discussion under https://forum.friendi.ca/display/0b6b25a8135aabc37a5a0f5684081633
// It can happen that a zero date is in the database, but storing it again is forbidden.
if ($last_contact < DBA::NULL_DATETIME) {
$last_contact = DBA::NULL_DATETIME;
}
if ($last_failure < DBA::NULL_DATETIME) {
$last_failure = DBA::NULL_DATETIME;
}
if (!$force && !PortableContact::updateNeeded($gserver['created'], '', $last_failure, $last_contact)) {
Logger::info('Use cached data', ['server' => $server_url]);
return ($last_contact >= $last_failure);
}
}
Logger::info('Server is outdated or unknown. Start discovery.', ['Server' => $server_url, 'Force' => $force, 'Created' => $gserver['created'], 'Failure' => $last_failure, 'Contact' => $last_contact]);
return self::detect($server_url);
}
/** /**
* Detect server data (type, protocol, version number, ...) * Detect server data (type, protocol, version number, ...)
* The detected data is then updated or inserted in the gserver table. * The detected data is then updated or inserted in the gserver table.
@ -133,9 +176,86 @@ class GServer
$ret = DBA::update('gserver', $serverdata, ['nurl' => $serverdata['nurl']]); $ret = DBA::update('gserver', $serverdata, ['nurl' => $serverdata['nurl']]);
} }
if (in_array($serverdata['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
self::discoverRelay($url);
}
return $ret; return $ret;
} }
/**
* @brief Fetch relay data from a given server url
*
* @param string $server_url address of the server
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
private static function discoverRelay($server_url)
{
Logger::info('Discover relay data', ['server' => $server_url]);
$curlResult = Network::curl($server_url . '/.well-known/x-social-relay');
if (!$curlResult->isSuccess()) {
return;
}
$data = json_decode($curlResult->getBody(), true);
if (!is_array($data)) {
return;
}
$gserver = DBA::selectFirst('gserver', ['id', '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']];
DBA::update('gserver', $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) {
DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], true);
}
}
// 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'];
}
}
}
Diaspora::setRelayContact($server_url, $fields);
}
private static function fetchStatistics($url) private static function fetchStatistics($url)
{ {
$curlResult = Network::curl($url . '/statistics.json'); $curlResult = Network::curl($url . '/statistics.json');

View file

@ -20,6 +20,7 @@ use Friendica\Core\Worker;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Model\Contact; use Friendica\Model\Contact;
use Friendica\Model\GContact; use Friendica\Model\GContact;
use Friendica\Model\GServer;
use Friendica\Model\Profile; use Friendica\Model\Profile;
use Friendica\Module\Register; use Friendica\Module\Register;
use Friendica\Network\Probe; use Friendica\Network\Probe;
@ -223,7 +224,7 @@ class PortableContact
return true; return true;
} }
return self::checkServer($server, $network, $force); return GServer::check($server, $force);
} }
public static function alternateOStatusUrl($url) public static function alternateOStatusUrl($url)
@ -267,7 +268,7 @@ class PortableContact
} }
if ($server_url != "") { if ($server_url != "") {
if (!self::checkServer($server_url, $gcontacts[0]["network"], $force)) { if (!GServer::check($server_url, $force)) {
if ($force) { if ($force) {
$fields = ['last_failure' => DateTimeFormat::utcNow()]; $fields = ['last_failure' => DateTimeFormat::utcNow()];
DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($profile)]); DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($profile)]);
@ -523,948 +524,6 @@ class PortableContact
return true; return true;
} }
/// @TODO Maybe move this out to an utilities class?
private static function toBoolean($val)
{
if (($val == "true") || ($val == 1)) {
return true;
} elseif (($val == "false") || ($val == 0)) {
return false;
}
return $val;
}
/**
* @brief Detect server type (Hubzilla or Friendica) via the poco data
*
* @param array $data POCO data
* @return array Server data
*/
private static function detectPocoData(array $data)
{
if (!isset($data['entry'])) {
return false;
}
if (count($data['entry']) == 0) {
return false;
}
if (!isset($data['entry'][0]['urls'])) {
return false;
}
if (count($data['entry'][0]['urls']) == 0) {
return false;
}
foreach ($data['entry'][0]['urls'] as $url) {
if ($url['type'] == 'zot') {
$server = [];
$server["platform"] = 'Hubzilla';
$server["network"] = Protocol::DIASPORA;
return $server;
}
}
return false;
}
/**
* @brief Detect server type by using the nodeinfo data
*
* @param string $server_url address of the server
* @return array Server data
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
private static function fetchNodeinfo($server_url)
{
$curlResult = Network::curl($server_url."/.well-known/nodeinfo");
if (!$curlResult->isSuccess()) {
return false;
}
$nodeinfo = json_decode($curlResult->getBody(), true);
if (!is_array($nodeinfo) || !isset($nodeinfo['links'])) {
return false;
}
$nodeinfo1_url = '';
$nodeinfo2_url = '';
foreach ($nodeinfo['links'] as $link) {
if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
Logger::log('Invalid nodeinfo format for ' . $server_url, Logger::DEBUG);
continue;
}
if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
$nodeinfo1_url = $link['href'];
} elseif ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0') {
$nodeinfo2_url = $link['href'];
}
}
if ($nodeinfo1_url . $nodeinfo2_url == '') {
return false;
}
$server = [];
// When the nodeinfo url isn't on the same host, then there is obviously something wrong
if (!empty($nodeinfo2_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo2_url, PHP_URL_HOST))) {
$server = self::parseNodeinfo2($nodeinfo2_url);
}
// When the nodeinfo url isn't on the same host, then there is obviously something wrong
if (empty($server) && !empty($nodeinfo1_url) && (parse_url($server_url, PHP_URL_HOST) == parse_url($nodeinfo1_url, PHP_URL_HOST))) {
$server = self::parseNodeinfo1($nodeinfo1_url);
}
return $server;
}
/**
* @brief Parses Nodeinfo 1
*
* @param string $nodeinfo_url address of the nodeinfo path
* @return array Server data
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
private static function parseNodeinfo1($nodeinfo_url)
{
$curlResult = Network::curl($nodeinfo_url);
if (!$curlResult->isSuccess()) {
return false;
}
$nodeinfo = json_decode($curlResult->getBody(), true);
if (!is_array($nodeinfo)) {
return false;
}
$server = [];
$server['register_policy'] = Register::CLOSED;
if (isset($nodeinfo['openRegistrations']) && is_bool($nodeinfo['openRegistrations']) && $nodeinfo['openRegistrations']) {
$server['register_policy'] = Register::OPEN;
}
if (is_array($nodeinfo['software'])) {
if (isset($nodeinfo['software']['name'])) {
$server['platform'] = $nodeinfo['software']['name'];
}
if (isset($nodeinfo['software']['version'])) {
$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']);
}
}
if (isset($nodeinfo['metadata']['nodeName'])) {
$server['site_name'] = $nodeinfo['metadata']['nodeName'];
}
if (!empty($nodeinfo['usage']['users']['total'])) {
$server['registered-users'] = $nodeinfo['usage']['users']['total'];
}
$diaspora = false;
$friendica = false;
$gnusocial = false;
if (!empty($nodeinfo['protocols']['inbound']) && is_array($nodeinfo['protocols']['inbound'])) {
foreach ($nodeinfo['protocols']['inbound'] as $inbound) {
if ($inbound == 'diaspora') {
$diaspora = true;
}
if ($inbound == 'friendica') {
$friendica = true;
}
if ($inbound == 'gnusocial') {
$gnusocial = true;
}
}
}
if ($gnusocial) {
$server['network'] = Protocol::OSTATUS;
}
if ($diaspora) {
$server['network'] = Protocol::DIASPORA;
}
if ($friendica) {
$server['network'] = Protocol::DFRN;
}
if (!$server) {
return false;
}
return $server;
}
/**
* @brief Parses Nodeinfo 2
*
* @param string $nodeinfo_url address of the nodeinfo path
* @return array Server data
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
private static function parseNodeinfo2($nodeinfo_url)
{
$curlResult = Network::curl($nodeinfo_url);
if (!$curlResult->isSuccess()) {
return false;
}
$nodeinfo = json_decode($curlResult->getBody(), true);
if (!is_array($nodeinfo)) {
return false;
}
$server = [];
$server['register_policy'] = Register::CLOSED;
if (is_bool($nodeinfo['openRegistrations']) && $nodeinfo['openRegistrations']) {
$server['register_policy'] = Register::OPEN;
}
if (is_array($nodeinfo['software'])) {
if (isset($nodeinfo['software']['name'])) {
$server['platform'] = $nodeinfo['software']['name'];
}
if (isset($nodeinfo['software']['version'])) {
$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']);
}
}
if (isset($nodeinfo['metadata']['nodeName'])) {
$server['site_name'] = $nodeinfo['metadata']['nodeName'];
}
if (!empty($nodeinfo['usage']['users']['total'])) {
$server['registered-users'] = $nodeinfo['usage']['users']['total'];
}
$diaspora = false;
$friendica = false;
$gnusocial = false;
if (!empty($nodeinfo['protocols'])) {
foreach ($nodeinfo['protocols'] as $protocol) {
if ($protocol == 'diaspora') {
$diaspora = true;
} elseif ($protocol == 'friendica') {
$friendica = true;
} elseif ($protocol == 'gnusocial') {
$gnusocial = true;
}
}
}
if ($gnusocial) {
$server['network'] = Protocol::OSTATUS;
} elseif ($diaspora) {
$server['network'] = Protocol::DIASPORA;
} elseif ($friendica) {
$server['network'] = Protocol::DFRN;
}
if (empty($server)) {
return false;
}
return $server;
}
/**
* @brief Detect server type (Hubzilla or Friendica) via the front page body
*
* @param string $body Front page of the server
* @return array Server data
*/
private static function detectServerType($body)
{
$server = false;
$doc = new DOMDocument();
/// @TODO Acoid supressing error
@$doc->loadHTML($body);
$xpath = new DOMXPath($doc);
$list = $xpath->query("//meta[@name]");
foreach ($list as $node) {
$attr = [];
if ($node->attributes->length) {
foreach ($node->attributes as $attribute) {
$attr[$attribute->name] = $attribute->value;
}
}
if ($attr['name'] == 'generator') {
$version_part = explode(" ", $attr['content']);
if (count($version_part) == 2) {
if (in_array($version_part[0], ["Friendika", "Friendica"])) {
$server = [];
$server["platform"] = $version_part[0];
$server["version"] = $version_part[1];
$server["network"] = Protocol::DFRN;
}
}
}
}
if (!$server) {
$list = $xpath->query("//meta[@property]");
foreach ($list as $node) {
$attr = [];
if ($node->attributes->length) {
foreach ($node->attributes as $attribute) {
$attr[$attribute->name] = $attribute->value;
}
}
if ($attr['property'] == 'generator' && in_array($attr['content'], ["hubzilla", "BlaBlaNet"])) {
$server = [];
$server["platform"] = $attr['content'];
$server["version"] = "";
$server["network"] = Protocol::DIASPORA;
}
}
}
if (!$server) {
return false;
}
$server["site_name"] = XML::getFirstNodeValue($xpath, '//head/title/text()');
return $server;
}
public static function checkServer($server_url, $network = "", $force = false)
{
// Unify the server address
$server_url = trim($server_url, "/");
$server_url = str_replace("/index.php", "", $server_url);
if ($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)];
DBA::update('gserver', $fields, $condition);
}
$poco = $gserver["poco"];
$noscrape = $gserver["noscrape"];
if ($network == "") {
$network = $gserver["network"];
}
$last_contact = $gserver["last_contact"];
$last_failure = $gserver["last_failure"];
$version = $gserver["version"];
$platform = $gserver["platform"];
$site_name = $gserver["site_name"];
$info = $gserver["info"];
$register_policy = $gserver["register_policy"];
$registered_users = $gserver["registered-users"];
// See discussion under https://forum.friendi.ca/display/0b6b25a8135aabc37a5a0f5684081633
// It can happen that a zero date is in the database, but storing it again is forbidden.
if ($last_contact < DBA::NULL_DATETIME) {
$last_contact = DBA::NULL_DATETIME;
}
if ($last_failure < DBA::NULL_DATETIME) {
$last_failure = DBA::NULL_DATETIME;
}
if (!$force && !self::updateNeeded($gserver["created"], "", $last_failure, $last_contact)) {
Logger::log("Use cached data for server ".$server_url, Logger::DEBUG);
return ($last_contact >= $last_failure);
}
} else {
$poco = "";
$noscrape = "";
$version = "";
$platform = "";
$site_name = "";
$info = "";
$register_policy = -1;
$registered_users = 0;
$last_contact = DBA::NULL_DATETIME;
$last_failure = DBA::NULL_DATETIME;
}
Logger::log("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$gserver["created"]." Failure: ".$last_failure." Contact: ".$last_contact, Logger::DEBUG);
$failure = false;
$possible_failure = false;
$orig_last_failure = $last_failure;
$orig_last_contact = $last_contact;
// Mastodon uses the "@" for user profiles.
// But this can be misunderstood.
if (parse_url($server_url, PHP_URL_USER) != '') {
DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => Strings::normaliseLink($server_url)]);
return false;
}
// Check if the page is accessible via SSL.
$orig_server_url = $server_url;
$server_url = str_replace("http://", "https://", $server_url);
// We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
$curlResult = Network::curl($server_url."/.well-known/host-meta", false, ['timeout' => 20]);
// Quit if there is a timeout.
// But we want to make sure to only quit if we are mostly sure that this server url fits.
if (DBA::isResult($gserver) && ($orig_server_url == $server_url) &&
($curlResult->isTimeout())) {
Logger::log("Connection to server ".$server_url." timed out.", Logger::DEBUG);
DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => Strings::normaliseLink($server_url)]);
return false;
}
// Maybe the page is unencrypted only?
$xmlobj = @simplexml_load_string($curlResult->getBody(), 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
if (!$curlResult->isSuccess() || ($curlResult->getBody() == "") || empty($xmlobj) || !is_object($xmlobj)) {
$server_url = str_replace("https://", "http://", $server_url);
// We set the timeout to 20 seconds since this operation should be done in no time if the server was vital
$curlResult = Network::curl($server_url."/.well-known/host-meta", false, ['timeout' => 20]);
// Quit if there is a timeout
if ($curlResult->isTimeout()) {
Logger::log("Connection to server " . $server_url . " timed out.", Logger::DEBUG);
DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => Strings::normaliseLink($server_url)]);
return false;
}
$xmlobj = @simplexml_load_string($curlResult->getBody(), 'SimpleXMLElement', 0, "http://docs.oasis-open.org/ns/xri/xrd-1.0");
}
if (!$curlResult->isSuccess() || ($curlResult->getBody() == "") || empty($xmlobj) || !is_object($xmlobj)) {
// Workaround for bad configured servers (known nginx problem)
if (!empty($curlResult->getInfo()) && !in_array($curlResult->getInfo()["http_code"], ["403", "404"])) {
$failure = true;
}
$possible_failure = true;
}
// If the server has no possible failure we reset the cached data
if (!$possible_failure) {
$version = "";
$platform = "";
$site_name = "";
$info = "";
$register_policy = -1;
}
if (!$failure) {
// This will be too low, but better than no value at all.
$registered_users = DBA::count('gcontact', ['server_url' => Strings::normaliseLink($server_url)]);
}
// Look for poco
if (!$failure) {
$curlResult = Network::curl($server_url."/poco");
if ($curlResult->isSuccess()) {
$data = json_decode($curlResult->getBody(), true);
if (isset($data['totalResults'])) {
$registered_users = $data['totalResults'];
$poco = $server_url . "/poco";
$server = self::detectPocoData($data);
if (!empty($server)) {
$platform = $server['platform'];
$network = $server['network'];
$version = '';
$site_name = '';
}
}
/*
* There are servers out there who don't return 404 on a failure
* We have to be sure that don't misunderstand this
*/
if (is_null($data)) {
$poco = "";
$noscrape = "";
$network = "";
}
}
}
if (!$failure) {
// Test for Diaspora, Hubzilla, Mastodon or older Friendica servers
$curlResult = Network::curl($server_url);
if (!$curlResult->isSuccess() || ($curlResult->getBody() == "")) {
$failure = true;
} else {
$server = self::detectServerType($curlResult->getBody());
if (!empty($server)) {
$platform = $server['platform'];
$network = $server['network'];
$version = $server['version'];
$site_name = $server['site_name'];
}
$lines = explode("\n", $curlResult->getHeader());
if (count($lines)) {
foreach ($lines as $line) {
$line = trim($line);
if (stristr($line, 'X-Diaspora-Version:')) {
$platform = "Diaspora";
$version = trim(str_replace("X-Diaspora-Version:", "", $line));
$version = trim(str_replace("x-diaspora-version:", "", $version));
$network = Protocol::DIASPORA;
$versionparts = explode("-", $version);
$version = $versionparts[0];
}
if (stristr($line, 'Server: Mastodon')) {
$platform = "Mastodon";
$network = Protocol::OSTATUS;
}
}
}
}
}
if (!$failure && ($poco == "")) {
// Test for Statusnet
// Will also return data for Friendica and GNU Social - but it will be overwritten later
// The "not implemented" is a special treatment for really, really old Friendica versions
$curlResult = Network::curl($server_url."/api/statusnet/version.json");
if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
$platform = "StatusNet";
// Remove junk that some GNU Social servers return
$version = str_replace(chr(239).chr(187).chr(191), "", $curlResult->getBody());
$version = trim($version, '"');
$network = Protocol::OSTATUS;
}
// Test for GNU Social
$curlResult = Network::curl($server_url."/api/gnusocial/version.json");
if ($curlResult->isSuccess() && ($curlResult->getBody() != '{"error":"not implemented"}') &&
($curlResult->getBody() != '') && (strlen($curlResult->getBody()) < 30)) {
$platform = "GNU Social";
// Remove junk that some GNU Social servers return
$version = str_replace(chr(239) . chr(187) . chr(191), "", $curlResult->getBody());
$version = trim($version, '"');
$network = Protocol::OSTATUS;
}
// Test for Mastodon
$orig_version = $version;
$curlResult = Network::curl($server_url . "/api/v1/instance");
if ($curlResult->isSuccess() && ($curlResult->getBody() != '')) {
$data = json_decode($curlResult->getBody(), true);
if (isset($data['version'])) {
$platform = "Mastodon";
$version = defaults($data, 'version', '');
$site_name = defaults($data, 'title', '');
$info = defaults($data, 'description', '');
$network = Protocol::OSTATUS;
}
if (!empty($data['stats']['user_count'])) {
$registered_users = $data['stats']['user_count'];
}
}
if (strstr($orig_version . $version, 'Pleroma')) {
$platform = 'Pleroma';
$version = trim(str_replace('Pleroma', '', $version));
}
}
if (!$failure) {
// Test for Hubzilla and Red
$curlResult = Network::curl($server_url . "/siteinfo.json");
if ($curlResult->isSuccess()) {
$data = json_decode($curlResult->getBody(), true);
if (isset($data['url'])) {
$platform = $data['platform'];
$version = $data['version'];
$network = Protocol::DIASPORA;
}
if (!empty($data['site_name'])) {
$site_name = $data['site_name'];
}
if (!empty($data['channels_total'])) {
$registered_users = $data['channels_total'];
}
if (!empty($data['register_policy'])) {
switch ($data['register_policy']) {
case "REGISTER_OPEN":
$register_policy = Register::OPEN;
break;
case "REGISTER_APPROVE":
$register_policy = Register::APPROVE;
break;
case "REGISTER_CLOSED":
default:
$register_policy = Register::CLOSED;
break;
}
}
} else {
// Test for Hubzilla, Redmatrix or Friendica
$curlResult = Network::curl($server_url."/api/statusnet/config.json");
if ($curlResult->isSuccess()) {
$data = json_decode($curlResult->getBody(), true);
if (isset($data['site']['server'])) {
if (isset($data['site']['platform'])) {
$platform = $data['site']['platform']['PLATFORM_NAME'];
$version = $data['site']['platform']['STD_VERSION'];
$network = Protocol::DIASPORA;
}
if (isset($data['site']['BlaBlaNet'])) {
$platform = $data['site']['BlaBlaNet']['PLATFORM_NAME'];
$version = $data['site']['BlaBlaNet']['STD_VERSION'];
$network = Protocol::DIASPORA;
}
if (isset($data['site']['hubzilla'])) {
$platform = $data['site']['hubzilla']['PLATFORM_NAME'];
$version = $data['site']['hubzilla']['RED_VERSION'];
$network = Protocol::DIASPORA;
}
if (isset($data['site']['redmatrix'])) {
if (isset($data['site']['redmatrix']['PLATFORM_NAME'])) {
$platform = $data['site']['redmatrix']['PLATFORM_NAME'];
} elseif (isset($data['site']['redmatrix']['RED_PLATFORM'])) {
$platform = $data['site']['redmatrix']['RED_PLATFORM'];
}
$version = $data['site']['redmatrix']['RED_VERSION'];
$network = Protocol::DIASPORA;
}
if (isset($data['site']['friendica'])) {
$platform = $data['site']['friendica']['FRIENDICA_PLATFORM'];
$version = $data['site']['friendica']['FRIENDICA_VERSION'];
$network = Protocol::DFRN;
}
$site_name = $data['site']['name'];
$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) {
$register_policy = Register::APPROVE;
} elseif (!$closed && !$private) {
$register_policy = Register::OPEN;
} else {
$register_policy = Register::CLOSED;
}
}
}
}
}
// Query statistics.json. Optional package for Diaspora, Friendica and Redmatrix
if (!$failure) {
$curlResult = Network::curl($server_url . "/statistics.json");
if ($curlResult->isSuccess()) {
$data = json_decode($curlResult->getBody(), true);
if (isset($data['version'])) {
$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.
$version = preg_replace("=(.+)-(.{4,})=ism", "$1", $version);
}
if (!empty($data['name'])) {
$site_name = $data['name'];
}
if (!empty($data['network'])) {
$platform = $data['network'];
}
if ($platform == "Diaspora") {
$network = Protocol::DIASPORA;
}
if (!empty($data['registrations_open']) && $data['registrations_open']) {
$register_policy = Register::OPEN;
} else {
$register_policy = Register::CLOSED;
}
}
}
// Query nodeinfo. Working for (at least) Diaspora and Friendica.
if (!$failure) {
$server = self::fetchNodeinfo($server_url);
if (!empty($server)) {
$register_policy = $server['register_policy'];
if (isset($server['platform'])) {
$platform = $server['platform'];
}
if (isset($server['network'])) {
$network = $server['network'];
}
if (isset($server['version'])) {
$version = $server['version'];
}
if (isset($server['site_name'])) {
$site_name = $server['site_name'];
}
if (isset($server['registered-users'])) {
$registered_users = $server['registered-users'];
}
}
}
// Check for noscrape
// Friendica servers could be detected as OStatus servers
if (!$failure && in_array($network, [Protocol::DFRN, Protocol::OSTATUS])) {
$curlResult = Network::curl($server_url . "/friendica/json");
if (!$curlResult->isSuccess()) {
$curlResult = Network::curl($server_url . "/friendika/json");
}
if ($curlResult->isSuccess()) {
$data = json_decode($curlResult->getBody(), true);
if (isset($data['version'])) {
$network = Protocol::DFRN;
if (!empty($data['no_scrape_url'])) {
$noscrape = $data['no_scrape_url'];
}
$version = $data['version'];
if (!empty($data['site_name'])) {
$site_name = $data['site_name'];
}
$info = defaults($data, 'info', '');
$register_policy = defaults($data, 'register_policy', 'REGISTER_CLOSED');
switch ($register_policy) {
case 'REGISTER_OPEN':
$register_policy = Register::OPEN;
break;
case 'REGISTER_APPROVE':
$register_policy = Register::APPROVE;
break;
default:
Logger::log("Register policy '$register_policy' from $server_url is invalid.");
// Defaulting to closed
case 'REGISTER_CLOSED':
case 'REGISTER_INVITATION':
$register_policy = Register::CLOSED;
break;
}
$platform = defaults($data, 'platform', '');
}
}
}
// Every server has got at least an admin account
if (!$failure && ($registered_users == 0)) {
$registered_users = 1;
}
if ($possible_failure && !$failure) {
$failure = true;
}
if ($failure) {
$last_contact = $orig_last_contact;
$last_failure = DateTimeFormat::utcNow();
} else {
$last_contact = DateTimeFormat::utcNow();
$last_failure = $orig_last_failure;
}
if (($last_contact <= $last_failure) && !$failure) {
Logger::log("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", Logger::DEBUG);
} elseif (($last_contact >= $last_failure) && $failure) {
Logger::log("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", Logger::DEBUG);
}
// Check again if the server exists
$found = DBA::exists('gserver', ['nurl' => Strings::normaliseLink($server_url)]);
$version = strip_tags($version);
$site_name = strip_tags($site_name);
$info = strip_tags($info);
$platform = strip_tags($platform);
$fields = ['url' => $server_url, 'version' => $version,
'site_name' => $site_name, 'info' => $info, 'register_policy' => $register_policy,
'poco' => $poco, 'noscrape' => $noscrape, 'network' => $network,
'platform' => $platform, 'registered-users' => $registered_users,
'last_contact' => $last_contact, 'last_failure' => $last_failure];
if ($found) {
DBA::update('gserver', $fields, ['nurl' => Strings::normaliseLink($server_url)]);
} elseif (!$failure) {
$fields['nurl'] = Strings::normaliseLink($server_url);
$fields['created'] = DateTimeFormat::utcNow();
DBA::insert('gserver', $fields);
}
if (!$failure && in_array($fields['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
self::discoverRelay($server_url);
}
Logger::log("End discovery for server " . $server_url, Logger::DEBUG);
return !$failure;
}
/**
* @brief Fetch relay data from a given server url
*
* @param string $server_url address of the server
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
private static function discoverRelay($server_url)
{
Logger::log("Discover relay data for server " . $server_url, Logger::DEBUG);
$curlResult = Network::curl($server_url . "/.well-known/x-social-relay");
if (!$curlResult->isSuccess()) {
return;
}
$data = json_decode($curlResult->getBody(), true);
if (!is_array($data)) {
return;
}
$gserver = DBA::selectFirst('gserver', ['id', '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']];
DBA::update('gserver', $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) {
DBA::insert('gserver-tag', ['gserver-id' => $gserver['id'], 'tag' => $tag], true);
}
}
// 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'];
}
}
}
Diaspora::setRelayContact($server_url, $fields);
}
/** /**
* @brief Returns a list of all known servers * @brief Returns a list of all known servers
* @return array List of server urls * @return array List of server urls
@ -1577,7 +636,7 @@ class PortableContact
// $servers = json_decode($result->getBody(), true); // $servers = json_decode($result->getBody(), true);
// foreach($servers['data'] as $server) // foreach($servers['data'] as $server)
// self::checkServer($server['instance_address']); // GServer::check($server['instance_address']);
// } // }
//} //}
@ -1646,7 +705,7 @@ class PortableContact
return true; return true;
} else { } else {
// If the server hadn't replied correctly, then force a sanity check // If the server hadn't replied correctly, then force a sanity check
self::checkServer($server["url"], $server["network"], true); GServer::check($server["url"], true);
// If we couldn't reach the server, we will try it some time later // If we couldn't reach the server, we will try it some time later
$fields = ['last_poco_query' => DateTimeFormat::utcNow()]; $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
@ -1681,7 +740,7 @@ class PortableContact
if (DBA::isResult($gservers)) { if (DBA::isResult($gservers)) {
foreach ($gservers as $gserver) { foreach ($gservers as $gserver) {
if (!self::checkServer($gserver['url'], $gserver['network'])) { if (!GServer::check($gserver['url'])) {
// The server is not reachable? Okay, then we will try it later // The server is not reachable? Okay, then we will try it later
$fields = ['last_poco_query' => DateTimeFormat::utcNow()]; $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]); DBA::update('gserver', $fields, ['nurl' => $gserver['nurl']]);

View file

@ -12,6 +12,7 @@ use Friendica\Core\Worker;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Model\GContact; use Friendica\Model\GContact;
use Friendica\Model\Contact; use Friendica\Model\Contact;
use Friendica\Model\GServer;
use Friendica\Network\Probe; use Friendica\Network\Probe;
use Friendica\Protocol\PortableContact; use Friendica\Protocol\PortableContact;
use Friendica\Util\DateTimeFormat; use Friendica\Util\DateTimeFormat;
@ -86,7 +87,7 @@ class DiscoverPoCo
return; return;
} }
$result = "Checking server ".$server_url." - "; $result = "Checking server ".$server_url." - ";
$ret = PortableContact::checkServer($server_url); $ret = GServer::check($server_url);
if ($ret) { if ($ret) {
$result .= "success"; $result .= "success";
} else { } else {
@ -186,7 +187,7 @@ class DiscoverPoCo
$server_url = $user["server_url"]; $server_url = $user["server_url"];
} }
if ((($server_url == "") && ($user["network"] == Protocol::FEED)) || $force_update || PortableContact::checkServer($server_url, $user["network"])) { if ((($server_url == "") && ($user["network"] == Protocol::FEED)) || $force_update || GServer::check($server_url)) {
Logger::log('Check profile '.$user["url"]); Logger::log('Check profile '.$user["url"]);
Worker::add(PRIORITY_LOW, "DiscoverPoCo", "check_profile", $user["url"]); Worker::add(PRIORITY_LOW, "DiscoverPoCo", "check_profile", $user["url"]);
@ -237,7 +238,7 @@ class DiscoverPoCo
$server_url = Contact::getBasepath($jj->url); $server_url = Contact::getBasepath($jj->url);
if ($server_url != '') { if ($server_url != '') {
if (!PortableContact::checkServer($server_url)) { if (!GServer::check($server_url)) {
Logger::log("Friendica server ".$server_url." doesn't answer.", Logger::DEBUG); Logger::log("Friendica server ".$server_url." doesn't answer.", Logger::DEBUG);
continue; continue;
} }

View file

@ -9,6 +9,7 @@ use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Model\PushSubscriber; use Friendica\Model\PushSubscriber;
use Friendica\Model\GServer;
use Friendica\Protocol\OStatus; use Friendica\Protocol\OStatus;
use Friendica\Util\Network; use Friendica\Util\Network;
@ -30,7 +31,7 @@ class PubSubPublish
return; return;
} }
/// @todo Check server status with PortableContact::checkServer() /// @todo Check server status with GServer::check()
// Before this can be done we need a way to safely detect the server url. // Before this can be done we need a way to safely detect the server url.
Logger::log("Generate feed of user " . $subscriber['nickname']. " to " . $subscriber['callback_url']. " - last updated " . $subscriber['last_update'], Logger::DEBUG); Logger::log("Generate feed of user " . $subscriber['nickname']. " to " . $subscriber['callback_url']. " - last updated " . $subscriber['last_update'], Logger::DEBUG);