3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Network;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
33 use Friendica\Model\Contact;
34 use Friendica\Model\GServer;
35 use Friendica\Model\Profile;
36 use Friendica\Model\User;
37 use Friendica\Network\HTTPClient\Client\HttpClient;
38 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
39 use Friendica\Protocol\ActivityNamespace;
40 use Friendica\Protocol\ActivityPub;
41 use Friendica\Protocol\Email;
42 use Friendica\Protocol\Feed;
43 use Friendica\Util\Crypto;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\Network;
46 use Friendica\Util\Strings;
47 use Friendica\Util\XML;
48 use GuzzleHttp\Psr7\Uri;
51 * This class contain functions for probing URL
55 const WEBFINGER = '/.well-known/webfinger?resource={uri}';
57 private static $baseurl;
58 private static $istimeout;
61 * Remove stuff from an URI that doesn't belong there
63 * @param string $rawUri
64 * @return string Cleaned URI
66 public static function cleanURI(string $rawUri): string
68 // At first remove leading and trailing junk
69 $rawUri = trim($rawUri, "@#?:/ \t\n\r\0\x0B");
71 $uri = new Uri($rawUri);
72 if (!$uri->getScheme()) {
73 return $uri->__toString();
76 // Remove the URL fragment, since these shouldn't be part of any profile URL
77 $uri = $uri->withFragment('');
79 return $uri->__toString();
83 * Rearrange the array so that it always has the same order
85 * @param array $data Unordered data
87 * @return array Ordered data
89 private static function rearrangeData($data)
91 $fields = ["name", "nick", "guid", "url", "addr", "alias", "photo", "header",
92 "account-type", "community", "keywords", "location", "about", "xmpp", "matrix",
93 "hide", "batch", "notify", "poll", "request", "confirm", "subscribe", "poco",
94 "following", "followers", "inbox", "outbox", "sharedinbox",
95 "priority", "network", "pubkey", "manually-approve", "baseurl", "gsid"];
97 $numeric_fields = ["gsid", "hide", "account-type", "manually-approve"];
100 foreach ($fields as $field) {
101 if (isset($data[$field])) {
102 if (in_array($field, $numeric_fields)) {
103 $newdata[$field] = (int)$data[$field];
105 $newdata[$field] = $data[$field];
107 } elseif (!in_array($field, $numeric_fields)) {
108 $newdata[$field] = "";
110 $newdata[$field] = null;
114 // We don't use the "priority" field anymore and replace it with a dummy.
115 $newdata["priority"] = 0;
121 * Check if the hostname belongs to the own server
123 * @param string $host The hostname that is to be checked
125 * @return bool Does the testes hostname belongs to the own server?
127 private static function ownHost($host)
129 $own_host = DI::baseUrl()->getHostname();
131 $parts = parse_url($host);
133 if (!isset($parts['scheme'])) {
134 $parts = parse_url('http://'.$host);
137 if (!isset($parts['host'])) {
140 return $parts['host'] == $own_host;
144 * Probes for webfinger path via "host-meta"
146 * We have to check if the servers in the future still will offer this.
147 * It seems as if it was dropped from the standard.
149 * @param string $host The host part of an url
151 * @return array with template and type of the webfinger template for JSON or XML
152 * @throws HTTPException\InternalServerErrorException
154 private static function hostMeta($host)
156 // Reset the static variable
159 // Handles the case when the hostname contains the scheme
160 if (!parse_url($host, PHP_URL_SCHEME)) {
161 $ssl_url = "https://" . $host . "/.well-known/host-meta";
162 $url = "http://" . $host . "/.well-known/host-meta";
164 $ssl_url = $host . "/.well-known/host-meta";
168 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
170 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
173 $curlResult = DI::httpClient()->get($ssl_url, [HttpClientOptions::TIMEOUT => $xrd_timeout, HttpClientOptions::ACCEPT_CONTENT => HttpClient::ACCEPT_XRD_XML]);
174 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
175 if ($curlResult->isSuccess()) {
176 $xml = $curlResult->getBody();
177 $xrd = XML::parseString($xml, true);
179 $host_url = 'https://' . $host;
183 } elseif ($curlResult->isTimeout()) {
184 Logger::info('Probing timeout', ['url' => $ssl_url]);
185 self::$istimeout = true;
189 if (!is_object($xrd) && !empty($url)) {
190 $curlResult = DI::httpClient()->get($url, [HttpClientOptions::TIMEOUT => $xrd_timeout, HttpClientOptions::ACCEPT_CONTENT => HttpClient::ACCEPT_XRD_XML]);
191 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
192 if ($curlResult->isTimeout()) {
193 Logger::info('Probing timeout', ['url' => $url]);
194 self::$istimeout = true;
196 } elseif ($connection_error && $ssl_connection_error) {
197 self::$istimeout = true;
201 $xml = $curlResult->getBody();
202 $xrd = XML::parseString($xml, true);
203 $host_url = 'http://'.$host;
205 if (!is_object($xrd)) {
206 Logger::info('No xrd object found', ['host' => $host]);
210 $links = XML::elementToArray($xrd);
211 if (!isset($links["xrd"]["link"])) {
212 Logger::info('No xrd data found', ['host' => $host]);
218 foreach ($links["xrd"]["link"] as $value => $link) {
219 if (!empty($link["@attributes"])) {
220 $attributes = $link["@attributes"];
221 } elseif ($value == "@attributes") {
227 if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
228 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
230 $lrdd[$type] = $attributes["template"];
234 if (Network::isUrlBlocked($host_url)) {
235 Logger::info('Domain is blocked', ['url' => $host]);
239 self::$baseurl = $host_url;
241 Logger::info('Probing successful', ['host' => $host]);
247 * Perform Webfinger lookup and return DFRN data
249 * Given an email style address, perform webfinger lookup and
250 * return the resulting DFRN profile URL, or if no DFRN profile URL
251 * is located, returns an OStatus subscription template (prefixed
252 * with the string 'stat:' to identify it as on OStatus template).
253 * If this isn't an email style address just return $webbie.
254 * Return an empty string if email-style addresses but webfinger fails,
255 * or if the resultant personal XRD doesn't contain a supported
256 * subscription/friend-request attribute.
258 * amended 7/9/2011 to return an hcard which could save potentially loading
259 * a lengthy content page to scrape dfrn attributes
261 * @param string $webbie Address that should be probed
262 * @param string $hcard_url Link to the hcard - is returned by reference
264 * @return string profile link
265 * @throws HTTPException\InternalServerErrorException
267 public static function webfingerDfrn(string $webbie, string &$hcard_url)
271 $links = self::lrdd($webbie);
272 Logger::debug('Result', ['url' => $webbie, 'links' => $links]);
273 if (!empty($links) && is_array($links)) {
274 foreach ($links as $link) {
275 if ($link['@attributes']['rel'] === ActivityNamespace::DFRN) {
276 $profile_link = $link['@attributes']['href'];
278 if (($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) && ($profile_link == "")) {
279 $profile_link = 'stat:'.$link['@attributes']['template'];
281 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
282 $hcard_url = $link['@attributes']['href'];
286 return $profile_link;
290 * Check an URI for LRDD data
292 * @param string $uri Address that should be probed
294 * @return array uri data
295 * @throws HTTPException\InternalServerErrorException
297 public static function lrdd(string $uri)
299 $data = self::getWebfingerArray($uri);
303 $webfinger = $data['webfinger'];
305 if (empty($webfinger["links"])) {
306 Logger::info('No webfinger links found', ['uri' => $uri]);
312 foreach ($webfinger["links"] as $link) {
313 $data[] = ["@attributes" => $link];
316 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
317 foreach ($webfinger["aliases"] as $alias) {
318 $data[] = ["@attributes" =>
328 * Fetch information (protocol endpoints and user information) about a given uri
330 * @param string $uri Address that should be probed
331 * @param string $network Test for this specific network
332 * @param integer $uid User ID for the probe (only used for mails)
333 * @param boolean $cache Use cached values?
335 * @return array uri data
336 * @throws HTTPException\InternalServerErrorException
337 * @throws \ImagickException
339 public static function uri($uri, $network = '', $uid = -1)
341 // Local profiles aren't probed via network
342 if (empty($network) && Contact::isLocal($uri)) {
343 $data = self::localProbe($uri);
353 if (empty($network) || ($network == Protocol::ACTIVITYPUB)) {
354 $ap_profile = ActivityPub::probeProfile($uri);
359 self::$istimeout = false;
361 if ($network != Protocol::ACTIVITYPUB) {
362 $data = self::detect($uri, $network, $uid, $ap_profile);
363 if (!is_array($data)) {
366 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
368 } elseif (!empty($ap_profile)) {
369 $ap_profile['batch'] = '';
370 $data = array_merge($ap_profile, $data);
376 if (!isset($data['url'])) {
380 if (empty($data['photo'])) {
381 $data['photo'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
384 if (empty($data['name'])) {
385 if (!empty($data['nick'])) {
386 $data['name'] = $data['nick'];
389 if (empty($data['name'])) {
390 $data['name'] = $data['url'];
394 if (empty($data['nick'])) {
395 $data['nick'] = strtolower($data['name']);
397 if (strpos($data['nick'], ' ')) {
398 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
402 if (!empty($data['baseurl']) && empty($data['gsid'])) {
403 $data['gsid'] = GServer::getID($data['baseurl']);
406 if (empty($data['network'])) {
407 $data['network'] = Protocol::PHANTOM;
410 // Ensure that local connections always are DFRN
411 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
412 $data['network'] = Protocol::DFRN;
415 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
416 $data['hide'] = self::getHideStatus($data['url']);
419 return self::rearrangeData($data);
424 * Fetches the "hide" status from the profile
426 * @param string $url URL of the profile
428 * @return boolean "hide" status
430 private static function getHideStatus($url)
432 $curlResult = DI::httpClient()->get($url, [HttpClientOptions::CONTENT_LENGTH => 1000000, HttpClientOptions::ACCEPT_CONTENT => HttpClient::ACCEPT_HTML]);
433 if (!$curlResult->isSuccess()) {
437 // If it isn't a HTML file then exit
438 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
442 $body = $curlResult->getBody();
447 $doc = new DOMDocument();
448 @$doc->loadHTML($body);
450 $xpath = new DOMXPath($doc);
452 $list = $xpath->query('//meta[@name]');
453 foreach ($list as $node) {
455 if ($node->attributes->length) {
456 foreach ($node->attributes as $attribute) {
457 $meta_tag[$attribute->name] = $attribute->value;
461 if (empty($meta_tag['content'])) {
465 $content = strtolower(trim($meta_tag['content']));
467 switch (strtolower(trim($meta_tag['name']))) {
468 case 'dfrn-global-visibility':
469 if ($content == 'false') {
474 if (strpos($content, 'noindex') !== false) {
485 * Fetch the "subscribe" and add it to the result
487 * @param array $result
488 * @param array $webfinger
489 * @return array result
491 private static function getSubscribeLink(array $result, array $webfinger)
493 if (empty($webfinger['links'])) {
497 foreach ($webfinger['links'] as $link) {
498 if (!empty($link['template']) && ($link['rel'] === ActivityNamespace::OSTATUSSUB)) {
499 $result['subscribe'] = $link['template'];
507 * Get webfinger data from a given URI
511 * @throws HTTPException\InternalServerErrorException
513 private static function getWebfingerArray(string $uri): array
515 $parts = parse_url($uri);
517 if (!empty($parts['scheme']) && !empty($parts['host'])) {
518 $host = $parts['host'];
519 if (!empty($parts['port'])) {
520 $host .= ':' . $parts['port'];
523 $baseurl = $parts['scheme'] . '://' . $host;
528 $path_parts = explode('/', trim($parts['path'] ?? '', '/'));
529 if (!empty($path_parts)) {
530 $nick = ltrim(end($path_parts), '@');
531 $addr = $nick . '@' . $host;
534 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClient::ACCEPT_JRD_JSON, $uri, $addr);
535 if (empty($webfinger)) {
536 $lrdd = self::hostMeta($host);
539 if (empty($webfinger) && empty($lrdd)) {
540 while (empty($lrdd) && empty($webfinger) && (sizeof($path_parts) > 1)) {
541 $host .= '/' . array_shift($path_parts);
542 $baseurl = $parts['scheme'] . '://' . $host;
545 $addr = $nick . '@' . $host;
548 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClient::ACCEPT_JRD_JSON, $uri, $addr);
549 if (empty($webfinger)) {
550 $lrdd = self::hostMeta($host);
554 if (empty($lrdd) && empty($webfinger)) {
558 } elseif (strstr($uri, '@')) {
559 // Remove "acct:" from the URI
560 $uri = str_replace('acct:', '', $uri);
562 $host = substr($uri, strpos($uri, '@') + 1);
563 $nick = substr($uri, 0, strpos($uri, '@'));
566 $webfinger = self::getWebfinger('https://' . $host . self::WEBFINGER, HttpClient::ACCEPT_JRD_JSON, $uri, $addr);
567 if (self::$istimeout) {
571 if (empty($webfinger)) {
572 $webfinger = self::getWebfinger('http://' . $host . self::WEBFINGER, HttpClient::ACCEPT_JRD_JSON, $uri, $addr);
573 if (self::$istimeout) {
577 $baseurl = 'https://' . $host;
580 if (empty($webfinger)) {
581 $lrdd = self::hostMeta($host);
582 if (self::$istimeout) {
585 $baseurl = self::$baseurl;
587 $baseurl = 'http://' . $host;
590 Logger::info('URI was not detectable', ['uri' => $uri]);
594 if (empty($webfinger)) {
595 foreach ($lrdd as $type => $template) {
600 $webfinger = self::getWebfinger($template, $type, $uri, $addr);
604 if (empty($webfinger)) {
608 if ($webfinger['detected'] == $addr) {
609 $webfinger['nick'] = $nick;
610 $webfinger['addr'] = $addr;
613 $webfinger['baseurl'] = $baseurl;
619 * Perform network request for webfinger data
621 * @param string $template
622 * @param string $type
624 * @param string $addr
625 * @return array webfinger results
627 private static function getWebfinger(string $template, string $type, string $uri, string $addr)
629 if (Network::isUrlBlocked($template)) {
630 Logger::info('Domain is blocked', ['url' => $template]);
634 // First try the address because this is the primary purpose of webfinger
637 $path = str_replace('{uri}', urlencode("acct:" . $addr), $template);
638 $webfinger = self::webfinger($path, $type);
639 if (self::$istimeout) {
645 if (empty($webfinger) && $uri != $addr) {
647 $path = str_replace('{uri}', urlencode($uri), $template);
648 $webfinger = self::webfinger($path, $type);
649 if (self::$istimeout) {
654 if (empty($webfinger)) {
658 return ['webfinger' => $webfinger, 'detected' => $detected];
662 * Fetch information (protocol endpoints and user information) about a given uri
664 * This function is only called by the "uri" function that adds caching and rearranging of data.
666 * @param string $uri Address that should be probed
667 * @param string $network Test for this specific network
668 * @param integer $uid User ID for the probe (only used for mails)
669 * @param array $ap_profile Previously probed AP profile
671 * @return array uri data
672 * @throws HTTPException\InternalServerErrorException
674 private static function detect(string $uri, string $network, int $uid, array $ap_profile)
678 'network' => $network,
683 Hook::callAll('probe_detect', $hookData);
685 if (isset($hookData['result'])) {
686 return is_array($hookData['result']) ? $hookData['result'] : [];
689 $parts = parse_url($uri);
690 if (empty($parts['scheme']) && empty($parts['host']) && !strstr($parts['path'], '@')) {
691 Logger::info('URI was not detectable', ['uri' => $uri]);
695 // If the URI starts with "mailto:" then jump directly to the mail detection
696 if (strpos($uri, 'mailto:') !== false) {
697 $uri = str_replace('mailto:', '', $uri);
698 return self::mail($uri, $uid);
701 if ($network == Protocol::MAIL) {
702 return self::mail($uri, $uid);
705 Logger::info('Probing start', ['uri' => $uri]);
707 if (!empty($ap_profile['addr']) && ($ap_profile['addr'] != $uri)) {
708 $data = self::getWebfingerArray($ap_profile['addr']);
712 $data = self::getWebfingerArray($uri);
716 if (!empty($parts['scheme'])) {
717 return self::feed($uri);
718 } elseif (!empty($uid)) {
719 return self::mail($uri, $uid);
725 $webfinger = $data['webfinger'];
726 $nick = $data['nick'] ?? '';
727 $addr = $data['addr'] ?? '';
728 $baseurl = $data['baseurl'] ?? '';
732 if (in_array($network, ["", Protocol::DFRN])) {
733 $result = self::dfrn($webfinger);
735 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
736 $result = self::diaspora($webfinger);
738 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
739 $result = self::ostatus($webfinger);
741 if (in_array($network, ['', Protocol::ZOT])) {
742 $result = self::zot($webfinger, $result, $baseurl);
744 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
745 $result = self::pumpio($webfinger, $addr);
747 if (empty($result['network']) && empty($ap_profile['network']) || ($network == Protocol::FEED)) {
748 $result = self::feed($uri);
750 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
751 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
752 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
753 $result["nick"] = $nick;
756 if (empty($result["addr"]) && ($addr != "")) {
757 $result["addr"] = $addr;
761 $result = self::getSubscribeLink($result, $webfinger);
763 if (empty($result["network"])) {
764 $result["network"] = Protocol::PHANTOM;
767 if (empty($result['baseurl']) && !empty($baseurl)) {
768 $result['baseurl'] = $baseurl;
771 if (empty($result["url"])) {
772 $result["url"] = $uri;
775 Logger::info('Probing done', ['uri' => $uri, 'network' => $result["network"]]);
781 * Check for Zot contact
783 * @param array $webfinger Webfinger data
784 * @param array $data previously probed data
786 * @return array Zot data
787 * @throws HTTPException\InternalServerErrorException
789 private static function zot($webfinger, $data, $baseurl)
791 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
792 foreach ($webfinger["aliases"] as $alias) {
793 if (substr($alias, 0, 5) == 'acct:') {
794 $data["addr"] = substr($alias, 5);
799 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
800 $data["addr"] = substr($webfinger["subject"], 5);
804 foreach ($webfinger['links'] as $link) {
805 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
806 $zot_url = $link['href'];
810 if (empty($zot_url) && !empty($data['addr']) && !empty($baseurl)) {
811 $condition = ['nurl' => Strings::normaliseLink($baseurl), 'platform' => ['hubzilla']];
812 if (!DBA::exists('gserver', $condition)) {
815 $zot_url = $baseurl . '/.well-known/zot-info?address=' . $data['addr'];
818 if (empty($zot_url)) {
822 $data = self::pollZot($zot_url, $data);
824 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
825 foreach ($webfinger['aliases'] as $alias) {
826 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
827 $data['alias'] = $alias;
835 public static function pollZot($url, $data)
837 // @todo Check if this endpoint might be queried via a POST
838 $curlResult = DI::httpClient()->get($url, [HttpClientOptions::ACCEPT_CONTENT => HttpClient::ACCEPT_DEFAULT]);
839 if ($curlResult->isTimeout()) {
842 $content = $curlResult->getBody();
847 $json = json_decode($content, true);
848 if (!is_array($json)) {
852 if (empty($data['network'])) {
853 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
854 $data['network'] = Protocol::ZOT;
855 } elseif (!isset($json['protocols'])) {
856 $data['network'] = Protocol::ZOT;
860 if (!empty($json['guid']) && empty($data['guid'])) {
861 $data['guid'] = $json['guid'];
863 if (!empty($json['key']) && empty($data['pubkey'])) {
864 $data['pubkey'] = $json['key'];
866 if (!empty($json['name'])) {
867 $data['name'] = $json['name'];
869 if (!empty($json['photo'])) {
870 $data['photo'] = $json['photo'];
871 if (!empty($json['photo_updated'])) {
872 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
875 if (!empty($json['address'])) {
876 $data['addr'] = $json['address'];
878 if (!empty($json['url'])) {
879 $data['url'] = $json['url'];
881 if (!empty($json['connections_url'])) {
882 $data['poco'] = $json['connections_url'];
884 if (isset($json['searchable'])) {
885 $data['hide'] = !$json['searchable'];
887 if (!empty($json['public_forum'])) {
888 $data['community'] = $json['public_forum'];
889 $data['account-type'] = User::PAGE_FLAGS_COMMUNITY;
892 if (!empty($json['profile'])) {
893 $profile = $json['profile'];
894 if (!empty($profile['description'])) {
895 $data['about'] = $profile['description'];
897 if (!empty($profile['keywords'])) {
898 $keywords = implode(', ', $profile['keywords']);
899 if (!empty($keywords)) {
900 $data['keywords'] = $keywords;
905 if (!empty($profile['region'])) {
906 $loc['region'] = $profile['region'];
908 if (!empty($profile['country'])) {
909 $loc['country-name'] = $profile['country'];
911 $location = Profile::formatLocation($loc);
912 if (!empty($location)) {
913 $data['location'] = $location;
921 * Perform a webfinger request.
923 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
925 * @param string $url Address that should be probed
926 * @param string $type type
928 * @return array webfinger data
929 * @throws HTTPException\InternalServerErrorException
931 public static function webfinger($url, $type)
933 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
935 $curlResult = DI::httpClient()->get($url, [HttpClientOptions::TIMEOUT => $xrd_timeout, HttpClientOptions::ACCEPT_CONTENT => $type]);
936 if ($curlResult->isTimeout()) {
937 self::$istimeout = true;
940 $data = $curlResult->getBody();
942 $webfinger = json_decode($data, true);
943 if (!empty($webfinger)) {
944 if (!isset($webfinger["links"])) {
945 Logger::info('No json webfinger links', ['url' => $url]);
951 // If it is not JSON, maybe it is XML
952 $xrd = XML::parseString($data, true);
953 if (!is_object($xrd)) {
954 Logger::info('No webfinger data retrievable', ['url' => $url]);
958 $xrd_arr = XML::elementToArray($xrd);
959 if (!isset($xrd_arr["xrd"]["link"])) {
960 Logger::info('No XML webfinger links', ['url' => $url]);
966 if (!empty($xrd_arr["xrd"]["subject"])) {
967 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
970 if (!empty($xrd_arr["xrd"]["alias"])) {
971 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
974 $webfinger["links"] = [];
976 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
977 if (!empty($data["@attributes"])) {
978 $attributes = $data["@attributes"];
979 } elseif ($value == "@attributes") {
985 $webfinger["links"][] = $attributes;
991 * Poll the Friendica specific noscrape page.
993 * "noscrape" is a faster alternative to fetch the data from the hcard.
994 * This functionality was originally created for the directory.
996 * @param string $noscrape_url Link to the noscrape page
997 * @param array $data The already fetched data
999 * @return array noscrape data
1000 * @throws HTTPException\InternalServerErrorException
1002 private static function pollNoscrape($noscrape_url, $data)
1004 $curlResult = DI::httpClient()->get($noscrape_url, [HttpClientOptions::ACCEPT_CONTENT => HttpClient::ACCEPT_JSON]);
1005 if ($curlResult->isTimeout()) {
1006 self::$istimeout = true;
1009 $content = $curlResult->getBody();
1011 Logger::info('Empty body', ['url' => $noscrape_url]);
1015 $json = json_decode($content, true);
1016 if (!is_array($json)) {
1017 Logger::info('No json data', ['url' => $noscrape_url]);
1021 if (!empty($json["fn"])) {
1022 $data["name"] = $json["fn"];
1025 if (!empty($json["addr"])) {
1026 $data["addr"] = $json["addr"];
1029 if (!empty($json["nick"])) {
1030 $data["nick"] = $json["nick"];
1033 if (!empty($json["guid"])) {
1034 $data["guid"] = $json["guid"];
1037 if (!empty($json["comm"])) {
1038 $data["community"] = $json["comm"];
1041 if (!empty($json["tags"])) {
1042 $keywords = implode(", ", $json["tags"]);
1043 if ($keywords != "") {
1044 $data["keywords"] = $keywords;
1048 $location = Profile::formatLocation($json);
1050 $data["location"] = $location;
1053 if (!empty($json["about"])) {
1054 $data["about"] = $json["about"];
1057 if (!empty($json["xmpp"])) {
1058 $data["xmpp"] = $json["xmpp"];
1061 if (!empty($json["matrix"])) {
1062 $data["matrix"] = $json["matrix"];
1065 if (!empty($json["key"])) {
1066 $data["pubkey"] = $json["key"];
1069 if (!empty($json["photo"])) {
1070 $data["photo"] = $json["photo"];
1073 if (!empty($json["dfrn-request"])) {
1074 $data["request"] = $json["dfrn-request"];
1077 if (!empty($json["dfrn-confirm"])) {
1078 $data["confirm"] = $json["dfrn-confirm"];
1081 if (!empty($json["dfrn-notify"])) {
1082 $data["notify"] = $json["dfrn-notify"];
1085 if (!empty($json["dfrn-poll"])) {
1086 $data["poll"] = $json["dfrn-poll"];
1089 if (isset($json["hide"])) {
1090 $data["hide"] = (bool)$json["hide"];
1092 $data["hide"] = false;
1099 * Check for valid DFRN data
1101 * @param array $data DFRN data
1103 * @return int Number of errors
1105 public static function validDfrn($data)
1108 if (!isset($data['key'])) {
1111 if (!isset($data['dfrn-request'])) {
1114 if (!isset($data['dfrn-confirm'])) {
1117 if (!isset($data['dfrn-notify'])) {
1120 if (!isset($data['dfrn-poll'])) {
1127 * Fetch data from a DFRN profile page and via "noscrape"
1129 * @param string $profile_link Link to the profile page
1131 * @return array profile data
1132 * @throws HTTPException\InternalServerErrorException
1133 * @throws \ImagickException
1135 public static function profile($profile_link)
1139 Logger::info('Check profile', ['link' => $profile_link]);
1141 // Fetch data via noscrape - this is faster
1142 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1143 $data = self::pollNoscrape($noscrape_url, $data);
1145 if (!isset($data["notify"])
1146 || !isset($data["confirm"])
1147 || !isset($data["request"])
1148 || !isset($data["poll"])
1149 || !isset($data["name"])
1150 || !isset($data["photo"])
1152 $data = self::pollHcard($profile_link, $data, true);
1157 if (empty($data["addr"]) || empty($data["nick"])) {
1158 $probe_data = self::uri($profile_link);
1159 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1160 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1163 $prof_data["addr"] = $data["addr"];
1164 $prof_data["nick"] = $data["nick"];
1165 $prof_data["dfrn-request"] = $data['request'] ?? null;
1166 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1167 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1168 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1169 $prof_data["photo"] = $data['photo'] ?? null;
1170 $prof_data["fn"] = $data['name'] ?? null;
1171 $prof_data["key"] = $data['pubkey'] ?? null;
1173 Logger::debug('Result', ['link' => $profile_link, 'data' => $prof_data]);
1179 * Check for DFRN contact
1181 * @param array $webfinger Webfinger data
1183 * @return array DFRN data
1184 * @throws HTTPException\InternalServerErrorException
1186 private static function dfrn($webfinger)
1190 // The array is reversed to take into account the order of preference for same-rel links
1191 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1192 foreach (array_reverse($webfinger["links"]) as $link) {
1193 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1194 $data["network"] = Protocol::DFRN;
1195 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1196 $data["poll"] = $link["href"];
1197 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1198 $data["url"] = $link["href"];
1199 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1200 $hcard_url = $link["href"];
1201 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1202 $data["poco"] = $link["href"];
1203 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1204 $data["photo"] = $link["href"];
1205 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1206 $data["baseurl"] = trim($link["href"], '/');
1207 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1208 $data["guid"] = $link["href"];
1209 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1210 $data["pubkey"] = base64_decode($link["href"]);
1212 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1213 if (strstr($data["pubkey"], 'RSA ')) {
1214 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1219 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1220 foreach ($webfinger["aliases"] as $alias) {
1221 if (empty($data["url"]) && !strstr($alias, "@")) {
1222 $data["url"] = $alias;
1223 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1224 $data["alias"] = $alias;
1225 } elseif (substr($alias, 0, 5) == 'acct:') {
1226 $data["addr"] = substr($alias, 5);
1231 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1232 $data["addr"] = substr($webfinger["subject"], 5);
1235 if (!isset($data["network"]) || ($hcard_url == "")) {
1239 // Fetch data via noscrape - this is faster
1240 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1241 $data = self::pollNoscrape($noscrape_url, $data);
1243 if (isset($data["notify"])
1244 && isset($data["confirm"])
1245 && isset($data["request"])
1246 && isset($data["poll"])
1247 && isset($data["name"])
1248 && isset($data["photo"])
1253 $data = self::pollHcard($hcard_url, $data, true);
1259 * Poll the hcard page (Diaspora and Friendica specific)
1261 * @param string $hcard_url Link to the hcard page
1262 * @param array $data The already fetched data
1263 * @param boolean $dfrn Poll DFRN specific data
1265 * @return array hcard data
1266 * @throws HTTPException\InternalServerErrorException
1268 private static function pollHcard($hcard_url, $data, $dfrn = false)
1270 $curlResult = DI::httpClient()->get($hcard_url, [HttpClientOptions::ACCEPT_CONTENT => HttpClient::ACCEPT_HTML]);
1271 if ($curlResult->isTimeout()) {
1272 self::$istimeout = true;
1275 $content = $curlResult->getBody();
1276 if (empty($content)) {
1280 $doc = new DOMDocument();
1281 if (!@$doc->loadHTML($content)) {
1285 $xpath = new DomXPath($doc);
1287 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1288 if (!is_object($vcards)) {
1292 if (!isset($data["baseurl"])) {
1293 $data["baseurl"] = "";
1296 if ($vcards->length > 0) {
1297 $vcard = $vcards->item(0);
1299 // We have to discard the guid from the hcard in favour of the guid from lrdd
1300 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1301 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1302 if (($search->length > 0) && empty($data["guid"])) {
1303 $data["guid"] = $search->item(0)->nodeValue;
1306 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1307 if ($search->length > 0) {
1308 $data["nick"] = $search->item(0)->nodeValue;
1311 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1312 if ($search->length > 0) {
1313 $data["name"] = $search->item(0)->nodeValue;
1316 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1317 if ($search->length > 0) {
1318 $data["searchable"] = $search->item(0)->nodeValue;
1321 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1322 if ($search->length > 0) {
1323 $data["pubkey"] = $search->item(0)->nodeValue;
1324 if (strstr($data["pubkey"], 'RSA ')) {
1325 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1329 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1330 if ($search->length > 0) {
1331 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1336 if (!empty($vcard)) {
1337 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1338 foreach ($photos as $photo) {
1340 foreach ($photo->attributes as $attribute) {
1341 $attr[$attribute->name] = trim($attribute->value);
1344 if (isset($attr["src"]) && isset($attr["width"])) {
1345 $avatar[$attr["width"]] = $attr["src"];
1348 // We don't have a width. So we just take everything that we got.
1349 // This is a Hubzilla workaround which doesn't send a width.
1350 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1351 $avatar[] = $attr["src"];
1356 if (sizeof($avatar)) {
1358 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1362 // Poll DFRN specific data
1363 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1364 if ($search->length > 0) {
1365 foreach ($search as $link) {
1366 //$data["request"] = $search->item(0)->nodeValue;
1368 foreach ($link->attributes as $attribute) {
1369 $attr[$attribute->name] = trim($attribute->value);
1372 $data[substr($attr["rel"], 5)] = $attr["href"];
1376 // Older Friendica versions had used the "uid" field differently than newer versions
1377 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1378 unset($data["guid"]);
1387 * Check for Diaspora contact
1389 * @param array $webfinger Webfinger data
1391 * @return array Diaspora data
1392 * @throws HTTPException\InternalServerErrorException
1394 private static function diaspora($webfinger)
1399 // The array is reversed to take into account the order of preference for same-rel links
1400 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1401 foreach (array_reverse($webfinger["links"]) as $link) {
1402 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1403 $hcard_url = $link["href"];
1404 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1405 $data["baseurl"] = trim($link["href"], '/');
1406 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1407 $data["guid"] = $link["href"];
1408 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1409 $data["url"] = $link["href"];
1410 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && empty($link["type"]) && !empty($link["href"])) {
1411 $profile_url = $link["href"];
1412 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1413 $data["poll"] = $link["href"];
1414 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1415 $data["poco"] = $link["href"];
1416 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1417 $data["notify"] = $link["href"];
1418 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1419 $data["pubkey"] = base64_decode($link["href"]);
1421 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1422 if (strstr($data["pubkey"], 'RSA ')) {
1423 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1428 if (empty($data["url"]) && !empty($profile_url)) {
1429 $data["url"] = $profile_url;
1432 if (empty($data["url"]) || empty($hcard_url)) {
1436 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1437 foreach ($webfinger["aliases"] as $alias) {
1438 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1439 $data["alias"] = $alias;
1440 } elseif (substr($alias, 0, 5) == 'acct:') {
1441 $data["addr"] = substr($alias, 5);
1446 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1447 $data["addr"] = substr($webfinger["subject"], 5);
1450 // Fetch further information from the hcard
1451 $data = self::pollHcard($hcard_url, $data);
1457 if (!empty($data["url"])
1458 && !empty($data["guid"])
1459 && !empty($data["baseurl"])
1460 && !empty($data["pubkey"])
1461 && !empty($hcard_url)
1463 $data["network"] = Protocol::DIASPORA;
1464 $data["manually-approve"] = false;
1466 // The Diaspora handle must always be lowercase
1467 if (!empty($data["addr"])) {
1468 $data["addr"] = strtolower($data["addr"]);
1471 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1472 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1473 $data["batch"] = $data["baseurl"] . "/receive/public";
1482 * Check for OStatus contact
1484 * @param array $webfinger Webfinger data
1485 * @param bool $short Short detection mode
1487 * @return array|bool OStatus data or "false" on error or "true" on short mode
1488 * @throws HTTPException\InternalServerErrorException
1490 private static function ostatus($webfinger, $short = false)
1494 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1495 foreach ($webfinger["aliases"] as $alias) {
1496 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1497 $data["addr"] = str_replace('acct:', '', $alias);
1502 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1503 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1505 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1508 if (!empty($webfinger["links"])) {
1509 // The array is reversed to take into account the order of preference for same-rel links
1510 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1511 foreach (array_reverse($webfinger["links"]) as $link) {
1512 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1513 && (($link["type"] ?? "") == "text/html")
1514 && ($link["href"] != "")
1516 $data["url"] = $data["alias"] = $link["href"];
1517 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1518 $data["notify"] = $link["href"];
1519 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1520 $data["poll"] = $link["href"];
1521 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1522 $pubkey = $link["href"];
1524 if (substr($pubkey, 0, 5) === 'data:') {
1525 if (strstr($pubkey, ',')) {
1526 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1528 $pubkey = substr($pubkey, 5);
1530 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1531 $curlResult = DI::httpClient()->get($pubkey, [HttpClientOptions::ACCEPT_CONTENT => HttpClient::ACCEPT_DEFAULT]);
1532 if ($curlResult->isTimeout()) {
1533 self::$istimeout = true;
1534 return $short ? false : [];
1536 $pubkey = $curlResult->getBody();
1539 $key = explode(".", $pubkey);
1541 if (sizeof($key) >= 3) {
1542 $m = Strings::base64UrlDecode($key[1]);
1543 $e = Strings::base64UrlDecode($key[2]);
1544 $data["pubkey"] = Crypto::meToPem($m, $e);
1550 if (isset($data["notify"]) && isset($data["pubkey"])
1551 && isset($data["poll"])
1552 && isset($data["url"])
1554 $data["network"] = Protocol::OSTATUS;
1555 $data["manually-approve"] = false;
1557 return $short ? false : [];
1564 // Fetch all additional data from the feed
1565 $curlResult = DI::httpClient()->get($data["poll"], [HttpClientOptions::ACCEPT_CONTENT => HttpClient::ACCEPT_FEED_XML]);
1566 if ($curlResult->isTimeout()) {
1567 self::$istimeout = true;
1570 $feed = $curlResult->getBody();
1571 $feed_data = Feed::import($feed);
1576 if (!empty($feed_data["header"]["author-name"])) {
1577 $data["name"] = $feed_data["header"]["author-name"];
1579 if (!empty($feed_data["header"]["author-nick"])) {
1580 $data["nick"] = $feed_data["header"]["author-nick"];
1582 if (!empty($feed_data["header"]["author-avatar"])) {
1583 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1585 if (!empty($feed_data["header"]["author-id"])) {
1586 $data["alias"] = $feed_data["header"]["author-id"];
1588 if (!empty($feed_data["header"]["author-location"])) {
1589 $data["location"] = $feed_data["header"]["author-location"];
1591 if (!empty($feed_data["header"]["author-about"])) {
1592 $data["about"] = $feed_data["header"]["author-about"];
1594 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1595 // So we take the value that we just fetched, although the other one worked as well
1596 if (!empty($feed_data["header"]["author-link"])) {
1597 $data["url"] = $feed_data["header"]["author-link"];
1600 if ($data["url"] == $data["alias"]) {
1601 $data["alias"] = '';
1604 /// @todo Fetch location and "about" from the feed as well
1609 * Fetch data from a pump.io profile page
1611 * @param string $profile_link Link to the profile page
1613 * @return array profile data
1615 private static function pumpioProfileData($profile_link)
1617 $curlResult = DI::httpClient()->get($profile_link, [HttpClientOptions::ACCEPT_CONTENT => HttpClient::ACCEPT_HTML]);
1618 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
1622 $doc = new DOMDocument();
1623 if (!@$doc->loadHTML($curlResult->getBody())) {
1627 $xpath = new DomXPath($doc);
1631 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1633 if ($data["name"] == '') {
1634 // This is ugly - but pump.io doesn't seem to know a better way for it
1635 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1636 $pos = strpos($data["name"], chr(10));
1638 $data["name"] = trim(substr($data["name"], 0, $pos));
1642 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1644 if ($data["location"] == '') {
1645 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1648 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1650 if ($data["about"] == '') {
1651 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1654 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1656 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1659 foreach ($avatar->attributes as $attribute) {
1660 if ($attribute->name == "src") {
1661 $data["photo"] = trim($attribute->value);
1670 * Check for pump.io contact
1672 * @param array $webfinger Webfinger data
1673 * @param string $addr
1674 * @return array pump.io data
1676 private static function pumpio($webfinger, $addr)
1679 // The array is reversed to take into account the order of preference for same-rel links
1680 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1681 foreach (array_reverse($webfinger["links"]) as $link) {
1682 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1683 && (($link["type"] ?? "") == "text/html")
1684 && ($link["href"] != "")
1686 $data["url"] = $link["href"];
1687 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1688 $data["notify"] = $link["href"];
1689 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1690 $data["poll"] = $link["href"];
1691 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1692 $data["dialback"] = $link["href"];
1695 if (isset($data["poll"]) && isset($data["notify"])
1696 && isset($data["dialback"])
1697 && isset($data["url"])
1699 // by now we use these fields only for the network type detection
1700 // So we unset all data that isn't used at the moment
1701 unset($data["dialback"]);
1703 $data["network"] = Protocol::PUMPIO;
1708 $profile_data = self::pumpioProfileData($data["url"]);
1710 if (!$profile_data) {
1714 $data = array_merge($data, $profile_data);
1716 if (($addr != '') && ($data['name'] != '')) {
1717 $name = trim(str_replace($addr, '', $data['name']));
1719 $data['name'] = $name;
1727 * Checks HTML page for RSS feed link
1729 * @param string $url Page link
1730 * @param string $body Page body string
1731 * @return string|false Feed link or false if body was invalid HTML document
1733 public static function getFeedLink(string $url, string $body)
1739 $doc = new DOMDocument();
1740 if (!@$doc->loadHTML($body)) {
1744 $xpath = new DOMXPath($doc);
1746 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1748 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1754 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1756 * Loosely based on RFC 1808
1758 * @see https://tools.ietf.org/html/rfc1808
1760 * @param string $href The potential relative href found in the HTML document
1761 * @param string $base The HTML document URL
1762 * @param DOMXPath $xpath The HTML document XPath
1765 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath)
1767 if (filter_var($href, FILTER_VALIDATE_URL)) {
1771 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1773 $baseParts = parse_url($base);
1774 if (empty($baseParts['host'])) {
1778 // Naked domain case (scheme://basehost)
1779 $path = $baseParts['path'] ?? '/';
1781 // Remove the filename part of the path if it exists (/base/path/file)
1782 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1784 $hrefParts = parse_url($href);
1786 if (!empty($hrefParts['path'])) {
1787 // Root path case (/path) including relative scheme case (//host/path)
1788 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1789 $path = $hrefParts['path'];
1791 $path = $path . '/' . $hrefParts['path'];
1793 // Resolve arbitrary relative path
1794 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1795 $parts = array_filter(explode('/', $path), 'strlen');
1796 $absolutes = array();
1797 foreach ($parts as $part) {
1798 if ('.' == $part) continue;
1799 if ('..' == $part) {
1800 array_pop($absolutes);
1802 $absolutes[] = $part;
1806 $path = '/' . implode('/', $absolutes);
1810 // Relative scheme case (//host/path)
1811 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1812 $baseParts['path'] = $path;
1813 unset($baseParts['query']);
1814 unset($baseParts['fragment']);
1816 return Network::unparseURL($baseParts);
1820 * Check for feed contact
1822 * @param string $url Profile link
1823 * @param boolean $probe Do a probe if the page contains a feed link
1825 * @return array feed data
1826 * @throws HTTPException\InternalServerErrorException
1828 private static function feed($url, $probe = true)
1830 $curlResult = DI::httpClient()->get($url, [HttpClientOptions::ACCEPT_CONTENT => HttpClient::ACCEPT_FEED_XML]);
1831 if ($curlResult->isTimeout()) {
1832 self::$istimeout = true;
1835 $feed = $curlResult->getBody();
1836 $feed_data = Feed::import($feed);
1843 $feed_url = self::getFeedLink($url, $feed);
1849 return self::feed($feed_url, false);
1852 if (!empty($feed_data["header"]["author-name"])) {
1853 $data["name"] = $feed_data["header"]["author-name"];
1856 if (!empty($feed_data["header"]["author-nick"])) {
1857 $data["nick"] = $feed_data["header"]["author-nick"];
1860 if (!empty($feed_data["header"]["author-avatar"])) {
1861 $data["photo"] = $feed_data["header"]["author-avatar"];
1864 if (!empty($feed_data["header"]["author-id"])) {
1865 $data["alias"] = $feed_data["header"]["author-id"];
1868 $data["url"] = $url;
1869 $data["poll"] = $url;
1871 $data["network"] = Protocol::FEED;
1877 * Check for mail contact
1879 * @param string $uri Profile link
1880 * @param integer $uid User ID
1882 * @return array mail data
1883 * @throws \Exception
1885 private static function mail($uri, $uid)
1887 if (!Network::isEmailDomainValid($uri)) {
1895 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1897 $condition = ["`uid` = ? AND `server` != ''", $uid];
1898 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1899 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1901 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1905 $mailbox = Email::constructMailboxName($mailacct);
1907 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1908 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1913 $msgs = Email::poll($mbox, $uri);
1914 Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
1916 if (!count($msgs)) {
1920 $phost = substr($uri, strpos($uri, '@') + 1);
1923 $data["addr"] = $uri;
1924 $data["network"] = Protocol::MAIL;
1925 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1926 $data["nick"] = $data["name"];
1927 $data["photo"] = Network::lookupAvatarByEmail($uri);
1928 $data["url"] = 'mailto:'.$uri;
1929 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1930 $data["poll"] = 'email ' . Strings::getRandomHex();
1932 $x = Email::messageMeta($mbox, $msgs[0]);
1933 if (stristr($x[0]->from, $uri)) {
1934 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1935 } elseif (stristr($x[0]->to, $uri)) {
1936 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1939 foreach ($adr as $feadr) {
1940 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1941 &&(strcasecmp($feadr->host, $phost) == 0)
1942 && (strlen($feadr->personal))
1944 $personal = imap_mime_header_decode($feadr->personal);
1946 foreach ($personal as $perspart) {
1947 if ($perspart->charset != "default") {
1948 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1950 $data["name"] .= $perspart->text;
1956 if (!empty($mbox)) {
1963 * Mix two paths together to possibly fix missing parts
1965 * @param string $avatar Path to the avatar
1966 * @param string $base Another path that is hopefully complete
1968 * @return string fixed avatar path
1969 * @throws \Exception
1971 public static function fixAvatar($avatar, $base)
1973 $base_parts = parse_url($base);
1975 // Remove all parts that could create a problem
1976 unset($base_parts['path']);
1977 unset($base_parts['query']);
1978 unset($base_parts['fragment']);
1980 $avatar_parts = parse_url($avatar);
1983 $parts = array_merge($base_parts, $avatar_parts);
1985 // And put them together again
1986 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1987 $host = isset($parts['host']) ? $parts['host'] : '';
1988 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1989 $path = isset($parts['path']) ? $parts['path'] : '';
1990 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1991 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1993 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1995 Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
2001 * Fetch the last date that the contact had posted something (publically)
2003 * @param array $data probing result
2004 * @return string last activity
2006 public static function getLastUpdate(array $data)
2008 $uid = User::getIdForURL($data['url']);
2010 $contact = Contact::selectFirst(['url', 'last-item'], ['self' => true, 'uid' => $uid]);
2011 if (!empty($contact['last-item'])) {
2012 return $contact['last-item'];
2016 if ($lastUpdate = self::updateFromNoScrape($data)) {
2020 if (!empty($data['outbox'])) {
2021 return self::updateFromOutbox($data['outbox'], $data);
2022 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
2023 return self::updateFromOutbox($data['poll'], $data);
2024 } elseif (!empty($data['poll'])) {
2025 return self::updateFromFeed($data);
2032 * Fetch the last activity date from the "noscrape" endpoint
2034 * @param array $data Probing result
2035 * @return string last activity
2037 * @return bool 'true' if update was successful or the server was unreachable
2039 private static function updateFromNoScrape(array $data)
2041 if (empty($data['baseurl'])) {
2045 // Check the 'noscrape' endpoint when it is a Friendica server
2046 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
2047 Strings::normaliseLink($data['baseurl'])]);
2048 if (!DBA::isResult($gserver)) {
2052 $curlResult = DI::httpClient()->get($gserver['noscrape'] . '/' . $data['nick'], [HttpClientOptions::ACCEPT_CONTENT => HttpClient::ACCEPT_JSON]);
2054 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
2055 $noscrape = json_decode($curlResult->getBody(), true);
2056 if (!empty($noscrape) && !empty($noscrape['updated'])) {
2057 return DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2065 * Fetch the last activity date from an ActivityPub Outbox
2067 * @param string $feed
2068 * @param array $data Probing result
2069 * @return string last activity
2070 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2072 private static function updateFromOutbox(string $feed, array $data)
2074 $outbox = ActivityPub::fetchContent($feed);
2075 if (empty($outbox)) {
2079 if (!empty($outbox['orderedItems'])) {
2080 $items = $outbox['orderedItems'];
2081 } elseif (!empty($outbox['first']['orderedItems'])) {
2082 $items = $outbox['first']['orderedItems'];
2083 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2084 return self::updateFromOutbox($outbox['first']['href'], $data);
2085 } elseif (!empty($outbox['first'])) {
2086 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2087 return self::updateFromOutbox($outbox['first'], $data);
2089 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2097 foreach ($items as $activity) {
2098 if (!empty($activity['published'])) {
2099 $published = DateTimeFormat::utc($activity['published']);
2100 } elseif (!empty($activity['object']['published'])) {
2101 $published = DateTimeFormat::utc($activity['object']['published']);
2106 if ($last_updated < $published) {
2107 $last_updated = $published;
2111 if (!empty($last_updated)) {
2112 return $last_updated;
2119 * Fetch the last activity date from an XML feed
2121 * @param array $data Probing result
2122 * @return string last activity
2124 private static function updateFromFeed(array $data)
2126 // Search for the newest entry in the feed
2127 $curlResult = DI::httpClient()->get($data['poll'], [HttpClientOptions::ACCEPT_CONTENT => HttpClient::ACCEPT_ATOM_XML]);
2128 if (!$curlResult->isSuccess() || !$curlResult->getBody()) {
2132 $doc = new DOMDocument();
2133 @$doc->loadXML($curlResult->getBody());
2135 $xpath = new DOMXPath($doc);
2136 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2138 $entries = $xpath->query('/atom:feed/atom:entry');
2142 foreach ($entries as $entry) {
2143 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2144 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
2145 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2146 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2148 if (empty($published) || empty($updated)) {
2149 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2153 if ($last_updated < $published) {
2154 $last_updated = $published;
2157 if ($last_updated < $updated) {
2158 $last_updated = $updated;
2162 if (!empty($last_updated)) {
2163 return $last_updated;
2170 * Probe data from local profiles without network traffic
2172 * @param string $url
2173 * @return array probed data
2174 * @throws HTTPException\InternalServerErrorException
2175 * @throws HTTPException\NotFoundException
2177 private static function localProbe(string $url): array
2180 $uid = User::getIdForURL($url);
2182 throw new HTTPException\NotFoundException('User not found.');
2185 $owner = User::getOwnerDataById($uid);
2186 $approfile = ActivityPub\Transmitter::getProfile($uid);
2188 if (empty($owner['gsid'])) {
2189 $owner['gsid'] = GServer::getID($approfile['generator']['url']);
2193 'name' => $owner['name'], 'nick' => $owner['nick'], 'guid' => $approfile['diaspora:guid'] ?? '',
2194 'url' => $owner['url'], 'addr' => $owner['addr'], 'alias' => $owner['alias'],
2195 'photo' => User::getAvatarUrl($owner),
2196 'header' => $owner['header'] ? Contact::getHeaderUrlForId($owner['id'], $owner['updated']) : '',
2197 'account-type' => $owner['contact-type'], 'community' => ($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY),
2198 'keywords' => $owner['keywords'], 'location' => $owner['location'], 'about' => $owner['about'],
2199 'xmpp' => $owner['xmpp'], 'matrix' => $owner['matrix'],
2200 'hide' => !$owner['net-publish'], 'batch' => '', 'notify' => $owner['notify'],
2201 'poll' => $owner['poll'], 'request' => $owner['request'], 'confirm' => $owner['confirm'],
2202 'subscribe' => $approfile['generator']['url'] . '/follow?url={uri}', 'poco' => $owner['poco'],
2203 'following' => $approfile['following'], 'followers' => $approfile['followers'],
2204 'inbox' => $approfile['inbox'], 'outbox' => $approfile['outbox'],
2205 'sharedinbox' => $approfile['endpoints']['sharedInbox'], 'network' => Protocol::DFRN,
2206 'pubkey' => $owner['upubkey'], 'baseurl' => $approfile['generator']['url'], 'gsid' => $owner['gsid'],
2207 'manually-approve' => in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])
2209 } catch (Exception $e) {
2210 // Default values for non existing targets
2212 'name' => $url, 'nick' => $url, 'url' => $url, 'network' => Protocol::PHANTOM,
2213 'photo' => DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO
2217 return self::rearrangeData($data);