Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1752 lines
48 KiB

<?php
/**
* @file src/Network/Probe.php
*/
namespace Friendica\Network;
/**
* @file src/Network/Probe.php
* @brief Functions for probing URL
*/
use DOMDocument;
use Friendica\Core\Cache;
use Friendica\Core\Config;
use Friendica\Core\Logger;
use Friendica\Core\Protocol;
use Friendica\Core\System;
use Friendica\Database\DBA;
use Friendica\Model\Contact;
use Friendica\Model\Profile;
use Friendica\Protocol\Email;
use Friendica\Protocol\Feed;
use Friendica\Protocol\ActivityPub;
use Friendica\Util\Crypto;
use Friendica\Util\DateTimeFormat;
use Friendica\Util\Network;
use Friendica\Util\Strings;
use Friendica\Util\XML;
use DomXPath;
/**
* @brief This class contain functions for probing URL
*
*/
class Probe
{
private static $baseurl;
/**
* @brief Rearrange the array so that it always has the same order
*
* @param array $data Unordered data
*
* @return array Ordered data
*/
private static function rearrangeData($data)
{
$fields = ["name", "nick", "guid", "url", "addr", "alias",
"photo", "community", "keywords", "location", "about",
"batch", "notify", "poll", "request", "confirm", "poco",
"priority", "network", "pubkey", "baseurl"];
$newdata = [];
foreach ($fields as $field) {
if (isset($data[$field])) {
$newdata[$field] = $data[$field];
} else {
$newdata[$field] = "";
}
}
// We don't use the "priority" field anymore and replace it with a dummy.
$newdata["priority"] = 0;
return $newdata;
}
/**
* @brief Check if the hostname belongs to the own server
*
* @param string $host The hostname that is to be checked
*
* @return bool Does the testes hostname belongs to the own server?
*/
private static function ownHost($host)
{
$own_host = \get_app()->getHostName();
$parts = parse_url($host);
if (!isset($parts['scheme'])) {
$parts = parse_url('http://'.$host);
}
if (!isset($parts['host'])) {
return false;
}
return $parts['host'] == $own_host;
}
/**
* @brief Probes for webfinger path via "host-meta"
*
* We have to check if the servers in the future still will offer this.
* It seems as if it was dropped from the standard.
*
* @param string $host The host part of an url
*
* @return array with template and type of the webfinger template for JSON or XML
* @throws HTTPException\InternalServerErrorException
*/
private static function hostMeta($host)
{
// Reset the static variable
self::$baseurl = '';
$ssl_url = "https://".$host."/.well-known/host-meta";
$url = "http://".$host."/.well-known/host-meta";
$xrd_timeout = Config::get('system', 'xrd_timeout', 20);
$redirects = 0;
Logger::log("Probing for ".$host, Logger::DEBUG);
$xrd = null;
$curlResult = Network::curl($ssl_url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
if ($curlResult->isSuccess()) {
$xml = $curlResult->getBody();
$xrd = XML::parseString($xml, false);
$host_url = 'https://'.$host;
}
if (!is_object($xrd)) {
$curlResult = Network::curl($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
if ($curlResult->isTimeout()) {
Logger::log("Probing timeout for " . $url, Logger::DEBUG);
return false;
}
$xml = $curlResult->getBody();
$xrd = XML::parseString($xml, false);
$host_url = 'http://'.$host;
}
if (!is_object($xrd)) {
Logger::log("No xrd object found for ".$host, Logger::DEBUG);
return [];
}
$links = XML::elementToArray($xrd);
if (!isset($links["xrd"]["link"])) {
Logger::log("No xrd data found for ".$host, Logger::DEBUG);
return [];
}
$lrdd = [];
// The following webfinger path is defined in RFC 7033 https://tools.ietf.org/html/rfc7033
// Problem is that Hubzilla currently doesn't provide all data in the JSON webfinger
// compared to the XML webfinger. So this is commented out by now.
// $lrdd = array("application/jrd+json" => $host_url.'/.well-known/webfinger?resource={uri}');
foreach ($links["xrd"]["link"] as $value => $link) {
if (!empty($link["@attributes"])) {
$attributes = $link["@attributes"];
} elseif ($value == "@attributes") {
$attributes = $link;
} else {
continue;
}
if (($attributes["rel"] == "lrdd") && !empty($attributes["template"])) {
$type = (empty($attributes["type"]) ? '' : $attributes["type"]);
$lrdd[$type] = $attributes["template"];
}
}
self::$baseurl = $host_url;
Logger::log("Probing successful for ".$host, Logger::DEBUG);
return $lrdd;
}
/**
* @brief Perform Webfinger lookup and return DFRN data
*
* Given an email style address, perform webfinger lookup and
* return the resulting DFRN profile URL, or if no DFRN profile URL
* is located, returns an OStatus subscription template (prefixed
* with the string 'stat:' to identify it as on OStatus template).
* If this isn't an email style address just return $webbie.
* Return an empty string if email-style addresses but webfinger fails,
* or if the resultant personal XRD doesn't contain a supported
* subscription/friend-request attribute.
*
* amended 7/9/2011 to return an hcard which could save potentially loading
* a lengthy content page to scrape dfrn attributes
*
* @param string $webbie Address that should be probed
* @param string $hcard_url Link to the hcard - is returned by reference
*
* @return string profile link
* @throws HTTPException\InternalServerErrorException
*/
public static function webfingerDfrn($webbie, &$hcard_url)
{
$profile_link = '';
$links = self::lrdd($webbie);
Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA);
if (count($links)) {
foreach ($links as $link) {
if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
$profile_link = $link['@attributes']['href'];
}
if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) && ($profile_link == "")) {
$profile_link = 'stat:'.$link['@attributes']['template'];
}
if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
$hcard_url = $link['@attributes']['href'];
}
}
}
return $profile_link;
}
/**
* @brief Check an URI for LRDD data
*
* this is a replacement for the "lrdd" function.
* It isn't used in this class and has some redundancies in the code.
* When time comes we can check the existing calls for "lrdd" if we can rework them.
*
* @param string $uri Address that should be probed
*
* @return array uri data
* @throws HTTPException\InternalServerErrorException
*/
public static function lrdd($uri)
{
$lrdd = self::hostMeta($uri);
$webfinger = null;
if (is_bool($lrdd)) {
return [];
}
if (!$lrdd) {
$parts = @parse_url($uri);
if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
return [];
}
$host = $parts["host"];
if (!empty($parts["port"])) {
$host .= ':'.$parts["port"];
}
$path_parts = explode("/", trim($parts["path"], "/"));
$nick = array_pop($path_parts);
do {
$lrdd = self::hostMeta($host);
$host .= "/".array_shift($path_parts);
} while (!$lrdd && (sizeof($path_parts) > 0));
}
if (!$lrdd) {
Logger::log("No lrdd data found for ".$uri, Logger::DEBUG);
return [];
}
foreach ($lrdd as $type => $template) {
if ($webfinger) {
continue;
}
$path = str_replace('{uri}', urlencode($uri), $template);
$webfinger = self::webfinger($path, $type);
if (!$webfinger && (strstr($uri, "@"))) {
$path = str_replace('{uri}', urlencode("acct:".$uri), $template);
$webfinger = self::webfinger($path, $type);
}
// Special treatment for Mastodon
// Problem is that Mastodon uses an URL format like http://domain.tld/@nick
// But the webfinger for this format fails.
if (!$webfinger && !empty($nick)) {
// Mastodon uses a "@" as prefix for usernames in their url format
$nick = ltrim($nick, '@');
$addr = $nick."@".$host;
$path = str_replace('{uri}', urlencode("acct:".$addr), $template);
$webfinger = self::webfinger($path, $type);
}
}
if (!is_array($webfinger["links"])) {
Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
return false;
}
$data = [];
foreach ($webfinger["links"] as $link) {
$data[] = ["@attributes" => $link];
}
if (is_array($webfinger["aliases"])) {
foreach ($webfinger["aliases"] as $alias) {
$data[] = ["@attributes" =>
["rel" => "alias",
"href" => $alias]];
}
}
return $data;
}
/**
* @brief Fetch information (protocol endpoints and user information) about a given uri
*
* @param string $uri Address that should be probed
* @param string $network Test for this specific network
* @param integer $uid User ID for the probe (only used for mails)
* @param boolean $cache Use cached values?
*
* @return array uri data
* @throws HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
public static function uri($uri, $network = '', $uid = -1, $cache = true)
{
if ($cache) {
$result = Cache::get('Probe::uri:' . $network . ':' . $uri);
if (!is_null($result)) {
return $result;
}
5 years ago
}
if ($uid == -1) {
$uid = local_user();
}
if ($network != Protocol::ACTIVITYPUB) {
$data = self::detect($uri, $network, $uid);
} else {
$data = null;
}
$ap_profile = ActivityPub::probeProfile($uri);
if (!empty($ap_profile) && (defaults($data, 'network', '') != Protocol::DFRN)) {
$data = $ap_profile;
}
if (!isset($data['url'])) {
$data['url'] = $uri;
}
if (!empty($data['photo'])) {
$data['baseurl'] = Network::getUrlMatch(Strings::normaliseLink(defaults($data, 'baseurl', '')), Strings::normaliseLink($data['photo']));
} else {
$data['photo'] = System::baseUrl() . '/images/person-300.jpg';
}
if (empty($data['name'])) {
if (!empty($data['nick'])) {
$data['name'] = $data['nick'];
}
if (empty($data['name'])) {
$data['name'] = $data['url'];
}
}
if (empty($data['nick'])) {
$data['nick'] = strtolower($data['name']);
if (strpos($data['nick'], ' ')) {
$data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
}
}
if (!empty(self::$baseurl)) {
$data['baseurl'] = self::$baseurl;
}
if (empty($data['network'])) {
$data['network'] = Protocol::PHANTOM;
}
$data = self::rearrangeData($data);
5 years ago
// Only store into the cache if the value seems to be valid
if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
Cache::set('Probe::uri:' . $network . ':' . $uri, $data, Cache::DAY);
5 years ago
/// @todo temporary fix - we need a real contact update function that updates only changing fields
/// The biggest problem is the avatar picture that could have a reduced image size.
/// It should only be updated if the existing picture isn't existing anymore.
/// We only update the contact when it is no probing for a specific network.
if (($data['network'] != Protocol::FEED)
&& ($network == '')
&& $data['name']
&& $data['nick']
&& $data['url']
&& $data['addr']
&& $data['poll']
) {
$fields = [
'name' => $data['name'],
'nick' => $data['nick'],
'url' => $data['url'],
'addr' => $data['addr'],
'photo' => $data['photo'],
'keywords' => $data['keywords'],
'location' => $data['location'],
'about' => $data['about'],
'notify' => $data['notify'],
'network' => $data['network'],
'server_url' => $data['baseurl']
];
// This doesn't cover the case when a community isn't a community anymore
if (!empty($data['community']) && $data['community']) {
$fields['community'] = $data['community'];
$fields['contact-type'] = Contact::TYPE_COMMUNITY;
}
$fieldnames = [];
foreach ($fields as $key => $val) {
if (empty($val)) {
unset($fields[$key]);
} else {
$fieldnames[] = $key;
}
}
$fields['updated'] = DateTimeFormat::utcNow();
$condition = ['nurl' => Strings::normaliseLink($data['url'])];
$old_fields = DBA::selectFirst('gcontact', $fieldnames, $condition);
// When the gcontact doesn't exist, the value "true" will trigger an insert.
// In difference to the public contacts we want to have every contact
// in the world in our global contacts.
if (!$old_fields) {
$old_fields = true;
// These values have to be set only on insert
$fields['photo'] = $data['photo'];
$fields['created'] = DateTimeFormat::utcNow();
}
DBA::update('gcontact', $fields, $condition, $old_fields);
$fields = [
'name' => $data['name'],
'nick' => $data['nick'],
'url' => $data['url'],
'addr' => $data['addr'],
'alias' => $data['alias'],
'keywords' => $data['keywords'],
'location' => $data['location'],
'about' => $data['about'],
'batch' => $data['batch'],
'notify' => $data['notify'],
'poll' => $data['poll'],
'request' => $data['request'],
'confirm' => $data['confirm'],
'poco' => $data['poco'],
'network' => $data['network'],
'pubkey' => $data['pubkey'],
'priority' => $data['priority'],
'writable' => true,
'rel' => Contact::SHARING
];
$fieldnames = [];
foreach ($fields as $key => $val) {
if (empty($val)) {
unset($fields[$key]);
} else {
$fieldnames[] = $key;
}
}
$condition = ['nurl' => Strings::normaliseLink($data['url']), 'self' => false, 'uid' => 0];
// "$old_fields" will return a "false" when the contact doesn't exist.
// This won't trigger an insert. This is intended, since we only need
// public contacts for everyone we store items from.
// We don't need to store every contact on the planet.
$old_fields = DBA::selectFirst('contact', $fieldnames, $condition);
$fields['name-date'] = DateTimeFormat::utcNow();
$fields['uri-date'] = DateTimeFormat::utcNow();
$fields['success_update'] = DateTimeFormat::utcNow();
DBA::update('contact', $fields, $condition, $old_fields);
}
5 years ago
}
return $data;
}
/**
* @brief Switch the scheme of an url between http and https
*
* @param string $url URL
*
* @return string switched URL
*/
private static function switchScheme($url)
{
$parts = parse_url($url);
if (!isset($parts['scheme'])) {
return $url;
}
if ($parts['scheme'] == 'http') {
$url = str_replace('http://', 'https://', $url);
} elseif ($parts['scheme'] == 'https') {
$url = str_replace('https://', 'http://', $url);
}
return $url;
}
/**
* @brief Checks if a profile url should be OStatus but only provides partial information
*
* @param array $webfinger Webfinger data
* @param string $lrdd Path template for webfinger request
* @param string $type type
*
* @return array fixed webfinger data
* @throws HTTPException\InternalServerErrorException
*/
private static function fixOStatus($webfinger, $lrdd, $type)
{
if (empty($webfinger['links']) || empty($webfinger['subject'])) {
return $webfinger;
}
$is_ostatus = false;
$has_key = false;
foreach ($webfinger['links'] as $link) {
if ($link['rel'] == NAMESPACE_OSTATUSSUB) {
$is_ostatus = true;
}
if ($link['rel'] == 'magic-public-key') {
$has_key = true;
}
}
if (!$is_ostatus || $has_key) {
return $webfinger;
}
$url = self::switchScheme($webfinger['subject']);
$path = str_replace('{uri}', urlencode($url), $lrdd);
$webfinger2 = self::webfinger($path, $type);
// Is the new webfinger detectable as OStatus?
if (self::ostatus($webfinger2, true)) {
$webfinger = $webfinger2;
}
return $webfinger;
}
/**
* @brief Fetch information (protocol endpoints and user information) about a given uri
*
* This function is only called by the "uri" function that adds caching and rearranging of data.
*
* @param string $uri Address that should be probed
* @param string $network Test for this specific network
* @param integer $uid User ID for the probe (only used for mails)
*
* @return array uri data
* @throws HTTPException\InternalServerErrorException
*/
private static function detect($uri, $network, $uid)
{
$parts = parse_url($uri);
if (!empty($parts["scheme"]) && !empty($parts["host"])) {
$host = $parts["host"];
if (!empty($parts["port"])) {
$host .= ':'.$parts["port"];
}
if ($host == 'twitter.com') {
return ["network" => Protocol::TWITTER];
}
$lrdd = self::hostMeta($host);
if (is_bool($lrdd)) {
return [];
}
$path_parts = explode("/", trim(defaults($parts, 'path', ''), "/"));
while (!$lrdd && (sizeof($path_parts) > 1)) {
$host .= "/".array_shift($path_parts);
$lrdd = self::hostMeta($host);
}
if (!$lrdd) {
Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
return self::feed($uri);
}
$nick = array_pop($path_parts);
// Mastodon uses a "@" as prefix for usernames in their url format
$nick = ltrim($nick, '@');
$addr = $nick."@".$host;
} elseif (strstr($uri, '@')) {
// If the URI starts with "mailto:" then jump directly to the mail detection
if (strpos($uri, 'mailto:') !== false) {
$uri = str_replace('mailto:', '', $uri);
return self::mail($uri, $uid);
}
if ($network == Protocol::MAIL) {
return self::mail($uri, $uid);
}
// Remove "acct:" from the URI
$uri = str_replace('acct:', '', $uri);
$host = substr($uri, strpos($uri, '@') + 1);
$nick = substr($uri, 0, strpos($uri, '@'));
if (strpos($uri, '@twitter.com')) {
return ["network" => Protocol::TWITTER];
}
$lrdd = self::hostMeta($host);
if (is_bool($lrdd)) {
return [];
}
if (!$lrdd) {
Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
return self::mail($uri, $uid);
}
$addr = $uri;
} else {
Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
return false;
}
$webfinger = false;
/// @todo Do we need the prefix "acct:" or "acct://"?
foreach ($lrdd as $type => $template) {
if ($webfinger) {
continue;
}
// At first try it with the given uri
$path = str_replace('{uri}', urlencode($uri), $template);
$webfinger = self::webfinger($path, $type);
// Fix possible problems with GNU Social probing to wrong scheme
$webfinger = self::fixOStatus($webfinger, $template, $type);
// We cannot be sure that the detected address was correct, so we don't use the values
if ($webfinger && ($uri != $addr)) {
$nick = "";
$addr = "";
}
// Try webfinger with the address (user@domain.tld)
if (!$webfinger) {
$path = str_replace('{uri}', urlencode($addr), $template);
$webfinger = self::webfinger($path, $type);
}
// Mastodon needs to have it with "acct:"
if (!$webfinger) {
$path = str_replace('{uri}', urlencode("acct:".$addr), $template);
$webfinger = self::webfinger($path, $type);
}
}
if (!$webfinger) {
return self::feed($uri);
}
$result = false;
Logger::log("Probing ".$uri, Logger::DEBUG);
5 years ago
if (in_array($network, ["", Protocol::DFRN])) {
$result = self::dfrn($webfinger);
}
if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
$result = self::diaspora($webfinger);
}
if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
$result = self::ostatus($webfinger);
}
if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
$result = self::pumpio($webfinger, $addr);
}
if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
$result = self::feed($uri);
} else {
// We overwrite the detected nick with our try if the previois routines hadn't detected it.
// Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
$result["nick"] = $nick;
}
if (empty($result["addr"]) && ($addr != "")) {
$result["addr"] = $addr;
}
}
if (empty($result["network"])) {
$result["network"] = Protocol::PHANTOM;
}
if (empty($result["url"])) {
$result["url"] = $uri;
}
Logger::log($uri." is ".$result["network"], Logger::DEBUG);
5 years ago
if (empty($result["baseurl"])) {
$pos = strpos($result["url"], $host);
if ($pos) {
$result["baseurl"] = substr($result["url"], 0, $pos).$host;
}
}
return $result;
}
/**
* @brief Perform a webfinger request.
*
* For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
*
* @param string $url Address that should be probed
* @param string $type type
*
* @return array webfinger data
* @throws HTTPException\InternalServerErrorException
*/
private static function webfinger($url, $type)
{
$xrd_timeout = Config::get('system', 'xrd_timeout', 20);
$redirects = 0;