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 $curlResult = DI::httpClient()->get($url, [HttpClientOptions::ACCEPT_CONTENT => HttpClient::ACCEPT_JSON]);
838 if ($curlResult->isTimeout()) {
841 $content = $curlResult->getBody();
846 $json = json_decode($content, true);
847 if (!is_array($json)) {
851 if (empty($data['network'])) {
852 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
853 $data['network'] = Protocol::ZOT;
854 } elseif (!isset($json['protocols'])) {
855 $data['network'] = Protocol::ZOT;
859 if (!empty($json['guid']) && empty($data['guid'])) {
860 $data['guid'] = $json['guid'];
862 if (!empty($json['key']) && empty($data['pubkey'])) {
863 $data['pubkey'] = $json['key'];
865 if (!empty($json['name'])) {
866 $data['name'] = $json['name'];
868 if (!empty($json['photo'])) {
869 $data['photo'] = $json['photo'];
870 if (!empty($json['photo_updated'])) {
871 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
874 if (!empty($json['address'])) {
875 $data['addr'] = $json['address'];
877 if (!empty($json['url'])) {
878 $data['url'] = $json['url'];
880 if (!empty($json['connections_url'])) {
881 $data['poco'] = $json['connections_url'];
883 if (isset($json['searchable'])) {
884 $data['hide'] = !$json['searchable'];
886 if (!empty($json['public_forum'])) {
887 $data['community'] = $json['public_forum'];
888 $data['account-type'] = User::PAGE_FLAGS_COMMUNITY;
891 if (!empty($json['profile'])) {
892 $profile = $json['profile'];
893 if (!empty($profile['description'])) {
894 $data['about'] = $profile['description'];
896 if (!empty($profile['keywords'])) {
897 $keywords = implode(', ', $profile['keywords']);
898 if (!empty($keywords)) {
899 $data['keywords'] = $keywords;
904 if (!empty($profile['region'])) {
905 $loc['region'] = $profile['region'];
907 if (!empty($profile['country'])) {
908 $loc['country-name'] = $profile['country'];
910 $location = Profile::formatLocation($loc);
911 if (!empty($location)) {
912 $data['location'] = $location;
920 * Perform a webfinger request.
922 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
924 * @param string $url Address that should be probed
925 * @param string $type type
927 * @return array webfinger data
928 * @throws HTTPException\InternalServerErrorException
930 public static function webfinger($url, $type)
932 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
934 $curlResult = DI::httpClient()->get($url, [HttpClientOptions::TIMEOUT => $xrd_timeout, HttpClientOptions::ACCEPT_CONTENT => $type]);
935 if ($curlResult->isTimeout()) {
936 self::$istimeout = true;
939 $data = $curlResult->getBody();
941 $webfinger = json_decode($data, true);
942 if (!empty($webfinger)) {
943 if (!isset($webfinger["links"])) {
944 Logger::info('No json webfinger links', ['url' => $url]);
950 // If it is not JSON, maybe it is XML
951 $xrd = XML::parseString($data, true);
952 if (!is_object($xrd)) {
953 Logger::info('No webfinger data retrievable', ['url' => $url]);
957 $xrd_arr = XML::elementToArray($xrd);
958 if (!isset($xrd_arr["xrd"]["link"])) {
959 Logger::info('No XML webfinger links', ['url' => $url]);
965 if (!empty($xrd_arr["xrd"]["subject"])) {
966 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
969 if (!empty($xrd_arr["xrd"]["alias"])) {
970 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
973 $webfinger["links"] = [];
975 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
976 if (!empty($data["@attributes"])) {
977 $attributes = $data["@attributes"];
978 } elseif ($value == "@attributes") {
984 $webfinger["links"][] = $attributes;
990 * Poll the Friendica specific noscrape page.
992 * "noscrape" is a faster alternative to fetch the data from the hcard.
993 * This functionality was originally created for the directory.
995 * @param string $noscrape_url Link to the noscrape page
996 * @param array $data The already fetched data
998 * @return array noscrape data
999 * @throws HTTPException\InternalServerErrorException
1001 private static function pollNoscrape($noscrape_url, $data)
1003 $curlResult = DI::httpClient()->get($noscrape_url, [HttpClientOptions::ACCEPT_CONTENT => HttpClient::ACCEPT_JSON]);
1004 if ($curlResult->isTimeout()) {
1005 self::$istimeout = true;
1008 $content = $curlResult->getBody();
1010 Logger::info('Empty body', ['url' => $noscrape_url]);
1014 $json = json_decode($content, true);
1015 if (!is_array($json)) {
1016 Logger::info('No json data', ['url' => $noscrape_url]);
1020 if (!empty($json["fn"])) {
1021 $data["name"] = $json["fn"];
1024 if (!empty($json["addr"])) {
1025 $data["addr"] = $json["addr"];
1028 if (!empty($json["nick"])) {
1029 $data["nick"] = $json["nick"];
1032 if (!empty($json["guid"])) {
1033 $data["guid"] = $json["guid"];
1036 if (!empty($json["comm"])) {
1037 $data["community"] = $json["comm"];
1040 if (!empty($json["tags"])) {
1041 $keywords = implode(", ", $json["tags"]);
1042 if ($keywords != "") {
1043 $data["keywords"] = $keywords;
1047 $location = Profile::formatLocation($json);
1049 $data["location"] = $location;
1052 if (!empty($json["about"])) {
1053 $data["about"] = $json["about"];
1056 if (!empty($json["xmpp"])) {
1057 $data["xmpp"] = $json["xmpp"];
1060 if (!empty($json["matrix"])) {
1061 $data["matrix"] = $json["matrix"];
1064 if (!empty($json["key"])) {
1065 $data["pubkey"] = $json["key"];
1068 if (!empty($json["photo"])) {
1069 $data["photo"] = $json["photo"];
1072 if (!empty($json["dfrn-request"])) {
1073 $data["request"] = $json["dfrn-request"];
1076 if (!empty($json["dfrn-confirm"])) {
1077 $data["confirm"] = $json["dfrn-confirm"];
1080 if (!empty($json["dfrn-notify"])) {
1081 $data["notify"] = $json["dfrn-notify"];
1084 if (!empty($json["dfrn-poll"])) {
1085 $data["poll"] = $json["dfrn-poll"];
1088 if (isset($json["hide"])) {
1089 $data["hide"] = (bool)$json["hide"];
1091 $data["hide"] = false;
1098 * Check for valid DFRN data
1100 * @param array $data DFRN data
1102 * @return int Number of errors
1104 public static function validDfrn($data)
1107 if (!isset($data['key'])) {
1110 if (!isset($data['dfrn-request'])) {
1113 if (!isset($data['dfrn-confirm'])) {
1116 if (!isset($data['dfrn-notify'])) {
1119 if (!isset($data['dfrn-poll'])) {
1126 * Fetch data from a DFRN profile page and via "noscrape"
1128 * @param string $profile_link Link to the profile page
1130 * @return array profile data
1131 * @throws HTTPException\InternalServerErrorException
1132 * @throws \ImagickException
1134 public static function profile($profile_link)
1138 Logger::info('Check profile', ['link' => $profile_link]);
1140 // Fetch data via noscrape - this is faster
1141 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1142 $data = self::pollNoscrape($noscrape_url, $data);
1144 if (!isset($data["notify"])
1145 || !isset($data["confirm"])
1146 || !isset($data["request"])
1147 || !isset($data["poll"])
1148 || !isset($data["name"])
1149 || !isset($data["photo"])
1151 $data = self::pollHcard($profile_link, $data, true);
1156 if (empty($data["addr"]) || empty($data["nick"])) {
1157 $probe_data = self::uri($profile_link);
1158 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1159 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1162 $prof_data["addr"] = $data["addr"];
1163 $prof_data["nick"] = $data["nick"];
1164 $prof_data["dfrn-request"] = $data['request'] ?? null;
1165 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1166 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1167 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1168 $prof_data["photo"] = $data['photo'] ?? null;
1169 $prof_data["fn"] = $data['name'] ?? null;
1170 $prof_data["key"] = $data['pubkey'] ?? null;
1172 Logger::debug('Result', ['link' => $profile_link, 'data' => $prof_data]);
1178 * Check for DFRN contact
1180 * @param array $webfinger Webfinger data
1182 * @return array DFRN data
1183 * @throws HTTPException\InternalServerErrorException
1185 private static function dfrn($webfinger)
1189 // The array is reversed to take into account the order of preference for same-rel links
1190 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1191 foreach (array_reverse($webfinger["links"]) as $link) {
1192 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1193 $data["network"] = Protocol::DFRN;
1194 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1195 $data["poll"] = $link["href"];
1196 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1197 $data["url"] = $link["href"];
1198 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1199 $hcard_url = $link["href"];
1200 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1201 $data["poco"] = $link["href"];
1202 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1203 $data["photo"] = $link["href"];
1204 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1205 $data["baseurl"] = trim($link["href"], '/');
1206 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1207 $data["guid"] = $link["href"];
1208 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1209 $data["pubkey"] = base64_decode($link["href"]);
1211 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1212 if (strstr($data["pubkey"], 'RSA ')) {
1213 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1218 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1219 foreach ($webfinger["aliases"] as $alias) {
1220 if (empty($data["url"]) && !strstr($alias, "@")) {
1221 $data["url"] = $alias;
1222 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1223 $data["alias"] = $alias;
1224 } elseif (substr($alias, 0, 5) == 'acct:') {
1225 $data["addr"] = substr($alias, 5);
1230 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1231 $data["addr"] = substr($webfinger["subject"], 5);
1234 if (!isset($data["network"]) || ($hcard_url == "")) {
1238 // Fetch data via noscrape - this is faster
1239 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1240 $data = self::pollNoscrape($noscrape_url, $data);
1242 if (isset($data["notify"])
1243 && isset($data["confirm"])
1244 && isset($data["request"])
1245 && isset($data["poll"])
1246 && isset($data["name"])
1247 && isset($data["photo"])
1252 $data = self::pollHcard($hcard_url, $data, true);
1258 * Poll the hcard page (Diaspora and Friendica specific)
1260 * @param string $hcard_url Link to the hcard page
1261 * @param array $data The already fetched data
1262 * @param boolean $dfrn Poll DFRN specific data
1264 * @return array hcard data
1265 * @throws HTTPException\InternalServerErrorException
1267 private static function pollHcard($hcard_url, $data, $dfrn = false)
1269 $curlResult = DI::httpClient()->get($hcard_url, [HttpClientOptions::ACCEPT_CONTENT => HttpClient::ACCEPT_HTML]);
1270 if ($curlResult->isTimeout()) {
1271 self::$istimeout = true;
1274 $content = $curlResult->getBody();
1275 if (empty($content)) {
1279 $doc = new DOMDocument();
1280 if (!@$doc->loadHTML($content)) {
1284 $xpath = new DomXPath($doc);
1286 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1287 if (!is_object($vcards)) {
1291 if (!isset($data["baseurl"])) {
1292 $data["baseurl"] = "";
1295 if ($vcards->length > 0) {
1296 $vcard = $vcards->item(0);
1298 // We have to discard the guid from the hcard in favour of the guid from lrdd
1299 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1300 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1301 if (($search->length > 0) && empty($data["guid"])) {
1302 $data["guid"] = $search->item(0)->nodeValue;
1305 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1306 if ($search->length > 0) {
1307 $data["nick"] = $search->item(0)->nodeValue;
1310 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1311 if ($search->length > 0) {
1312 $data["name"] = $search->item(0)->nodeValue;
1315 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1316 if ($search->length > 0) {
1317 $data["searchable"] = $search->item(0)->nodeValue;
1320 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1321 if ($search->length > 0) {
1322 $data["pubkey"] = $search->item(0)->nodeValue;
1323 if (strstr($data["pubkey"], 'RSA ')) {
1324 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1328 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1329 if ($search->length > 0) {
1330 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1335 if (!empty($vcard)) {
1336 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1337 foreach ($photos as $photo) {
1339 foreach ($photo->attributes as $attribute) {
1340 $attr[$attribute->name] = trim($attribute->value);
1343 if (isset($attr["src"]) && isset($attr["width"])) {
1344 $avatar[$attr["width"]] = $attr["src"];
1347 // We don't have a width. So we just take everything that we got.
1348 // This is a Hubzilla workaround which doesn't send a width.
1349 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1350 $avatar[] = $attr["src"];
1355 if (sizeof($avatar)) {
1357 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1361 // Poll DFRN specific data
1362 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1363 if ($search->length > 0) {
1364 foreach ($search as $link) {
1365 //$data["request"] = $search->item(0)->nodeValue;
1367 foreach ($link->attributes as $attribute) {
1368 $attr[$attribute->name] = trim($attribute->value);
1371 $data[substr($attr["rel"], 5)] = $attr["href"];
1375 // Older Friendica versions had used the "uid" field differently than newer versions
1376 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1377 unset($data["guid"]);
1386 * Check for Diaspora contact
1388 * @param array $webfinger Webfinger data
1390 * @return array Diaspora data
1391 * @throws HTTPException\InternalServerErrorException
1393 private static function diaspora($webfinger)
1398 // The array is reversed to take into account the order of preference for same-rel links
1399 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1400 foreach (array_reverse($webfinger["links"]) as $link) {
1401 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1402 $hcard_url = $link["href"];
1403 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1404 $data["baseurl"] = trim($link["href"], '/');
1405 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1406 $data["guid"] = $link["href"];
1407 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1408 $data["url"] = $link["href"];
1409 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && empty($link["type"]) && !empty($link["href"])) {
1410 $profile_url = $link["href"];
1411 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1412 $data["poll"] = $link["href"];
1413 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1414 $data["poco"] = $link["href"];
1415 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1416 $data["notify"] = $link["href"];
1417 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1418 $data["pubkey"] = base64_decode($link["href"]);
1420 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1421 if (strstr($data["pubkey"], 'RSA ')) {
1422 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1427 if (empty($data["url"]) && !empty($profile_url)) {
1428 $data["url"] = $profile_url;
1431 if (empty($data["url"]) || empty($hcard_url)) {
1435 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1436 foreach ($webfinger["aliases"] as $alias) {
1437 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1438 $data["alias"] = $alias;
1439 } elseif (substr($alias, 0, 5) == 'acct:') {
1440 $data["addr"] = substr($alias, 5);
1445 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1446 $data["addr"] = substr($webfinger["subject"], 5);
1449 // Fetch further information from the hcard
1450 $data = self::pollHcard($hcard_url, $data);
1456 if (!empty($data["url"])
1457 && !empty($data["guid"])
1458 && !empty($data["baseurl"])
1459 && !empty($data["pubkey"])
1460 && !empty($hcard_url)
1462 $data["network"] = Protocol::DIASPORA;
1463 $data["manually-approve"] = false;
1465 // The Diaspora handle must always be lowercase
1466 if (!empty($data["addr"])) {
1467 $data["addr"] = strtolower($data["addr"]);
1470 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1471 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1472 $data["batch"] = $data["baseurl"] . "/receive/public";
1481 * Check for OStatus contact
1483 * @param array $webfinger Webfinger data
1484 * @param bool $short Short detection mode
1486 * @return array|bool OStatus data or "false" on error or "true" on short mode
1487 * @throws HTTPException\InternalServerErrorException
1489 private static function ostatus($webfinger, $short = false)
1493 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1494 foreach ($webfinger["aliases"] as $alias) {
1495 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1496 $data["addr"] = str_replace('acct:', '', $alias);
1501 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1502 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1504 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1507 if (!empty($webfinger["links"])) {
1508 // The array is reversed to take into account the order of preference for same-rel links
1509 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1510 foreach (array_reverse($webfinger["links"]) as $link) {
1511 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1512 && (($link["type"] ?? "") == "text/html")
1513 && ($link["href"] != "")
1515 $data["url"] = $data["alias"] = $link["href"];
1516 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1517 $data["notify"] = $link["href"];
1518 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1519 $data["poll"] = $link["href"];
1520 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1521 $pubkey = $link["href"];
1523 if (substr($pubkey, 0, 5) === 'data:') {
1524 if (strstr($pubkey, ',')) {
1525 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1527 $pubkey = substr($pubkey, 5);
1529 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1530 $curlResult = DI::httpClient()->get($pubkey, [HttpClientOptions::ACCEPT_CONTENT => HttpClient::ACCEPT_MAGIC_KEY]);
1531 if ($curlResult->isTimeout()) {
1532 self::$istimeout = true;
1533 return $short ? false : [];
1535 Logger::debug('Fetched public key', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $pubkey]);
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);