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\HttpClientAccept;
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\Protocol\Salmon;
44 use Friendica\Util\Crypto;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Network;
47 use Friendica\Util\Strings;
48 use Friendica\Util\XML;
49 use GuzzleHttp\Psr7\Uri;
52 * This class contain functions for probing URL
56 const HOST_META = '/.well-known/host-meta';
57 const WEBFINGER = '/.well-known/webfinger?resource={uri}';
60 * @var string Base URL
62 private static $baseurl;
65 * @var boolean Whether a timeout has occured
67 private static $isTimeout;
70 * Checks if the provided network can be probed
72 * @param string $network
76 public static function isProbable(string $network): bool
78 return (in_array($network, array_merge(Protocol::FEDERATED, [Protocol::ZOT, Protocol::PHANTOM])));
82 * Remove stuff from an URI that doesn't belong there
84 * @param string $rawUri
85 * @return string Cleaned URI
87 public static function cleanURI(string $rawUri): string
89 // At first remove leading and trailing junk
90 $rawUri = trim($rawUri, "@#?: \t\n\r\0\x0B");
92 $rawUri = Network::convertToIdn($rawUri);
94 $uri = new Uri($rawUri);
95 if (!$uri->getScheme()) {
96 return $uri->__toString();
99 // Remove the URL fragment, since these shouldn't be part of any profile URL
100 $uri = $uri->withFragment('');
102 return $uri->__toString();
106 * Rearrange the array so that it always has the same order
108 * @param array $data Unordered data
109 * @return array Ordered data
111 private static function rearrangeData(array $data): array
113 $fields = ['name', 'given_name', 'family_name', 'nick', 'guid', 'url', 'addr', 'alias',
114 'photo', 'photo_medium', 'photo_small', 'header',
115 'account-type', 'community', 'keywords', 'location', 'about', 'xmpp', 'matrix',
116 'hide', 'batch', 'notify', 'poll', 'request', 'confirm', 'subscribe', 'poco',
117 'following', 'followers', 'inbox', 'outbox', 'sharedinbox',
118 'priority', 'network', 'pubkey', 'manually-approve', 'baseurl', 'gsid'];
120 $numeric_fields = ['gsid', 'hide', 'account-type', 'manually-approve'];
123 foreach ($fields as $field) {
124 if (isset($data[$field])) {
125 if (in_array($field, $numeric_fields)) {
126 $newdata[$field] = (int)$data[$field];
128 $newdata[$field] = trim($data[$field]);
130 } elseif (!in_array($field, $numeric_fields)) {
131 $newdata[$field] = '';
133 $newdata[$field] = null;
137 $newdata['networks'] = [];
138 foreach ([Protocol::DIASPORA, Protocol::OSTATUS] as $network) {
139 if (!empty($data['networks'][$network])) {
140 $data['networks'][$network]['subscribe'] = $newdata['subscribe'] ?? '';
141 $data['networks'][$network]['baseurl'] = $newdata['baseurl'] ?? '';
142 $data['networks'][$network]['gsid'] = $newdata['gsid'] ?? 0;
143 $newdata['networks'][$network] = self::rearrangeData($data['networks'][$network]);
144 unset($newdata['networks'][$network]['networks']);
148 // We don't use the "priority" field anymore and replace it with a dummy.
149 $newdata['priority'] = 0;
155 * Check if the hostname belongs to the own server
157 * @param string $host The hostname that is to be checked
158 * @return bool Does the testes hostname belongs to the own server?
160 private static function ownHost(string $host): bool
162 $own_host = DI::baseUrl()->getHostname();
164 $parts = parse_url($host);
166 if (!isset($parts['scheme'])) {
167 $parts = parse_url('http://' . $host);
170 if (!isset($parts['host'])) {
173 return $parts['host'] == $own_host;
177 * Probes for webfinger path via "host-meta"
179 * We have to check if the servers in the future still will offer this.
180 * It seems as if it was dropped from the standard.
182 * @param string $host The host part of an url
184 * @return array with template and type of the webfinger template for JSON or XML
185 * @throws HTTPException\InternalServerErrorException
187 private static function hostMeta(string $host): array
189 // Reset the static variable
192 // Handles the case when the hostname contains the scheme
193 if (!parse_url($host, PHP_URL_SCHEME)) {
194 $ssl_url = 'https://' . $host . self::HOST_META;
195 $url = 'http://' . $host . self::HOST_META;
197 $ssl_url = $host . self::HOST_META;
201 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
203 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
206 $curlResult = DI::httpClient()->get($ssl_url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
207 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
208 if ($curlResult->isSuccess()) {
209 $xml = $curlResult->getBody();
210 $xrd = XML::parseString($xml, true);
212 $host_url = 'https://' . $host;
216 } elseif ($curlResult->isTimeout()) {
217 Logger::info('Probing timeout', ['url' => $ssl_url]);
218 self::$isTimeout = true;
222 if (!is_object($xrd) && !empty($url)) {
223 $curlResult = DI::httpClient()->get($url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
224 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
225 if ($curlResult->isTimeout()) {
226 Logger::info('Probing timeout', ['url' => $url]);
227 self::$isTimeout = true;
229 } elseif ($connection_error && $ssl_connection_error) {
230 self::$isTimeout = true;
234 $xml = $curlResult->getBody();
235 $xrd = XML::parseString($xml, true);
236 $host_url = 'http://'.$host;
238 if (!is_object($xrd)) {
239 Logger::info('No xrd object found', ['host' => $host]);
243 $links = XML::elementToArray($xrd);
244 if (!isset($links['xrd']['link'])) {
245 Logger::info('No xrd data found', ['host' => $host]);
251 foreach ($links['xrd']['link'] as $value => $link) {
252 if (!empty($link['@attributes'])) {
253 $attributes = $link['@attributes'];
254 } elseif ($value == '@attributes') {
260 if (!empty($attributes['rel']) && $attributes['rel'] == 'lrdd' && !empty($attributes['template'])) {
261 $type = (empty($attributes['type']) ? '' : $attributes['type']);
263 $lrdd[$type] = $attributes['template'];
267 if (Network::isUrlBlocked($host_url)) {
268 Logger::info('Domain is blocked', ['url' => $host]);
272 self::$baseurl = $host_url;
274 Logger::info('Probing successful', ['host' => $host]);
280 * Check an URI for LRDD data
282 * @param string $uri Address that should be probed
283 * @return array uri data
284 * @throws HTTPException\InternalServerErrorException
286 public static function lrdd(string $uri): array
288 $data = self::getWebfingerArray($uri);
292 $webfinger = $data['webfinger'];
294 if (empty($webfinger['links'])) {
295 Logger::info('No webfinger links found', ['uri' => $uri]);
301 foreach ($webfinger['links'] as $link) {
302 $data[] = ['@attributes' => $link];
305 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
306 foreach ($webfinger['aliases'] as $alias) {
320 * Fetch information (protocol endpoints and user information) about a given uri
322 * @param string $uri Address that should be probed
323 * @param string $network Test for this specific network
324 * @param integer $uid User ID for the probe (only used for mails)
325 * @param boolean $cache Use cached values?
327 * @return array uri data
328 * @throws HTTPException\InternalServerErrorException
329 * @throws \ImagickException
331 public static function uri(string $uri, string $network = '', int $uid = -1): array
333 // Local profiles aren't probed via network
334 if (empty($network) && Contact::isLocal($uri)) {
335 $data = self::localProbe($uri);
342 $uid = DI::userSession()->getLocalUserId();
345 if (empty($network) || ($network == Protocol::ACTIVITYPUB)) {
346 $ap_profile = ActivityPub::probeProfile($uri);
351 self::$isTimeout = false;
353 if ($network != Protocol::ACTIVITYPUB) {
354 $data = self::detect($uri, $network, $uid, $ap_profile);
355 if (!is_array($data)) {
358 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
359 $networks = $data['networks'] ?? [];
360 unset($data['networks']);
361 $networks[$data['network']] = $data;
363 $data['networks'] = $networks;
364 } elseif (!empty($ap_profile)) {
365 $ap_profile['batch'] = '';
366 $data = array_merge($ap_profile, $data);
372 if (!isset($data['url'])) {
376 if (empty($data['photo'])) {
377 $data['photo'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
380 if (empty($data['name'])) {
381 if (!empty($data['nick'])) {
382 $data['name'] = $data['nick'];
385 if (empty($data['name'])) {
386 $data['name'] = $data['url'];
390 if (empty($data['nick'])) {
391 $data['nick'] = strtolower($data['name']);
393 if (strpos($data['nick'], ' ')) {
394 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
398 if (!empty($data['baseurl']) && empty($data['gsid'])) {
399 $data['gsid'] = GServer::getID($data['baseurl']);
402 if (empty($data['network'])) {
403 $data['network'] = Protocol::PHANTOM;
406 // Ensure that local connections always are DFRN
407 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
408 $data['network'] = Protocol::DFRN;
411 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
412 $data['hide'] = self::getHideStatus($data['url']);
415 return self::rearrangeData($data);
420 * Fetches the "hide" status from the profile
422 * @param string $url URL of the profile
423 * @return boolean "hide" status
425 private static function getHideStatus(string $url): bool
427 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::CONTENT_LENGTH => 1000000]);
428 if (!$curlResult->isSuccess()) {
432 // If it isn't a HTML file then exit
433 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
437 $body = $curlResult->getBody();
442 $doc = new DOMDocument();
443 @$doc->loadHTML($body);
445 $xpath = new DOMXPath($doc);
447 $list = $xpath->query('//meta[@name]');
448 foreach ($list as $node) {
450 if ($node->attributes->length) {
451 foreach ($node->attributes as $attribute) {
452 $meta_tag[$attribute->name] = $attribute->value;
456 if (empty($meta_tag['content'])) {
460 $content = strtolower(trim($meta_tag['content']));
462 switch (strtolower(trim($meta_tag['name']))) {
463 case 'dfrn-global-visibility':
464 if ($content == 'false') {
469 if (strpos($content, 'noindex') !== false) {
480 * Fetch the "subscribe" and add it to the result
482 * @param array $result Result array
483 * @param array $webfinger Webfinger data
485 * @return array result Altered/unaltered result array
487 private static function getSubscribeLink(array $result, array $webfinger): array
489 if (empty($webfinger['links'])) {
493 foreach ($webfinger['links'] as $link) {
494 if (!empty($link['template']) && ($link['rel'] === ActivityNamespace::OSTATUSSUB)) {
495 $result['subscribe'] = $link['template'];
503 * Get webfinger data from a given URI
505 * @param string $uri URI
507 * @return array Webfinger data
508 * @throws HTTPException\InternalServerErrorException
510 private static function getWebfingerArray(string $uri): array
512 $parts = parse_url($uri);
514 if (!empty($parts['scheme']) && !empty($parts['host'])) {
515 $host = $parts['host'];
516 if (!empty($parts['port'])) {
517 $host .= ':' . $parts['port'];
520 $baseurl = $parts['scheme'] . '://' . $host;
525 $path_parts = explode('/', trim($parts['path'] ?? '', '/'));
526 if (!empty($path_parts)) {
527 $nick = ltrim(end($path_parts), '@');
528 $addr = $nick . '@' . $host;
531 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
532 if (empty($webfinger)) {
533 $lrdd = self::hostMeta($host);
536 if (empty($webfinger) && empty($lrdd)) {
537 while (empty($lrdd) && empty($webfinger) && (sizeof($path_parts) > 1)) {
538 $host .= '/' . array_shift($path_parts);
539 $baseurl = $parts['scheme'] . '://' . $host;
542 $addr = $nick . '@' . $host;
545 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
546 if (empty($webfinger)) {
547 $lrdd = self::hostMeta($host);
551 if (empty($lrdd) && empty($webfinger)) {
555 } elseif (strstr($uri, '@')) {
556 // Remove "acct:" from the URI
557 $uri = str_replace('acct:', '', $uri);
559 $host = substr($uri, strpos($uri, '@') + 1);
560 $nick = substr($uri, 0, strpos($uri, '@'));
563 $webfinger = self::getWebfinger('https://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
564 if (self::$isTimeout) {
568 if (empty($webfinger)) {
569 $webfinger = self::getWebfinger('http://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
570 if (self::$isTimeout) {
574 $baseurl = 'https://' . $host;
577 if (empty($webfinger)) {
578 $lrdd = self::hostMeta($host);
579 if (self::$isTimeout) {
582 $baseurl = self::$baseurl;
584 $baseurl = 'http://' . $host;
587 Logger::info('URI was not detectable', ['uri' => $uri]);
591 if (empty($webfinger)) {
592 foreach ($lrdd as $type => $template) {
597 $webfinger = self::getWebfinger($template, $type, $uri, $addr);
601 if (empty($webfinger)) {
605 if ($webfinger['detected'] == $addr) {
606 $webfinger['nick'] = $nick;
607 $webfinger['addr'] = $addr;
610 $webfinger['baseurl'] = $baseurl;
616 * Perform network request for webfinger data
618 * @param string $template
619 * @param string $type
621 * @param string $addr
623 * @return array webfinger results
625 private static function getWebfinger(string $template, string $type, string $uri, string $addr): array
627 if (Network::isUrlBlocked($template)) {
628 Logger::info('Domain is blocked', ['url' => $template]);
632 // First try the address because this is the primary purpose of webfinger
635 $path = str_replace('{uri}', urlencode('acct:' . $addr), $template);
636 $webfinger = self::webfinger($path, $type);
637 if (self::$isTimeout) {
643 if (empty($webfinger) && $uri != $addr) {
645 $path = str_replace('{uri}', urlencode($uri), $template);
646 $webfinger = self::webfinger($path, $type);
647 if (self::$isTimeout) {
652 if (empty($webfinger)) {
656 return ['webfinger' => $webfinger, 'detected' => $detected];
660 * Fetch information (protocol endpoints and user information) about a given uri
662 * This function is only called by the "uri" function that adds caching and rearranging of data.
664 * @param string $uri Address that should be probed
665 * @param string $network Test for this specific network
666 * @param integer $uid User ID for the probe (only used for mails)
667 * @param array $ap_profile Previously probed AP profile
668 * @return array URI data
669 * @throws HTTPException\InternalServerErrorException
671 private static function detect(string $uri, string $network, int $uid, array $ap_profile): array
675 'network' => $network,
680 Hook::callAll('probe_detect', $hookData);
682 if (isset($hookData['result'])) {
683 return is_array($hookData['result']) ? $hookData['result'] : [];
686 $parts = parse_url($uri);
687 if (empty($parts['scheme']) && empty($parts['host']) && !strstr($parts['path'], '@')) {
688 Logger::info('URI was not detectable', ['uri' => $uri]);
692 // If the URI starts with "mailto:" then jump directly to the mail detection
693 if (strpos($uri, 'mailto:') !== false) {
694 $uri = str_replace('mailto:', '', $uri);
695 return self::mail($uri, $uid);
698 if ($network == Protocol::MAIL) {
699 return self::mail($uri, $uid);
702 Logger::info('Probing start', ['uri' => $uri]);
704 if (!empty($ap_profile['addr']) && ($ap_profile['addr'] != $uri)) {
705 $data = self::getWebfingerArray($ap_profile['addr']);
709 $data = self::getWebfingerArray($uri);
713 if (!empty($parts['scheme'])) {
714 return self::feed($uri);
715 } elseif (!empty($uid)) {
716 return self::mail($uri, $uid);
722 $webfinger = $data['webfinger'];
723 $nick = $data['nick'] ?? '';
724 $addr = $data['addr'] ?? '';
725 $baseurl = $data['baseurl'] ?? '';
729 if (in_array($network, ['', Protocol::DFRN])) {
730 $result = self::dfrn($webfinger);
732 if ((!$result && ($network == '')) || ($network == Protocol::DIASPORA)) {
733 $result = self::diaspora($webfinger);
735 $result['networks'][Protocol::DIASPORA] = self::diaspora($webfinger);
737 if ((!$result && ($network == '')) || ($network == Protocol::OSTATUS)) {
738 $result = self::ostatus($webfinger);
740 $result['networks'][Protocol::OSTATUS] = self::ostatus($webfinger);
742 if (in_array($network, ['', Protocol::ZOT])) {
743 $result = self::zot($webfinger, $result, $baseurl);
745 if ((!$result && ($network == '')) || ($network == Protocol::PUMPIO)) {
746 $result = self::pumpio($webfinger, $addr);
748 if (empty($result['network']) && empty($ap_profile['network']) || ($network == Protocol::FEED)) {
749 $result = self::feed($uri);
751 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
752 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
753 if ((empty($result['nick']) || (strstr($result['nick'], ' '))) && ($nick != '')) {
754 $result['nick'] = $nick;
757 if (empty($result['addr']) && ($addr != '')) {
758 $result['addr'] = $addr;
762 $result = self::getSubscribeLink($result, $webfinger);
764 if (empty($result['network'])) {
765 $result['network'] = Protocol::PHANTOM;
768 if (empty($result['baseurl']) && !empty($baseurl)) {
769 $result['baseurl'] = $baseurl;
772 if (empty($result['url'])) {
773 $result['url'] = $uri;
776 Logger::info('Probing done', ['uri' => $uri, 'network' => $result['network']]);
782 * Check for Zot contact
784 * @param array $webfinger Webfinger data
785 * @param array $data previously probed data
786 * @param string $baseUrl Base URL
788 * @return array Zot data
789 * @throws HTTPException\InternalServerErrorException
791 private static function zot(array $webfinger, array $data, string $baseurl): array
793 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
794 foreach ($webfinger['aliases'] as $alias) {
795 if (substr($alias, 0, 5) == 'acct:') {
796 $data['addr'] = substr($alias, 5);
801 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
802 $data['addr'] = substr($webfinger['subject'], 5);
806 foreach ($webfinger['links'] as $link) {
807 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
808 $zot_url = $link['href'];
812 if (empty($zot_url) && !empty($data['addr']) && !empty($baseurl)) {
813 $condition = ['nurl' => Strings::normaliseLink($baseurl), 'platform' => ['hubzilla']];
814 if (!DBA::exists('gserver', $condition)) {
817 $zot_url = $baseurl . '/.well-known/zot-info?address=' . $data['addr'];
820 if (empty($zot_url)) {
824 $data = self::pollZot($zot_url, $data);
826 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
827 foreach ($webfinger['aliases'] as $alias) {
828 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
829 $data['alias'] = $alias;
837 public static function pollZot(string $url, array $data): array
839 $curlResult = DI::httpClient()->get($url, HttpClientAccept::JSON);
840 if ($curlResult->isTimeout()) {
843 $content = $curlResult->getBody();
848 $json = json_decode($content, true);
849 if (!is_array($json)) {
853 if (empty($data['network'])) {
854 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
855 $data['network'] = Protocol::ZOT;
856 } elseif (!isset($json['protocols'])) {
857 $data['network'] = Protocol::ZOT;
861 if (!empty($json['guid']) && empty($data['guid'])) {
862 $data['guid'] = $json['guid'];
864 if (!empty($json['key']) && empty($data['pubkey'])) {
865 $data['pubkey'] = $json['key'];
867 if (!empty($json['name'])) {
868 $data['name'] = $json['name'];
870 if (!empty($json['photo'])) {
871 $data['photo'] = $json['photo'];
872 if (!empty($json['photo_updated'])) {
873 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
876 if (!empty($json['address'])) {
877 $data['addr'] = $json['address'];
879 if (!empty($json['url'])) {
880 $data['url'] = $json['url'];
882 if (!empty($json['connections_url'])) {
883 $data['poco'] = $json['connections_url'];
885 if (isset($json['searchable'])) {
886 $data['hide'] = !$json['searchable'];
888 if (!empty($json['public_forum'])) {
889 $data['community'] = $json['public_forum'];
890 $data['account-type'] = User::PAGE_FLAGS_COMMUNITY;
893 if (!empty($json['profile'])) {
894 $profile = $json['profile'];
895 if (!empty($profile['description'])) {
896 $data['about'] = $profile['description'];
898 if (!empty($profile['keywords'])) {
899 $keywords = implode(', ', $profile['keywords']);
900 if (!empty($keywords)) {
901 $data['keywords'] = $keywords;
906 if (!empty($profile['region'])) {
907 $loc['region'] = $profile['region'];
909 if (!empty($profile['country'])) {
910 $loc['country-name'] = $profile['country'];
912 $location = Profile::formatLocation($loc);
913 if (!empty($location)) {
914 $data['location'] = $location;
922 * Perform a webfinger request.
924 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
926 * @param string $url Address that should be probed
927 * @param string $type type
929 * @return array webfinger data
930 * @throws HTTPException\InternalServerErrorException
932 public static function webfinger(string $url, string $type): array
934 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
936 $curlResult = DI::httpClient()->get($url, $type, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
937 if ($curlResult->isTimeout()) {
938 self::$isTimeout = true;
941 $data = $curlResult->getBody();
943 $webfinger = json_decode($data, true);
944 if (!empty($webfinger)) {
945 if (!isset($webfinger['links'])) {
946 Logger::info('No json webfinger links', ['url' => $url]);
952 // If it is not JSON, maybe it is XML
953 $xrd = XML::parseString($data, true);
954 if (!is_object($xrd)) {
955 Logger::info('No webfinger data retrievable', ['url' => $url]);
959 $xrd_arr = XML::elementToArray($xrd);
960 if (!isset($xrd_arr['xrd']['link'])) {
961 Logger::info('No XML webfinger links', ['url' => $url]);
967 if (!empty($xrd_arr['xrd']['subject'])) {
968 $webfinger['subject'] = $xrd_arr['xrd']['subject'];
971 if (!empty($xrd_arr['xrd']['alias'])) {
972 $webfinger['aliases'] = $xrd_arr['xrd']['alias'];
975 $webfinger['links'] = [];
977 foreach ($xrd_arr['xrd']['link'] as $value => $data) {
978 if (!empty($data['@attributes'])) {
979 $attributes = $data['@attributes'];
980 } elseif ($value == '@attributes') {
986 $webfinger['links'][] = $attributes;
992 * Poll the Friendica specific noscrape page.
994 * "noscrape" is a faster alternative to fetch the data from the hcard.
995 * This functionality was originally created for the directory.
997 * @param string $noscrape_url Link to the noscrape page
998 * @param array $data The already fetched data
1000 * @return array noscrape data
1001 * @throws HTTPException\InternalServerErrorException
1003 private static function pollNoscrape(string $noscrape_url, array $data): array
1005 $curlResult = DI::httpClient()->get($noscrape_url, HttpClientAccept::JSON);
1006 if ($curlResult->isTimeout()) {
1007 self::$isTimeout = true;
1010 $content = $curlResult->getBody();
1012 Logger::info('Empty body', ['url' => $noscrape_url]);
1016 $json = json_decode($content, true);
1017 if (!is_array($json)) {
1018 Logger::info('No json data', ['url' => $noscrape_url]);
1022 if (!empty($json['fn'])) {
1023 $data['name'] = $json['fn'];
1026 if (!empty($json['addr'])) {
1027 $data['addr'] = $json['addr'];
1030 if (!empty($json['nick'])) {
1031 $data['nick'] = $json['nick'];
1034 if (!empty($json['guid'])) {
1035 $data['guid'] = $json['guid'];
1038 if (!empty($json['comm'])) {
1039 $data['community'] = $json['comm'];
1042 if (!empty($json['tags'])) {
1043 $keywords = implode(', ', $json['tags']);
1044 if ($keywords != '') {
1045 $data['keywords'] = $keywords;
1049 $location = Profile::formatLocation($json);
1051 $data['location'] = $location;
1054 if (!empty($json['about'])) {
1055 $data['about'] = $json['about'];
1058 if (!empty($json['xmpp'])) {
1059 $data['xmpp'] = $json['xmpp'];
1062 if (!empty($json['matrix'])) {
1063 $data['matrix'] = $json['matrix'];
1066 if (!empty($json['key'])) {
1067 $data['pubkey'] = $json['key'];
1070 if (!empty($json['photo'])) {
1071 $data['photo'] = $json['photo'];
1074 if (!empty($json['dfrn-request'])) {
1075 $data['request'] = $json['dfrn-request'];
1078 if (!empty($json['dfrn-confirm'])) {
1079 $data['confirm'] = $json['dfrn-confirm'];
1082 if (!empty($json['dfrn-notify'])) {
1083 $data['notify'] = $json['dfrn-notify'];
1086 if (!empty($json['dfrn-poll'])) {
1087 $data['poll'] = $json['dfrn-poll'];
1090 if (isset($json['hide'])) {
1091 $data['hide'] = (bool)$json['hide'];
1093 $data['hide'] = false;
1100 * Check for valid DFRN data
1102 * @param array $data DFRN data
1104 * @return int Number of errors
1106 public static function validDfrn(array $data): int
1109 if (!isset($data['key'])) {
1112 if (!isset($data['dfrn-request'])) {
1115 if (!isset($data['dfrn-confirm'])) {
1118 if (!isset($data['dfrn-notify'])) {
1121 if (!isset($data['dfrn-poll'])) {
1128 * Fetch data from a DFRN profile page and via "noscrape"
1130 * @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(string $profile_link): array
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
1182 * @return array DFRN data
1183 * @throws HTTPException\InternalServerErrorException
1185 private static function dfrn(array $webfinger): array
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 ')) {
1212 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1217 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1218 foreach ($webfinger['aliases'] as $alias) {
1219 if (empty($data['url']) && !strstr($alias, '@')) {
1220 $data['url'] = $alias;
1221 } elseif (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
1222 $data['alias'] = $alias;
1223 } elseif (substr($alias, 0, 5) == 'acct:') {
1224 $data['addr'] = substr($alias, 5);
1229 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1230 $data['addr'] = substr($webfinger['subject'], 5);
1233 if (!isset($data['network']) || ($hcard_url == '')) {
1237 // Fetch data via noscrape - this is faster
1238 $noscrape_url = str_replace('/hcard/', '/noscrape/', $hcard_url);
1239 $data = self::pollNoscrape($noscrape_url, $data);
1241 if (isset($data['notify'])
1242 && isset($data['confirm'])
1243 && isset($data['request'])
1244 && isset($data['poll'])
1245 && isset($data['name'])
1246 && isset($data['photo'])
1251 $data = self::pollHcard($hcard_url, $data, true);
1257 * Poll the hcard page (Diaspora and Friendica specific)
1259 * @param string $hcard_url Link to the hcard page
1260 * @param array $data The already fetched data
1261 * @param boolean $dfrn Poll DFRN specific data
1262 * @return array hcard data
1263 * @throws HTTPException\InternalServerErrorException
1265 private static function pollHcard(string $hcard_url, array $data, bool $dfrn = false): array
1267 $curlResult = DI::httpClient()->get($hcard_url, HttpClientAccept::HTML);
1268 if ($curlResult->isTimeout()) {
1269 self::$isTimeout = true;
1272 $content = $curlResult->getBody();
1273 if (empty($content)) {
1277 $doc = new DOMDocument();
1278 if (!@$doc->loadHTML($content)) {
1282 $xpath = new DomXPath($doc);
1284 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1285 if (!is_object($vcards)) {
1289 if (!isset($data['baseurl'])) {
1290 $data['baseurl'] = '';
1293 if ($vcards->length > 0) {
1294 $vcard = $vcards->item(0);
1296 // We have to discard the guid from the hcard in favour of the guid from lrdd
1297 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1298 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1299 if (($search->length > 0) && empty($data['guid'])) {
1300 $data['guid'] = $search->item(0)->nodeValue;
1303 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1304 if ($search->length > 0) {
1305 $data['nick'] = $search->item(0)->nodeValue;
1308 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1309 if ($search->length > 0) {
1310 $data['name'] = $search->item(0)->nodeValue;
1313 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' given_name ')]", $vcard); // */
1314 if ($search->length > 0) {
1315 $data["given_name"] = $search->item(0)->nodeValue;
1318 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' family_name ')]", $vcard); // */
1319 if ($search->length > 0) {
1320 $data["family_name"] = $search->item(0)->nodeValue;
1323 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1324 if ($search->length > 0) {
1325 $data['hide'] = (strtolower($search->item(0)->nodeValue) != 'true');
1328 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1329 if ($search->length > 0) {
1330 $data['pubkey'] = $search->item(0)->nodeValue;
1331 if (strstr($data['pubkey'], 'RSA ')) {
1332 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1336 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1337 if ($search->length > 0) {
1338 $data['baseurl'] = trim($search->item(0)->nodeValue, '/');
1343 if (!empty($vcard)) {
1344 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1345 foreach ($photos as $photo) {
1347 foreach ($photo->attributes as $attribute) {
1348 $attr[$attribute->name] = trim($attribute->value);
1351 if (isset($attr['src']) && isset($attr['width'])) {
1352 $avatars[$attr['width']] = self::fixAvatar($attr['src'], $data['baseurl']);
1355 // We don't have a width. So we just take everything that we got.
1356 // This is a Hubzilla workaround which doesn't send a width.
1357 if (!$avatars && !empty($attr['src'])) {
1358 $avatars[] = self::fixAvatar($attr['src'], $data['baseurl']);
1365 $data['photo'] = array_pop($avatars);
1367 $data['photo_medium'] = array_pop($avatars);
1371 $data['photo_small'] = array_pop($avatars);
1376 // Poll DFRN specific data
1377 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1378 if ($search->length > 0) {
1379 foreach ($search as $link) {
1380 //$data['request'] = $search->item(0)->nodeValue;
1382 foreach ($link->attributes as $attribute) {
1383 $attr[$attribute->name] = trim($attribute->value);
1386 $data[substr($attr['rel'], 5)] = $attr['href'];
1390 // Older Friendica versions had used the "uid" field differently than newer versions
1391 if (!empty($data['nick']) && !empty($data['guid']) && ($data['nick'] == $data['guid'])) {
1392 unset($data['guid']);
1400 * Check for Diaspora contact
1402 * @param array $webfinger Webfinger data
1404 * @return array Diaspora data
1405 * @throws HTTPException\InternalServerErrorException
1407 private static function diaspora(array $webfinger): array
1412 // The array is reversed to take into account the order of preference for same-rel links
1413 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1414 foreach (array_reverse($webfinger['links']) as $link) {
1415 if (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1416 $hcard_url = $link['href'];
1417 } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1418 $data['baseurl'] = trim($link['href'], '/');
1419 } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1420 $data['guid'] = $link['href'];
1421 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1422 $data['url'] = $link['href'];
1423 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && empty($link['type']) && !empty($link['href'])) {
1424 $profile_url = $link['href'];
1425 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1426 $data['poll'] = $link['href'];
1427 } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1428 $data['poco'] = $link['href'];
1429 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1430 $data['notify'] = $link['href'];
1431 } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1432 $data['pubkey'] = base64_decode($link['href']);
1434 if (strstr($data['pubkey'], 'RSA ')) {
1435 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1440 if (empty($data['url']) && !empty($profile_url)) {
1441 $data['url'] = $profile_url;
1444 if (empty($data['url']) || empty($hcard_url)) {
1448 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1449 foreach ($webfinger['aliases'] as $alias) {
1450 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data['url']) && ! strstr($alias, '@')) {
1451 $data['alias'] = $alias;
1452 } elseif (substr($alias, 0, 5) == 'acct:') {
1453 $data['addr'] = substr($alias, 5);
1458 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1459 $data['addr'] = substr($webfinger['subject'], 5);
1462 // Fetch further information from the hcard
1463 $data = self::pollHcard($hcard_url, $data);
1469 if (!empty($data['url'])
1470 && !empty($data['guid'])
1471 && !empty($data['baseurl'])
1472 && !empty($data['pubkey'])
1473 && !empty($hcard_url)
1475 $data['network'] = Protocol::DIASPORA;
1476 $data['manually-approve'] = false;
1478 // The Diaspora handle must always be lowercase
1479 if (!empty($data['addr'])) {
1480 $data['addr'] = strtolower($data['addr']);
1483 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1484 $data['notify'] = $data['baseurl'] . '/receive/users/' . $data['guid'];
1485 $data['batch'] = $data['baseurl'] . '/receive/public';
1494 * Check for OStatus contact
1496 * @param array $webfinger Webfinger data
1497 * @param bool $short Short detection mode
1499 * @return array|bool OStatus data or "false" on error or "true" on short mode
1500 * @throws HTTPException\InternalServerErrorException
1502 private static function ostatus(array $webfinger, bool $short = false)
1506 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1507 foreach ($webfinger['aliases'] as $alias) {
1508 if (strstr($alias, '@') && !strstr(Strings::normaliseLink($alias), 'http://')) {
1509 $data['addr'] = str_replace('acct:', '', $alias);
1514 if (!empty($webfinger['subject']) && strstr($webfinger['subject'], '@')
1515 && !strstr(Strings::normaliseLink($webfinger['subject']), 'http://')
1517 $data['addr'] = str_replace('acct:', '', $webfinger['subject']);
1520 if (!empty($webfinger['links'])) {
1521 // The array is reversed to take into account the order of preference for same-rel links
1522 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1523 foreach (array_reverse($webfinger['links']) as $link) {
1524 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1525 && (($link['type'] ?? '') == 'text/html')
1526 && ($link['href'] != '')
1528 $data['url'] = $data['alias'] = $link['href'];
1529 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1530 $data['notify'] = $link['href'];
1531 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1532 $data['poll'] = $link['href'];
1533 } elseif (($link['rel'] == 'magic-public-key') && !empty($link['href'])) {
1534 $pubkey = $link['href'];
1536 if (substr($pubkey, 0, 5) === 'data:') {
1537 if (strstr($pubkey, ',')) {
1538 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1540 $pubkey = substr($pubkey, 5);
1542 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1543 $curlResult = DI::httpClient()->get($pubkey, HttpClientAccept::MAGIC_KEY);
1544 if ($curlResult->isTimeout()) {
1545 self::$isTimeout = true;
1546 return $short ? false : [];
1548 Logger::debug('Fetched public key', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $pubkey]);
1549 $pubkey = $curlResult->getBody();
1553 $data['pubkey'] = Salmon::magicKeyToPem($pubkey);
1554 } catch (\Throwable $e) {
1561 if (isset($data['notify']) && isset($data['pubkey'])
1562 && isset($data['poll'])
1563 && isset($data['url'])
1565 $data['network'] = Protocol::OSTATUS;
1566 $data['manually-approve'] = false;
1568 return $short ? false : [];
1575 // Fetch all additional data from the feed
1576 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::FEED_XML);
1577 if ($curlResult->isTimeout()) {
1578 self::$isTimeout = true;
1581 $feed = $curlResult->getBody();
1582 $feed_data = Feed::import($feed);
1587 if (!empty($feed_data['header']['author-name'])) {
1588 $data['name'] = $feed_data['header']['author-name'];
1590 if (!empty($feed_data['header']['author-nick'])) {
1591 $data['nick'] = $feed_data['header']['author-nick'];
1593 if (!empty($feed_data['header']['author-avatar'])) {
1594 $data['photo'] = self::fixAvatar($feed_data['header']['author-avatar'], $data['url']);
1596 if (!empty($feed_data['header']['author-id'])) {
1597 $data['alias'] = $feed_data['header']['author-id'];
1599 if (!empty($feed_data['header']['author-location'])) {
1600 $data['location'] = $feed_data['header']['author-location'];
1602 if (!empty($feed_data['header']['author-about'])) {
1603 $data['about'] = $feed_data['header']['author-about'];
1605 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1606 // So we take the value that we just fetched, although the other one worked as well
1607 if (!empty($feed_data['header']['author-link'])) {
1608 $data['url'] = $feed_data['header']['author-link'];
1611 if ($data['url'] == $data['alias']) {
1612 $data['alias'] = '';
1615 /// @todo Fetch location and "about" from the feed as well
1620 * Fetch data from a pump.io profile page
1622 * @param string $profile_link Link to the profile page
1624 * @return array Profile data
1626 private static function pumpioProfileData(string $profile_link): array
1628 $curlResult = DI::httpClient()->get($profile_link, HttpClientAccept::HTML);
1629 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
1633 $doc = new DOMDocument();
1634 if (!@$doc->loadHTML($curlResult->getBody())) {
1638 $xpath = new DomXPath($doc);
1641 $data['name'] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1643 if ($data['name'] == '') {
1644 // This is ugly - but pump.io doesn't seem to know a better way for it
1645 $data['name'] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1646 $pos = strpos($data['name'], chr(10));
1648 $data['name'] = trim(substr($data['name'], 0, $pos));
1652 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1654 if ($data['location'] == '') {
1655 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1658 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1660 if ($data['about'] == '') {
1661 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1664 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1666 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1669 foreach ($avatar->attributes as $attribute) {
1670 if ($attribute->name == 'src') {
1671 $data['photo'] = trim($attribute->value);
1680 * Check for pump.io contact
1682 * @param array $webfinger Webfinger data
1683 * @param string $addr
1685 * @return array pump.io data
1687 private static function pumpio(array $webfinger, string $addr): array
1690 // The array is reversed to take into account the order of preference for same-rel links
1691 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1692 foreach (array_reverse($webfinger['links']) as $link) {
1693 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1694 && (($link['type'] ?? '') == 'text/html')
1695 && ($link['href'] != '')
1697 $data['url'] = $link['href'];
1698 } elseif (($link['rel'] == 'activity-inbox') && ($link['href'] != '')) {
1699 $data['notify'] = $link['href'];
1700 } elseif (($link['rel'] == 'activity-outbox') && ($link['href'] != '')) {
1701 $data['poll'] = $link['href'];
1702 } elseif (($link['rel'] == 'dialback') && ($link['href'] != '')) {
1703 $data['dialback'] = $link['href'];
1706 if (isset($data['poll']) && isset($data['notify'])
1707 && isset($data['dialback'])
1708 && isset($data['url'])
1710 // by now we use these fields only for the network type detection
1711 // So we unset all data that isn't used at the moment
1712 unset($data['dialback']);
1714 $data['network'] = Protocol::PUMPIO;
1719 $profile_data = self::pumpioProfileData($data['url']);
1721 if (!$profile_data) {
1725 $data = array_merge($data, $profile_data);
1727 if (($addr != '') && ($data['name'] != '')) {
1728 $name = trim(str_replace($addr, '', $data['name']));
1730 $data['name'] = $name;
1738 * Checks HTML page for RSS feed link
1740 * @param string $url Page link
1741 * @param string $body Page body string
1743 * @return string|false Feed link or false if body was invalid HTML document
1745 public static function getFeedLink(string $url, string $body)
1751 $doc = new DOMDocument();
1752 if (!@$doc->loadHTML($body)) {
1756 $xpath = new DOMXPath($doc);
1758 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1759 $feedUrl = $feedUrl ?: $xpath->evaluate('string(/html/head/link[@type="application/atom+xml" and @rel="alternate"]/@href)');
1761 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1767 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1769 * Loosely based on RFC 1808
1771 * @see https://tools.ietf.org/html/rfc1808
1773 * @param string $href The potential relative href found in the HTML document
1774 * @param string $base The HTML document URL
1775 * @param DOMXPath $xpath The HTML document XPath
1777 * @return string Absolute URL
1779 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath): string
1781 if (filter_var($href, FILTER_VALIDATE_URL)) {
1785 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1787 $baseParts = parse_url($base);
1788 if (empty($baseParts['host'])) {
1792 // Naked domain case (scheme://basehost)
1793 $path = $baseParts['path'] ?? '/';
1795 // Remove the filename part of the path if it exists (/base/path/file)
1796 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1798 $hrefParts = parse_url($href);
1800 if (!empty($hrefParts['path'])) {
1801 // Root path case (/path) including relative scheme case (//host/path)
1802 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1803 $path = $hrefParts['path'];
1805 $path = $path . '/' . $hrefParts['path'];
1807 // Resolve arbitrary relative path
1808 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1809 $parts = array_filter(explode('/', $path), 'strlen');
1811 foreach ($parts as $part) {
1812 if ('.' == $part) continue;
1813 if ('..' == $part) {
1814 array_pop($absolutes);
1816 $absolutes[] = $part;
1820 $path = '/' . implode('/', $absolutes);
1824 // Relative scheme case (//host/path)
1825 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1826 $baseParts['path'] = $path;
1827 unset($baseParts['query']);
1828 unset($baseParts['fragment']);
1830 return Network::unparseURL($baseParts);
1834 * Check for feed contact
1836 * @param string $url Profile link
1837 * @param boolean $probe Do a probe if the page contains a feed link
1839 * @return array feed data
1840 * @throws HTTPException\InternalServerErrorException
1842 private static function feed(string $url, bool $probe = true): array
1844 $curlResult = DI::httpClient()->get($url, HttpClientAccept::FEED_XML);
1845 if ($curlResult->isTimeout()) {
1846 self::$isTimeout = true;
1849 $feed = $curlResult->getBody();
1850 $feed_data = Feed::import($feed);
1857 $feed_url = self::getFeedLink($url, $feed);
1863 return self::feed($feed_url, false);
1866 if (!empty($feed_data['header']['author-name'])) {
1867 $data['name'] = $feed_data['header']['author-name'];
1870 if (!empty($feed_data['header']['author-nick'])) {
1871 $data['nick'] = $feed_data['header']['author-nick'];
1874 if (!empty($feed_data['header']['author-avatar'])) {
1875 $data['photo'] = $feed_data['header']['author-avatar'];
1878 if (!empty($feed_data['header']['author-id'])) {
1879 $data['alias'] = $feed_data['header']['author-id'];
1882 $data['url'] = $url;
1883 $data['poll'] = $url;
1885 $data['network'] = Protocol::FEED;
1891 * Check for mail contact
1893 * @param string $uri Profile link
1894 * @param integer $uid User ID
1896 * @return array mail data
1897 * @throws \Exception
1899 private static function mail(string $uri, int $uid): array
1901 if (!Network::isEmailDomainValid($uri)) {
1909 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1911 $condition = ["`uid` = ? AND `server` != ''", $uid];
1912 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1913 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1915 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1919 $mailbox = Email::constructMailboxName($mailacct);
1921 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1922 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1927 $msgs = Email::poll($mbox, $uri);
1928 Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
1930 if (!count($msgs)) {
1934 $phost = substr($uri, strpos($uri, '@') + 1);
1938 'network' => Protocol::MAIL,
1939 'name' => substr($uri, 0, strpos($uri, '@')),
1940 'photo' => Network::lookupAvatarByEmail($uri),
1941 'url' => 'mailto:' . $uri,
1942 'notify' => 'smtp ' . Strings::getRandomHex(),
1943 'poll' => 'email ' . Strings::getRandomHex(),
1946 $data['nick'] = $data['name'];
1948 $x = Email::messageMeta($mbox, $msgs[0]);
1950 if (stristr($x[0]->from, $uri)) {
1951 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1952 } elseif (stristr($x[0]->to, $uri)) {
1953 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1957 foreach ($adr as $feadr) {
1958 if ((strcasecmp($feadr->mailbox, $data['name']) == 0)
1959 &&(strcasecmp($feadr->host, $phost) == 0)
1960 && (strlen($feadr->personal))
1962 $personal = imap_mime_header_decode($feadr->personal);
1964 foreach ($personal as $perspart) {
1965 if ($perspart->charset != 'default') {
1966 $data['name'] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1968 $data['name'] .= $perspart->text;
1975 if (!empty($mbox)) {
1983 * Mix two paths together to possibly fix missing parts
1985 * @param string $avatar Path to the avatar
1986 * @param string $base Another path that is hopefully complete
1988 * @return string fixed avatar path
1989 * @throws \Exception
1991 public static function fixAvatar(string $avatar, string $base): string
1993 $base_parts = parse_url($base);
1995 // Remove all parts that could create a problem
1996 unset($base_parts['path']);
1997 unset($base_parts['query']);
1998 unset($base_parts['fragment']);
2000 $avatar_parts = parse_url($avatar);
2003 $parts = array_merge($base_parts, $avatar_parts);
2005 // And put them together again
2006 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
2007 $host = isset($parts['host']) ? $parts['host'] : '';
2008 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
2009 $path = isset($parts['path']) ? $parts['path'] : '';
2010 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
2011 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
2013 $fixed = $scheme.$host.$port.$path.$query.$fragment;
2015 Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
2021 * Fetch the last date that the contact had posted something (publically)
2023 * @param array $data probing result
2025 * @return string last activity
2027 public static function getLastUpdate(array $data): string
2029 $uid = User::getIdForURL($data['url']);
2031 $contact = Contact::selectFirst(['url', 'last-item'], ['self' => true, 'uid' => $uid]);
2032 if (!empty($contact['last-item'])) {
2033 return $contact['last-item'];
2037 if ($lastUpdate = self::updateFromNoScrape($data)) {
2041 if (!empty($data['outbox'])) {
2042 return self::updateFromOutbox($data['outbox'], $data);
2043 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
2044 return self::updateFromOutbox($data['poll'], $data);
2045 } elseif (!empty($data['poll'])) {
2046 return self::updateFromFeed($data);
2053 * Fetch the last activity date from the "noscrape" endpoint
2055 * @param array $data Probing result
2057 * @return string last activity or true if update was successful or the server was unreachable
2059 private static function updateFromNoScrape(array $data): string
2061 if (empty($data['baseurl'])) {
2065 // Check the 'noscrape' endpoint when it is a Friendica server
2066 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
2067 Strings::normaliseLink($data['baseurl'])]);
2068 if (!DBA::isResult($gserver)) {
2072 $curlResult = DI::httpClient()->get($gserver['noscrape'] . '/' . $data['nick'], HttpClientAccept::JSON);
2074 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
2075 $noscrape = json_decode($curlResult->getBody(), true);
2076 if (!empty($noscrape) && !empty($noscrape['updated'])) {
2077 return DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2085 * Fetch the last activity date from an ActivityPub Outbox
2087 * @param string $feed
2088 * @param array $data Probing result
2090 * @return string last activity
2091 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2093 private static function updateFromOutbox(string $feed, array $data): string
2095 $outbox = ActivityPub::fetchContent($feed);
2096 if (empty($outbox)) {
2100 if (!empty($outbox['orderedItems'])) {
2101 $items = $outbox['orderedItems'];
2102 } elseif (!empty($outbox['first']['orderedItems'])) {
2103 $items = $outbox['first']['orderedItems'];
2104 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2105 return self::updateFromOutbox($outbox['first']['href'], $data);
2106 } elseif (!empty($outbox['first'])) {
2107 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2108 return self::updateFromOutbox($outbox['first'], $data);
2110 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2118 foreach ($items as $activity) {
2119 if (!empty($activity['published'])) {
2120 $published = DateTimeFormat::utc($activity['published']);
2121 } elseif (!empty($activity['object']['published'])) {
2122 $published = DateTimeFormat::utc($activity['object']['published']);
2127 if ($last_updated < $published) {
2128 $last_updated = $published;
2132 if (!empty($last_updated)) {
2133 return $last_updated;
2140 * Fetch the last activity date from an XML feed
2142 * @param array $data Probing result
2143 * @return string last activity
2145 private static function updateFromFeed(array $data): string
2147 // Search for the newest entry in the feed
2148 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::ATOM_XML);
2149 if (!$curlResult->isSuccess() || !$curlResult->getBody()) {
2153 $doc = new DOMDocument();
2154 @$doc->loadXML($curlResult->getBody());
2156 $xpath = new DOMXPath($doc);
2157 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2159 $entries = $xpath->query('/atom:feed/atom:entry');
2163 foreach ($entries as $entry) {
2164 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2165 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
2166 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2167 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2169 if (empty($published) || empty($updated)) {
2170 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2174 if ($last_updated < $published) {
2175 $last_updated = $published;
2178 if ($last_updated < $updated) {
2179 $last_updated = $updated;
2183 if (!empty($last_updated)) {
2184 return $last_updated;
2191 * Probe data from local profiles without network traffic
2193 * @param string $url
2195 * @return array probed data
2196 * @throws HTTPException\InternalServerErrorException
2197 * @throws HTTPException\NotFoundException
2199 private static function localProbe(string $url): array
2202 $uid = User::getIdForURL($url);
2204 throw new HTTPException\NotFoundException('User not found.');
2207 $owner = User::getOwnerDataById($uid);
2208 $approfile = ActivityPub\Transmitter::getProfile($uid);
2210 if (empty($owner['gsid'])) {
2211 $owner['gsid'] = GServer::getID($approfile['generator']['url']);
2215 'name' => $owner['name'], 'nick' => $owner['nick'], 'guid' => $approfile['diaspora:guid'] ?? '',
2216 'url' => $owner['url'], 'addr' => $owner['addr'], 'alias' => $owner['alias'],
2217 'photo' => User::getAvatarUrl($owner),
2218 'header' => $owner['header'] ? Contact::getHeaderUrlForId($owner['id'], $owner['updated']) : '',
2219 'account-type' => $owner['contact-type'], 'community' => ($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY),
2220 'keywords' => $owner['keywords'], 'location' => $owner['location'], 'about' => $owner['about'],
2221 'xmpp' => $owner['xmpp'], 'matrix' => $owner['matrix'],
2222 'hide' => !$owner['net-publish'], 'batch' => '', 'notify' => $owner['notify'],
2223 'poll' => $owner['poll'], 'request' => $owner['request'], 'confirm' => $owner['confirm'],
2224 'subscribe' => $approfile['generator']['url'] . '/contact/follow?url={uri}', 'poco' => $owner['poco'],
2225 'following' => $approfile['following'], 'followers' => $approfile['followers'],
2226 'inbox' => $approfile['inbox'], 'outbox' => $approfile['outbox'],
2227 'sharedinbox' => $approfile['endpoints']['sharedInbox'], 'network' => Protocol::DFRN,
2228 'pubkey' => $owner['upubkey'], 'baseurl' => $approfile['generator']['url'], 'gsid' => $owner['gsid'],
2229 'manually-approve' => in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])
2231 } catch (Exception $e) {
2232 // Default values for non existing targets
2234 'name' => $url, 'nick' => $url, 'url' => $url, 'network' => Protocol::PHANTOM,
2235 'photo' => DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO
2239 return self::rearrangeData($data);