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\Diaspora;
42 use Friendica\Protocol\Email;
43 use Friendica\Protocol\Feed;
44 use Friendica\Protocol\Salmon;
45 use Friendica\Util\Crypto;
46 use Friendica\Util\DateTimeFormat;
47 use Friendica\Util\Network;
48 use Friendica\Util\Strings;
49 use Friendica\Util\XML;
50 use GuzzleHttp\Psr7\Uri;
53 * This class contain functions for probing URL
57 const HOST_META = '/.well-known/host-meta';
58 const WEBFINGER = '/.well-known/webfinger?resource={uri}';
61 * @var string Base URL
63 private static $baseurl;
66 * @var boolean Whether a timeout has occured
68 private static $isTimeout;
71 * Checks if the provided network can be probed
73 * @param string $network
77 public static function isProbable(string $network): bool
79 return (in_array($network, array_merge(Protocol::FEDERATED, [Protocol::ZOT, Protocol::PHANTOM])));
83 * Remove stuff from an URI that doesn't belong there
85 * @param string $rawUri
86 * @return string Cleaned URI
88 public static function cleanURI(string $rawUri): string
90 // At first remove leading and trailing junk
91 $rawUri = trim($rawUri, "@#?: \t\n\r\0\x0B");
93 $rawUri = Network::convertToIdn($rawUri);
95 $uri = new Uri($rawUri);
96 if (!$uri->getScheme()) {
97 return $uri->__toString();
100 // Remove the URL fragment, since these shouldn't be part of any profile URL
101 $uri = $uri->withFragment('');
103 return $uri->__toString();
107 * Rearrange the array so that it always has the same order
109 * @param array $data Unordered data
110 * @return array Ordered data
112 private static function rearrangeData(array $data): array
114 $fields = ['name', 'given_name', 'family_name', 'nick', 'guid', 'url', 'addr', 'alias',
115 'photo', 'photo_medium', 'photo_small', 'header',
116 'account-type', 'community', 'keywords', 'location', 'about', 'xmpp', 'matrix',
117 'hide', 'batch', 'notify', 'poll', 'request', 'confirm', 'subscribe', 'poco',
118 'following', 'followers', 'inbox', 'outbox', 'sharedinbox',
119 'priority', 'network', 'pubkey', 'manually-approve', 'baseurl', 'gsid'];
121 $numeric_fields = ['gsid', 'hide', 'account-type', 'manually-approve'];
124 foreach ($fields as $field) {
125 if (isset($data[$field])) {
126 if (in_array($field, $numeric_fields)) {
127 $newdata[$field] = (int)$data[$field];
129 $newdata[$field] = trim($data[$field]);
131 } elseif (!in_array($field, $numeric_fields)) {
132 $newdata[$field] = '';
134 $newdata[$field] = null;
138 $newdata['networks'] = [];
139 foreach ([Protocol::DIASPORA, Protocol::OSTATUS] as $network) {
140 if (!empty($data['networks'][$network])) {
141 $data['networks'][$network]['subscribe'] = $newdata['subscribe'] ?? '';
142 $data['networks'][$network]['baseurl'] = $newdata['baseurl'] ?? '';
143 $data['networks'][$network]['gsid'] = $newdata['gsid'] ?? 0;
144 $newdata['networks'][$network] = self::rearrangeData($data['networks'][$network]);
145 unset($newdata['networks'][$network]['networks']);
149 // We don't use the "priority" field anymore and replace it with a dummy.
150 $newdata['priority'] = 0;
156 * Check if the hostname belongs to the own server
158 * @param string $host The hostname that is to be checked
159 * @return bool Does the testes hostname belongs to the own server?
161 private static function ownHost(string $host): bool
163 $own_host = DI::baseUrl()->getHostname();
165 $parts = parse_url($host);
167 if (!isset($parts['scheme'])) {
168 $parts = parse_url('http://' . $host);
171 if (!isset($parts['host'])) {
174 return $parts['host'] == $own_host;
178 * Probes for webfinger path via "host-meta"
180 * We have to check if the servers in the future still will offer this.
181 * It seems as if it was dropped from the standard.
183 * @param string $host The host part of an url
185 * @return array with template and type of the webfinger template for JSON or XML
186 * @throws HTTPException\InternalServerErrorException
188 private static function hostMeta(string $host): array
190 // Reset the static variable
193 // Handles the case when the hostname contains the scheme
194 if (!parse_url($host, PHP_URL_SCHEME)) {
195 $ssl_url = 'https://' . $host . self::HOST_META;
196 $url = 'http://' . $host . self::HOST_META;
198 $ssl_url = $host . self::HOST_META;
202 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
204 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
207 $curlResult = DI::httpClient()->get($ssl_url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
208 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
209 if ($curlResult->isSuccess()) {
210 $xml = $curlResult->getBody();
211 $xrd = XML::parseString($xml, true);
213 $host_url = 'https://' . $host;
217 } elseif ($curlResult->isTimeout()) {
218 Logger::info('Probing timeout', ['url' => $ssl_url]);
219 self::$isTimeout = true;
223 if (!is_object($xrd) && !empty($url)) {
224 $curlResult = DI::httpClient()->get($url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
225 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
226 if ($curlResult->isTimeout()) {
227 Logger::info('Probing timeout', ['url' => $url]);
228 self::$isTimeout = true;
230 } elseif ($connection_error && $ssl_connection_error) {
231 self::$isTimeout = true;
235 $xml = $curlResult->getBody();
236 $xrd = XML::parseString($xml, true);
237 $host_url = 'http://'.$host;
239 if (!is_object($xrd)) {
240 Logger::info('No xrd object found', ['host' => $host]);
244 $links = XML::elementToArray($xrd);
245 if (!isset($links['xrd']['link'])) {
246 Logger::info('No xrd data found', ['host' => $host]);
252 foreach ($links['xrd']['link'] as $value => $link) {
253 if (!empty($link['@attributes'])) {
254 $attributes = $link['@attributes'];
255 } elseif ($value == '@attributes') {
261 if (!empty($attributes['rel']) && $attributes['rel'] == 'lrdd' && !empty($attributes['template'])) {
262 $type = (empty($attributes['type']) ? '' : $attributes['type']);
264 $lrdd[$type] = $attributes['template'];
268 if (Network::isUrlBlocked($host_url)) {
269 Logger::info('Domain is blocked', ['url' => $host]);
273 self::$baseurl = $host_url;
275 Logger::info('Probing successful', ['host' => $host]);
281 * Check an URI for LRDD data
283 * @param string $uri Address that should be probed
284 * @return array uri data
285 * @throws HTTPException\InternalServerErrorException
287 public static function lrdd(string $uri): array
289 $data = self::getWebfingerArray($uri);
293 $webfinger = $data['webfinger'];
295 if (empty($webfinger['links'])) {
296 Logger::info('No webfinger links found', ['uri' => $uri]);
302 foreach ($webfinger['links'] as $link) {
303 $data[] = ['@attributes' => $link];
306 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
307 foreach ($webfinger['aliases'] as $alias) {
321 * Fetch information (protocol endpoints and user information) about a given uri
323 * @param string $uri Address that should be probed
324 * @param string $network Test for this specific network
325 * @param integer $uid User ID for the probe (only used for mails)
326 * @param boolean $cache Use cached values?
328 * @return array uri data
329 * @throws HTTPException\InternalServerErrorException
330 * @throws \ImagickException
332 public static function uri(string $uri, string $network = '', int $uid = -1): array
334 // Local profiles aren't probed via network
335 if (empty($network) && Contact::isLocal($uri)) {
336 $data = self::localProbe($uri);
343 $uid = DI::userSession()->getLocalUserId();
346 if (empty($network) || ($network == Protocol::ACTIVITYPUB)) {
347 $ap_profile = ActivityPub::probeProfile($uri);
352 self::$isTimeout = false;
354 if ($network != Protocol::ACTIVITYPUB) {
355 $data = self::detect($uri, $network, $uid, $ap_profile);
356 if (!is_array($data)) {
359 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
360 $networks = $data['networks'] ?? [];
361 unset($data['networks']);
362 if (!empty($data['network'])) {
363 $networks[$data['network']] = $data;
366 $data['networks'] = $networks;
367 } elseif (!empty($ap_profile)) {
368 $ap_profile['batch'] = '';
369 $data = array_merge($ap_profile, $data);
375 if (!isset($data['url'])) {
379 if (empty($data['photo'])) {
380 $data['photo'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
383 if (empty($data['name'])) {
384 if (!empty($data['nick'])) {
385 $data['name'] = $data['nick'];
388 if (empty($data['name'])) {
389 $data['name'] = $data['url'];
393 if (empty($data['nick'])) {
394 $data['nick'] = strtolower($data['name']);
396 if (strpos($data['nick'], ' ')) {
397 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
401 if (!empty($data['baseurl']) && empty($data['gsid'])) {
402 $data['gsid'] = GServer::getID($data['baseurl']);
405 if (empty($data['network'])) {
406 $data['network'] = Protocol::PHANTOM;
409 // Ensure that local connections always are DFRN
410 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
411 $data['network'] = Protocol::DFRN;
414 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
415 $data['hide'] = self::getHideStatus($data['url']);
418 return self::rearrangeData($data);
423 * Fetches the "hide" status from the profile
425 * @param string $url URL of the profile
426 * @return boolean "hide" status
428 private static function getHideStatus(string $url): bool
430 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::CONTENT_LENGTH => 1000000]);
431 if (!$curlResult->isSuccess()) {
435 // If it isn't a HTML file then exit
436 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
440 $body = $curlResult->getBody();
445 $doc = new DOMDocument();
446 @$doc->loadHTML($body);
448 $xpath = new DOMXPath($doc);
450 $list = $xpath->query('//meta[@name]');
451 foreach ($list as $node) {
453 if ($node->attributes->length) {
454 foreach ($node->attributes as $attribute) {
455 $meta_tag[$attribute->name] = $attribute->value;
459 if (empty($meta_tag['content'])) {
463 $content = strtolower(trim($meta_tag['content']));
465 switch (strtolower(trim($meta_tag['name']))) {
466 case 'dfrn-global-visibility':
467 if ($content == 'false') {
472 if (strpos($content, 'noindex') !== false) {
483 * Fetch the "subscribe" and add it to the result
485 * @param array $result Result array
486 * @param array $webfinger Webfinger data
488 * @return array result Altered/unaltered result array
490 private static function getSubscribeLink(array $result, array $webfinger): array
492 if (empty($webfinger['links'])) {
496 foreach ($webfinger['links'] as $link) {
497 if (!empty($link['template']) && ($link['rel'] === ActivityNamespace::OSTATUSSUB)) {
498 $result['subscribe'] = $link['template'];
506 * Get webfinger data from a given URI
508 * @param string $uri URI
510 * @return array Webfinger data
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, HttpClientAccept::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, HttpClientAccept::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, HttpClientAccept::JRD_JSON, $uri, $addr);
567 if (self::$isTimeout) {
571 if (empty($webfinger)) {
572 $webfinger = self::getWebfinger('http://' . $host . self::WEBFINGER, HttpClientAccept::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
626 * @return array webfinger results
628 private static function getWebfinger(string $template, string $type, string $uri, string $addr): array
630 if (Network::isUrlBlocked($template)) {
631 Logger::info('Domain is blocked', ['url' => $template]);
635 // First try the address because this is the primary purpose of webfinger
638 $path = str_replace('{uri}', urlencode('acct:' . $addr), $template);
639 $webfinger = self::webfinger($path, $type);
640 if (self::$isTimeout) {
646 if (empty($webfinger) && $uri != $addr) {
648 $path = str_replace('{uri}', urlencode($uri), $template);
649 $webfinger = self::webfinger($path, $type);
650 if (self::$isTimeout) {
655 if (empty($webfinger)) {
659 return ['webfinger' => $webfinger, 'detected' => $detected];
663 * Fetch information (protocol endpoints and user information) about a given uri
665 * This function is only called by the "uri" function that adds caching and rearranging of data.
667 * @param string $uri Address that should be probed
668 * @param string $network Test for this specific network
669 * @param integer $uid User ID for the probe (only used for mails)
670 * @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): array
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 $result['networks'][Protocol::DIASPORA] = self::diaspora($webfinger);
740 if ((!$result && ($network == '')) || ($network == Protocol::OSTATUS)) {
741 $result = self::ostatus($webfinger);
743 $result['networks'][Protocol::OSTATUS] = self::ostatus($webfinger);
745 if (in_array($network, ['', Protocol::ZOT])) {
746 $result = self::zot($webfinger, $result, $baseurl);
748 if ((!$result && ($network == '')) || ($network == Protocol::PUMPIO)) {
749 $result = self::pumpio($webfinger, $addr);
751 if (empty($result['network']) && empty($ap_profile['network']) || ($network == Protocol::FEED)) {
752 $result = self::feed($uri);
754 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
755 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
756 if ((empty($result['nick']) || (strstr($result['nick'], ' '))) && ($nick != '')) {
757 $result['nick'] = $nick;
760 if (empty($result['addr']) && ($addr != '')) {
761 $result['addr'] = $addr;
765 $result = self::getSubscribeLink($result, $webfinger);
767 if (empty($result['network'])) {
768 $result['network'] = Protocol::PHANTOM;
771 if (empty($result['baseurl']) && !empty($baseurl)) {
772 $result['baseurl'] = $baseurl;
775 if (empty($result['url'])) {
776 $result['url'] = $uri;
779 Logger::info('Probing done', ['uri' => $uri, 'network' => $result['network']]);
785 * Check for Zot contact
787 * @param array $webfinger Webfinger data
788 * @param array $data previously probed data
789 * @param string $baseUrl Base URL
791 * @return array Zot data
792 * @throws HTTPException\InternalServerErrorException
794 private static function zot(array $webfinger, array $data, string $baseurl): array
796 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
797 foreach ($webfinger['aliases'] as $alias) {
798 if (substr($alias, 0, 5) == 'acct:') {
799 $data['addr'] = substr($alias, 5);
804 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
805 $data['addr'] = substr($webfinger['subject'], 5);
809 foreach ($webfinger['links'] as $link) {
810 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
811 $zot_url = $link['href'];
815 if (empty($zot_url) && !empty($data['addr']) && !empty($baseurl)) {
816 $condition = ['nurl' => Strings::normaliseLink($baseurl), 'platform' => ['hubzilla']];
817 if (!DBA::exists('gserver', $condition)) {
820 $zot_url = $baseurl . '/.well-known/zot-info?address=' . $data['addr'];
823 if (empty($zot_url)) {
827 $data = self::pollZot($zot_url, $data);
829 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
830 foreach ($webfinger['aliases'] as $alias) {
831 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
832 $data['alias'] = $alias;
840 public static function pollZot(string $url, array $data): array
842 $curlResult = DI::httpClient()->get($url, HttpClientAccept::JSON);
843 if ($curlResult->isTimeout()) {
846 $content = $curlResult->getBody();
851 $json = json_decode($content, true);
852 if (!is_array($json)) {
856 if (empty($data['network'])) {
857 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
858 $data['network'] = Protocol::ZOT;
859 } elseif (!isset($json['protocols'])) {
860 $data['network'] = Protocol::ZOT;
864 if (!empty($json['guid']) && empty($data['guid'])) {
865 $data['guid'] = $json['guid'];
867 if (!empty($json['key']) && empty($data['pubkey'])) {
868 $data['pubkey'] = $json['key'];
870 if (!empty($json['name'])) {
871 $data['name'] = $json['name'];
873 if (!empty($json['photo'])) {
874 $data['photo'] = $json['photo'];
875 if (!empty($json['photo_updated'])) {
876 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
879 if (!empty($json['address'])) {
880 $data['addr'] = $json['address'];
882 if (!empty($json['url'])) {
883 $data['url'] = $json['url'];
885 if (!empty($json['connections_url'])) {
886 $data['poco'] = $json['connections_url'];
888 if (isset($json['searchable'])) {
889 $data['hide'] = !$json['searchable'];
891 if (!empty($json['public_forum'])) {
892 $data['community'] = $json['public_forum'];
893 $data['account-type'] = User::PAGE_FLAGS_COMMUNITY;
896 if (!empty($json['profile'])) {
897 $profile = $json['profile'];
898 if (!empty($profile['description'])) {
899 $data['about'] = $profile['description'];
901 if (!empty($profile['keywords'])) {
902 $keywords = implode(', ', $profile['keywords']);
903 if (!empty($keywords)) {
904 $data['keywords'] = $keywords;
909 if (!empty($profile['region'])) {
910 $loc['region'] = $profile['region'];
912 if (!empty($profile['country'])) {
913 $loc['country-name'] = $profile['country'];
915 $location = Profile::formatLocation($loc);
916 if (!empty($location)) {
917 $data['location'] = $location;
925 * Perform a webfinger request.
927 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
929 * @param string $url Address that should be probed
930 * @param string $type type
932 * @return array webfinger data
933 * @throws HTTPException\InternalServerErrorException
935 public static function webfinger(string $url, string $type): array
937 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
939 $curlResult = DI::httpClient()->get($url, $type, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
940 if ($curlResult->isTimeout()) {
941 self::$isTimeout = true;
944 $data = $curlResult->getBody();
946 $webfinger = json_decode($data, true);
947 if (!empty($webfinger)) {
948 if (!isset($webfinger['links'])) {
949 Logger::info('No json webfinger links', ['url' => $url]);
955 // If it is not JSON, maybe it is XML
956 $xrd = XML::parseString($data, true);
957 if (!is_object($xrd)) {
958 Logger::info('No webfinger data retrievable', ['url' => $url]);
962 $xrd_arr = XML::elementToArray($xrd);
963 if (!isset($xrd_arr['xrd']['link'])) {
964 Logger::info('No XML webfinger links', ['url' => $url]);
970 if (!empty($xrd_arr['xrd']['subject'])) {
971 $webfinger['subject'] = $xrd_arr['xrd']['subject'];
974 if (!empty($xrd_arr['xrd']['alias'])) {
975 $webfinger['aliases'] = $xrd_arr['xrd']['alias'];
978 $webfinger['links'] = [];
980 foreach ($xrd_arr['xrd']['link'] as $value => $data) {
981 if (!empty($data['@attributes'])) {
982 $attributes = $data['@attributes'];
983 } elseif ($value == '@attributes') {
989 $webfinger['links'][] = $attributes;
995 * Poll the Friendica specific noscrape page.
997 * "noscrape" is a faster alternative to fetch the data from the hcard.
998 * This functionality was originally created for the directory.
1000 * @param string $noscrape_url Link to the noscrape page
1001 * @param array $data The already fetched data
1003 * @return array noscrape data
1004 * @throws HTTPException\InternalServerErrorException
1006 private static function pollNoscrape(string $noscrape_url, array $data): array
1008 $curlResult = DI::httpClient()->get($noscrape_url, HttpClientAccept::JSON);
1009 if ($curlResult->isTimeout()) {
1010 self::$isTimeout = true;
1013 $content = $curlResult->getBody();
1015 Logger::info('Empty body', ['url' => $noscrape_url]);
1019 $json = json_decode($content, true);
1020 if (!is_array($json)) {
1021 Logger::info('No json data', ['url' => $noscrape_url]);
1025 if (!empty($json['fn'])) {
1026 $data['name'] = $json['fn'];
1029 if (!empty($json['addr'])) {
1030 $data['addr'] = $json['addr'];
1033 if (!empty($json['nick'])) {
1034 $data['nick'] = $json['nick'];
1037 if (!empty($json['guid'])) {
1038 $data['guid'] = $json['guid'];
1041 if (!empty($json['comm'])) {
1042 $data['community'] = $json['comm'];
1045 if (!empty($json['tags'])) {
1046 $keywords = implode(', ', $json['tags']);
1047 if ($keywords != '') {
1048 $data['keywords'] = $keywords;
1052 $location = Profile::formatLocation($json);
1054 $data['location'] = $location;
1057 if (!empty($json['about'])) {
1058 $data['about'] = $json['about'];
1061 if (!empty($json['xmpp'])) {
1062 $data['xmpp'] = $json['xmpp'];
1065 if (!empty($json['matrix'])) {
1066 $data['matrix'] = $json['matrix'];
1069 if (!empty($json['key'])) {
1070 $data['pubkey'] = $json['key'];
1073 if (!empty($json['photo'])) {
1074 $data['photo'] = $json['photo'];
1077 if (!empty($json['dfrn-request'])) {
1078 $data['request'] = $json['dfrn-request'];
1081 if (!empty($json['dfrn-confirm'])) {
1082 $data['confirm'] = $json['dfrn-confirm'];
1085 if (!empty($json['dfrn-notify'])) {
1086 $data['notify'] = $json['dfrn-notify'];
1089 if (!empty($json['dfrn-poll'])) {
1090 $data['poll'] = $json['dfrn-poll'];
1093 if (isset($json['hide'])) {
1094 $data['hide'] = (bool)$json['hide'];
1096 $data['hide'] = false;
1103 * Check for valid DFRN data
1105 * @param array $data DFRN data
1107 * @return int Number of errors
1109 public static function validDfrn(array $data): int
1112 if (!isset($data['key'])) {
1115 if (!isset($data['dfrn-request'])) {
1118 if (!isset($data['dfrn-confirm'])) {
1121 if (!isset($data['dfrn-notify'])) {
1124 if (!isset($data['dfrn-poll'])) {
1131 * Fetch data from a DFRN profile page and via "noscrape"
1133 * @param string $profile_link Link to the profile page
1134 * @return array profile data
1135 * @throws HTTPException\InternalServerErrorException
1136 * @throws \ImagickException
1138 public static function profile(string $profile_link): array
1142 Logger::info('Check profile', ['link' => $profile_link]);
1144 // Fetch data via noscrape - this is faster
1145 $noscrape_url = str_replace(['/hcard/', '/profile/'], '/noscrape/', $profile_link);
1146 $data = self::pollNoscrape($noscrape_url, $data);
1148 if (!isset($data['notify'])
1149 || !isset($data['confirm'])
1150 || !isset($data['request'])
1151 || !isset($data['poll'])
1152 || !isset($data['name'])
1153 || !isset($data['photo'])
1155 $data = self::pollHcard($profile_link, $data, true);
1160 if (empty($data['addr']) || empty($data['nick'])) {
1161 $probe_data = self::uri($profile_link);
1162 $data['addr'] = ($data['addr'] ?? '') ?: $probe_data['addr'];
1163 $data['nick'] = ($data['nick'] ?? '') ?: $probe_data['nick'];
1166 $prof_data['addr'] = $data['addr'];
1167 $prof_data['nick'] = $data['nick'];
1168 $prof_data['dfrn-request'] = $data['request'] ?? null;
1169 $prof_data['dfrn-confirm'] = $data['confirm'] ?? null;
1170 $prof_data['dfrn-notify'] = $data['notify'] ?? null;
1171 $prof_data['dfrn-poll'] = $data['poll'] ?? null;
1172 $prof_data['photo'] = $data['photo'] ?? null;
1173 $prof_data['fn'] = $data['name'] ?? null;
1174 $prof_data['key'] = $data['pubkey'] ?? null;
1176 Logger::debug('Result', ['link' => $profile_link, 'data' => $prof_data]);
1182 * Check for DFRN contact
1184 * @param array $webfinger Webfinger data
1185 * @return array DFRN data
1186 * @throws HTTPException\InternalServerErrorException
1188 private static function dfrn(array $webfinger): array
1192 // The array is reversed to take into account the order of preference for same-rel links
1193 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1194 foreach (array_reverse($webfinger['links']) as $link) {
1195 if (($link['rel'] == ActivityNamespace::DFRN) && !empty($link['href'])) {
1196 $data['network'] = Protocol::DFRN;
1197 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1198 $data['poll'] = $link['href'];
1199 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1200 $data['url'] = $link['href'];
1201 } elseif (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1202 $hcard_url = $link['href'];
1203 } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1204 $data['poco'] = $link['href'];
1205 } elseif (($link['rel'] == 'http://webfinger.net/rel/avatar') && !empty($link['href'])) {
1206 $data['photo'] = $link['href'];
1207 } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1208 $data['baseurl'] = trim($link['href'], '/');
1209 } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1210 $data['guid'] = $link['href'];
1211 } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1212 $data['pubkey'] = base64_decode($link['href']);
1214 if (strstr($data['pubkey'], 'RSA ')) {
1215 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1220 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1221 foreach ($webfinger['aliases'] as $alias) {
1222 if (empty($data['url']) && !strstr($alias, '@')) {
1223 $data['url'] = $alias;
1224 } elseif (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
1225 $data['alias'] = $alias;
1226 } elseif (substr($alias, 0, 5) == 'acct:') {
1227 $data['addr'] = substr($alias, 5);
1232 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1233 $data['addr'] = substr($webfinger['subject'], 5);
1236 if (!isset($data['network']) || ($hcard_url == '')) {
1240 // Fetch data via noscrape - this is faster
1241 $noscrape_url = str_replace('/hcard/', '/noscrape/', $hcard_url);
1242 $data = self::pollNoscrape($noscrape_url, $data);
1244 if (isset($data['notify'])
1245 && isset($data['confirm'])
1246 && isset($data['request'])
1247 && isset($data['poll'])
1248 && isset($data['name'])
1249 && isset($data['photo'])
1254 $data = self::pollHcard($hcard_url, $data, true);
1260 * Poll the hcard page (Diaspora and Friendica specific)
1262 * @param string $hcard_url Link to the hcard page
1263 * @param array $data The already fetched data
1264 * @param boolean $dfrn Poll DFRN specific data
1265 * @return array hcard data
1266 * @throws HTTPException\InternalServerErrorException
1268 private static function pollHcard(string $hcard_url, array $data, bool $dfrn = false): array
1270 $curlResult = DI::httpClient()->get($hcard_url, HttpClientAccept::HTML);
1271 if ($curlResult->isTimeout()) {
1272 self::$isTimeout = true;
1275 $content = $curlResult->getBody();
1276 if (empty($content)) {
1280 $doc = new DOMDocument();
1281 if (!@$doc->loadHTML($content)) {
1285 $xpath = new DomXPath($doc);
1287 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1288 if (!is_object($vcards)) {
1292 if (!isset($data['baseurl'])) {
1293 $data['baseurl'] = '';
1296 if ($vcards->length > 0) {
1297 $vcard = $vcards->item(0);
1299 // We have to discard the guid from the hcard in favour of the guid from lrdd
1300 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1301 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1302 if (($search->length > 0) && empty($data['guid'])) {
1303 $data['guid'] = $search->item(0)->nodeValue;
1306 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1307 if ($search->length > 0) {
1308 $data['nick'] = $search->item(0)->nodeValue;
1311 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1312 if ($search->length > 0) {
1313 $data['name'] = $search->item(0)->nodeValue;
1316 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' given_name ')]", $vcard); // */
1317 if ($search->length > 0) {
1318 $data["given_name"] = $search->item(0)->nodeValue;
1321 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' family_name ')]", $vcard); // */
1322 if ($search->length > 0) {
1323 $data["family_name"] = $search->item(0)->nodeValue;
1326 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1327 if ($search->length > 0) {
1328 $data['hide'] = (strtolower($search->item(0)->nodeValue) != 'true');
1331 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1332 if ($search->length > 0) {
1333 $data['pubkey'] = $search->item(0)->nodeValue;
1334 if (strstr($data['pubkey'], 'RSA ')) {
1335 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1339 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1340 if ($search->length > 0) {
1341 $data['baseurl'] = trim($search->item(0)->nodeValue, '/');
1346 if (!empty($vcard)) {
1347 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1348 foreach ($photos as $photo) {
1350 foreach ($photo->attributes as $attribute) {
1351 $attr[$attribute->name] = trim($attribute->value);
1354 if (isset($attr['src']) && isset($attr['width'])) {
1355 $avatars[$attr['width']] = self::fixAvatar($attr['src'], $data['baseurl']);
1358 // We don't have a width. So we just take everything that we got.
1359 // This is a Hubzilla workaround which doesn't send a width.
1360 if (!$avatars && !empty($attr['src'])) {
1361 $avatars[] = self::fixAvatar($attr['src'], $data['baseurl']);
1368 $data['photo'] = array_pop($avatars);
1370 $data['photo_medium'] = array_pop($avatars);
1374 $data['photo_small'] = array_pop($avatars);
1379 // Poll DFRN specific data
1380 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1381 if ($search->length > 0) {
1382 foreach ($search as $link) {
1383 //$data['request'] = $search->item(0)->nodeValue;
1385 foreach ($link->attributes as $attribute) {
1386 $attr[$attribute->name] = trim($attribute->value);
1389 $data[substr($attr['rel'], 5)] = $attr['href'];
1393 // Older Friendica versions had used the "uid" field differently than newer versions
1394 if (!empty($data['nick']) && !empty($data['guid']) && ($data['nick'] == $data['guid'])) {
1395 unset($data['guid']);
1403 * Check for Diaspora contact
1405 * @param array $webfinger Webfinger data
1407 * @return array Diaspora data
1408 * @throws HTTPException\InternalServerErrorException
1410 private static function diaspora(array $webfinger): array
1415 // The array is reversed to take into account the order of preference for same-rel links
1416 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1417 foreach (array_reverse($webfinger['links']) as $link) {
1418 if (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1419 $hcard_url = $link['href'];
1420 } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1421 $data['baseurl'] = trim($link['href'], '/');
1422 } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1423 $data['guid'] = $link['href'];
1424 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1425 $data['url'] = $link['href'];
1426 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && empty($link['type']) && !empty($link['href'])) {
1427 $profile_url = $link['href'];
1428 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1429 $data['poll'] = $link['href'];
1430 } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1431 $data['poco'] = $link['href'];
1432 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1433 $data['notify'] = $link['href'];
1434 } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1435 $data['pubkey'] = base64_decode($link['href']);
1437 if (strstr($data['pubkey'], 'RSA ')) {
1438 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1443 if (empty($data['url']) && !empty($profile_url)) {
1444 $data['url'] = $profile_url;
1447 if (empty($data['url']) || empty($hcard_url)) {
1451 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1452 foreach ($webfinger['aliases'] as $alias) {
1453 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data['url']) && ! strstr($alias, '@')) {
1454 $data['alias'] = $alias;
1455 } elseif (substr($alias, 0, 5) == 'acct:') {
1456 $data['addr'] = substr($alias, 5);
1461 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1462 $data['addr'] = substr($webfinger['subject'], 5);
1465 // Fetch further information from the hcard
1466 $data = self::pollHcard($hcard_url, $data);
1472 if (!empty($data['url'])
1473 && !empty($data['guid'])
1474 && !empty($data['baseurl'])
1475 && !empty($data['pubkey'])
1476 && !empty($hcard_url)
1478 $data['network'] = Protocol::DIASPORA;
1479 $data['manually-approve'] = false;
1481 // The Diaspora handle must always be lowercase
1482 if (!empty($data['addr'])) {
1483 $data['addr'] = strtolower($data['addr']);
1486 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1487 $data['notify'] = $data['baseurl'] . '/receive/users/' . $data['guid'];
1488 $data['batch'] = $data['baseurl'] . '/receive/public';
1497 * Check for OStatus contact
1499 * @param array $webfinger Webfinger data
1500 * @param bool $short Short detection mode
1502 * @return array|bool OStatus data or "false" on error or "true" on short mode
1503 * @throws HTTPException\InternalServerErrorException
1505 private static function ostatus(array $webfinger, bool $short = false)
1509 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1510 foreach ($webfinger['aliases'] as $alias) {
1511 if (strstr($alias, '@') && !strstr(Strings::normaliseLink($alias), 'http://')) {
1512 $data['addr'] = str_replace('acct:', '', $alias);
1517 if (!empty($webfinger['subject']) && strstr($webfinger['subject'], '@')
1518 && !strstr(Strings::normaliseLink($webfinger['subject']), 'http://')
1520 $data['addr'] = str_replace('acct:', '', $webfinger['subject']);
1523 if (!empty($webfinger['links'])) {
1524 // The array is reversed to take into account the order of preference for same-rel links
1525 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1526 foreach (array_reverse($webfinger['links']) as $link) {
1527 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1528 && (($link['type'] ?? '') == 'text/html')
1529 && ($link['href'] != '')
1531 $data['url'] = $data['alias'] = $link['href'];
1532 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1533 $data['notify'] = $link['href'];
1534 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1535 $data['poll'] = $link['href'];
1536 } elseif (($link['rel'] == 'magic-public-key') && !empty($link['href'])) {
1537 $pubkey = $link['href'];
1539 if (substr($pubkey, 0, 5) === 'data:') {
1540 if (strstr($pubkey, ',')) {
1541 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1543 $pubkey = substr($pubkey, 5);
1545 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1546 $curlResult = DI::httpClient()->get($pubkey, HttpClientAccept::MAGIC_KEY);
1547 if ($curlResult->isTimeout()) {
1548 self::$isTimeout = true;
1549 return $short ? false : [];
1551 Logger::debug('Fetched public key', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $pubkey]);
1552 $pubkey = $curlResult->getBody();
1556 $data['pubkey'] = Salmon::magicKeyToPem($pubkey);
1557 } catch (\Throwable $e) {
1564 if (isset($data['notify']) && isset($data['pubkey'])
1565 && isset($data['poll'])
1566 && isset($data['url'])
1568 $data['network'] = Protocol::OSTATUS;
1569 $data['manually-approve'] = false;
1571 return $short ? false : [];
1578 // Fetch all additional data from the feed
1579 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::FEED_XML);
1580 if ($curlResult->isTimeout()) {
1581 self::$isTimeout = true;
1584 $feed = $curlResult->getBody();
1585 $feed_data = Feed::import($feed);
1590 if (!empty($feed_data['header']['author-name'])) {
1591 $data['name'] = $feed_data['header']['author-name'];
1593 if (!empty($feed_data['header']['author-nick'])) {
1594 $data['nick'] = $feed_data['header']['author-nick'];
1596 if (!empty($feed_data['header']['author-avatar'])) {
1597 $data['photo'] = self::fixAvatar($feed_data['header']['author-avatar'], $data['url']);
1599 if (!empty($feed_data['header']['author-id'])) {
1600 $data['alias'] = $feed_data['header']['author-id'];
1602 if (!empty($feed_data['header']['author-location'])) {
1603 $data['location'] = $feed_data['header']['author-location'];
1605 if (!empty($feed_data['header']['author-about'])) {
1606 $data['about'] = $feed_data['header']['author-about'];
1608 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1609 // So we take the value that we just fetched, although the other one worked as well
1610 if (!empty($feed_data['header']['author-link'])) {
1611 $data['url'] = $feed_data['header']['author-link'];
1614 if ($data['url'] == $data['alias']) {
1615 $data['alias'] = '';
1618 /// @todo Fetch location and "about" from the feed as well
1623 * Fetch data from a pump.io profile page
1625 * @param string $profile_link Link to the profile page
1627 * @return array Profile data
1629 private static function pumpioProfileData(string $profile_link): array
1631 $curlResult = DI::httpClient()->get($profile_link, HttpClientAccept::HTML);
1632 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
1636 $doc = new DOMDocument();
1637 if (!@$doc->loadHTML($curlResult->getBody())) {
1641 $xpath = new DomXPath($doc);
1644 $data['name'] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1646 if ($data['name'] == '') {
1647 // This is ugly - but pump.io doesn't seem to know a better way for it
1648 $data['name'] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1649 $pos = strpos($data['name'], chr(10));
1651 $data['name'] = trim(substr($data['name'], 0, $pos));
1655 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1657 if ($data['location'] == '') {
1658 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1661 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1663 if ($data['about'] == '') {
1664 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1667 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1669 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1672 foreach ($avatar->attributes as $attribute) {
1673 if ($attribute->name == 'src') {
1674 $data['photo'] = trim($attribute->value);
1683 * Check for pump.io contact
1685 * @param array $webfinger Webfinger data
1686 * @param string $addr
1688 * @return array pump.io data
1690 private static function pumpio(array $webfinger, string $addr): array
1693 // The array is reversed to take into account the order of preference for same-rel links
1694 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1695 foreach (array_reverse($webfinger['links']) as $link) {
1696 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1697 && (($link['type'] ?? '') == 'text/html')
1698 && ($link['href'] != '')
1700 $data['url'] = $link['href'];
1701 } elseif (($link['rel'] == 'activity-inbox') && ($link['href'] != '')) {
1702 $data['notify'] = $link['href'];
1703 } elseif (($link['rel'] == 'activity-outbox') && ($link['href'] != '')) {
1704 $data['poll'] = $link['href'];
1705 } elseif (($link['rel'] == 'dialback') && ($link['href'] != '')) {
1706 $data['dialback'] = $link['href'];
1709 if (isset($data['poll']) && isset($data['notify'])
1710 && isset($data['dialback'])
1711 && isset($data['url'])
1713 // by now we use these fields only for the network type detection
1714 // So we unset all data that isn't used at the moment
1715 unset($data['dialback']);
1717 $data['network'] = Protocol::PUMPIO;
1722 $profile_data = self::pumpioProfileData($data['url']);
1724 if (!$profile_data) {
1728 $data = array_merge($data, $profile_data);
1730 if (($addr != '') && ($data['name'] != '')) {
1731 $name = trim(str_replace($addr, '', $data['name']));
1733 $data['name'] = $name;
1741 * Checks HTML page for RSS feed link
1743 * @param string $url Page link
1744 * @param string $body Page body string
1746 * @return string|false Feed link or false if body was invalid HTML document
1748 public static function getFeedLink(string $url, string $body)
1754 $doc = new DOMDocument();
1755 if (!@$doc->loadHTML($body)) {
1759 $xpath = new DOMXPath($doc);
1761 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1762 $feedUrl = $feedUrl ?: $xpath->evaluate('string(/html/head/link[@type="application/atom+xml" and @rel="alternate"]/@href)');
1764 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1770 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1772 * Loosely based on RFC 1808
1774 * @see https://tools.ietf.org/html/rfc1808
1776 * @param string $href The potential relative href found in the HTML document
1777 * @param string $base The HTML document URL
1778 * @param DOMXPath $xpath The HTML document XPath
1780 * @return string Absolute URL
1782 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath): string
1784 if (filter_var($href, FILTER_VALIDATE_URL)) {
1788 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1790 $baseParts = parse_url($base);
1791 if (empty($baseParts['host'])) {
1795 // Naked domain case (scheme://basehost)
1796 $path = $baseParts['path'] ?? '/';
1798 // Remove the filename part of the path if it exists (/base/path/file)
1799 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1801 $hrefParts = parse_url($href);
1803 if (!empty($hrefParts['path'])) {
1804 // Root path case (/path) including relative scheme case (//host/path)
1805 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1806 $path = $hrefParts['path'];
1808 $path = $path . '/' . $hrefParts['path'];
1810 // Resolve arbitrary relative path
1811 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1812 $parts = array_filter(explode('/', $path), 'strlen');
1814 foreach ($parts as $part) {
1815 if ('.' == $part) continue;
1816 if ('..' == $part) {
1817 array_pop($absolutes);
1819 $absolutes[] = $part;
1823 $path = '/' . implode('/', $absolutes);
1827 // Relative scheme case (//host/path)
1828 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1829 $baseParts['path'] = $path;
1830 unset($baseParts['query']);
1831 unset($baseParts['fragment']);
1833 return Network::unparseURL($baseParts);
1837 * Check for feed contact
1839 * @param string $url Profile link
1840 * @param boolean $probe Do a probe if the page contains a feed link
1842 * @return array feed data
1843 * @throws HTTPException\InternalServerErrorException
1845 private static function feed(string $url, bool $probe = true): array
1847 $curlResult = DI::httpClient()->get($url, HttpClientAccept::FEED_XML);
1848 if ($curlResult->isTimeout()) {
1849 self::$isTimeout = true;
1852 $feed = $curlResult->getBody();
1853 $feed_data = Feed::import($feed);
1860 $feed_url = self::getFeedLink($url, $feed);
1866 return self::feed($feed_url, false);
1869 if (!empty($feed_data['header']['author-name'])) {
1870 $data['name'] = $feed_data['header']['author-name'];
1873 if (!empty($feed_data['header']['author-nick'])) {
1874 $data['nick'] = $feed_data['header']['author-nick'];
1877 if (!empty($feed_data['header']['author-avatar'])) {
1878 $data['photo'] = $feed_data['header']['author-avatar'];
1881 if (!empty($feed_data['header']['author-id'])) {
1882 $data['alias'] = $feed_data['header']['author-id'];
1885 $data['url'] = $url;
1886 $data['poll'] = $url;
1888 $data['network'] = Protocol::FEED;
1894 * Check for mail contact
1896 * @param string $uri Profile link
1897 * @param integer $uid User ID
1899 * @return array mail data
1900 * @throws \Exception
1902 private static function mail(string $uri, int $uid): array
1904 if (!Network::isEmailDomainValid($uri)) {
1912 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1914 $condition = ["`uid` = ? AND `server` != ''", $uid];
1915 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1916 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1918 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1922 $mailbox = Email::constructMailboxName($mailacct);
1924 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1925 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1930 $msgs = Email::poll($mbox, $uri);
1931 Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
1933 if (!count($msgs)) {
1937 $phost = substr($uri, strpos($uri, '@') + 1);
1941 'network' => Protocol::MAIL,
1942 'name' => substr($uri, 0, strpos($uri, '@')),
1943 'photo' => Network::lookupAvatarByEmail($uri),
1944 'url' => 'mailto:' . $uri,
1945 'notify' => 'smtp ' . Strings::getRandomHex(),
1946 'poll' => 'email ' . Strings::getRandomHex(),
1949 $data['nick'] = $data['name'];
1951 $x = Email::messageMeta($mbox, $msgs[0]);
1953 if (stristr($x[0]->from, $uri)) {
1954 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1955 } elseif (stristr($x[0]->to, $uri)) {
1956 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1960 foreach ($adr as $feadr) {
1961 if ((strcasecmp($feadr->mailbox, $data['name']) == 0)
1962 &&(strcasecmp($feadr->host, $phost) == 0)
1963 && (strlen($feadr->personal))
1965 $personal = imap_mime_header_decode($feadr->personal);
1967 foreach ($personal as $perspart) {
1968 if ($perspart->charset != 'default') {
1969 $data['name'] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1971 $data['name'] .= $perspart->text;
1978 if (!empty($mbox)) {
1986 * Mix two paths together to possibly fix missing parts
1988 * @param string $avatar Path to the avatar
1989 * @param string $base Another path that is hopefully complete
1991 * @return string fixed avatar path
1992 * @throws \Exception
1994 public static function fixAvatar(string $avatar, string $base): string
1996 $base_parts = parse_url($base);
1998 // Remove all parts that could create a problem
1999 unset($base_parts['path']);
2000 unset($base_parts['query']);
2001 unset($base_parts['fragment']);
2003 $avatar_parts = parse_url($avatar);
2006 $parts = array_merge($base_parts, $avatar_parts);
2008 // And put them together again
2009 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
2010 $host = isset($parts['host']) ? $parts['host'] : '';
2011 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
2012 $path = isset($parts['path']) ? $parts['path'] : '';
2013 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
2014 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
2016 $fixed = $scheme.$host.$port.$path.$query.$fragment;
2018 Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
2024 * Fetch the last date that the contact had posted something (publically)
2026 * @param array $data probing result
2028 * @return string last activity
2030 public static function getLastUpdate(array $data): string
2032 $uid = User::getIdForURL($data['url']);
2034 $contact = Contact::selectFirst(['url', 'last-item'], ['self' => true, 'uid' => $uid]);
2035 if (!empty($contact['last-item'])) {
2036 return $contact['last-item'];
2040 if ($lastUpdate = self::updateFromNoScrape($data)) {
2044 if (!empty($data['outbox'])) {
2045 return self::updateFromOutbox($data['outbox'], $data);
2046 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
2047 return self::updateFromOutbox($data['poll'], $data);
2048 } elseif (!empty($data['poll'])) {
2049 return self::updateFromFeed($data);
2056 * Fetch the last activity date from the "noscrape" endpoint
2058 * @param array $data Probing result
2060 * @return string last activity or true if update was successful or the server was unreachable
2062 private static function updateFromNoScrape(array $data): string
2064 if (empty($data['baseurl'])) {
2068 // Check the 'noscrape' endpoint when it is a Friendica server
2069 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
2070 Strings::normaliseLink($data['baseurl'])]);
2071 if (!DBA::isResult($gserver)) {
2075 $curlResult = DI::httpClient()->get($gserver['noscrape'] . '/' . $data['nick'], HttpClientAccept::JSON);
2077 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
2078 $noscrape = json_decode($curlResult->getBody(), true);
2079 if (!empty($noscrape) && !empty($noscrape['updated'])) {
2080 return DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2088 * Fetch the last activity date from an ActivityPub Outbox
2090 * @param string $feed
2091 * @param array $data Probing result
2093 * @return string last activity
2094 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2096 private static function updateFromOutbox(string $feed, array $data): string
2098 $outbox = ActivityPub::fetchContent($feed);
2099 if (empty($outbox)) {
2103 if (!empty($outbox['orderedItems'])) {
2104 $items = $outbox['orderedItems'];
2105 } elseif (!empty($outbox['first']['orderedItems'])) {
2106 $items = $outbox['first']['orderedItems'];
2107 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2108 return self::updateFromOutbox($outbox['first']['href'], $data);
2109 } elseif (!empty($outbox['first'])) {
2110 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2111 return self::updateFromOutbox($outbox['first'], $data);
2113 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2121 foreach ($items as $activity) {
2122 if (!empty($activity['published'])) {
2123 $published = DateTimeFormat::utc($activity['published']);
2124 } elseif (!empty($activity['object']['published'])) {
2125 $published = DateTimeFormat::utc($activity['object']['published']);
2130 if ($last_updated < $published) {
2131 $last_updated = $published;
2135 if (!empty($last_updated)) {
2136 return $last_updated;
2143 * Fetch the last activity date from an XML feed
2145 * @param array $data Probing result
2146 * @return string last activity
2148 private static function updateFromFeed(array $data): string
2150 // Search for the newest entry in the feed
2151 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::ATOM_XML);
2152 if (!$curlResult->isSuccess() || !$curlResult->getBody()) {
2156 $doc = new DOMDocument();
2157 @$doc->loadXML($curlResult->getBody());
2159 $xpath = new DOMXPath($doc);
2160 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2162 $entries = $xpath->query('/atom:feed/atom:entry');
2166 foreach ($entries as $entry) {
2167 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2168 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
2169 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2170 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2172 if (empty($published) || empty($updated)) {
2173 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2177 if ($last_updated < $published) {
2178 $last_updated = $published;
2181 if ($last_updated < $updated) {
2182 $last_updated = $updated;
2186 if (!empty($last_updated)) {
2187 return $last_updated;
2194 * Probe data from local profiles without network traffic
2196 * @param string $url
2198 * @return array probed data
2199 * @throws HTTPException\InternalServerErrorException
2200 * @throws HTTPException\NotFoundException
2202 private static function localProbe(string $url): array
2205 $uid = User::getIdForURL($url);
2207 throw new HTTPException\NotFoundException('User not found.');
2210 $owner = User::getOwnerDataById($uid);
2211 $approfile = ActivityPub\Transmitter::getProfile($uid);
2213 $split_name = Diaspora::splitName($owner['name']);
2214 $firstname = $split_name['first'];
2215 $lastname = $split_name['last'];
2217 if (empty($owner['gsid'])) {
2218 $owner['gsid'] = GServer::getID($approfile['generator']['url']);
2222 'name' => $owner['name'], 'nick' => $owner['nick'], 'guid' => $approfile['diaspora:guid'] ?? '',
2223 'url' => $owner['url'], 'addr' => $owner['addr'], 'alias' => $owner['alias'],
2224 'photo' => User::getAvatarUrl($owner),
2225 'header' => $owner['header'] ? Contact::getHeaderUrlForId($owner['id'], $owner['updated']) : '',
2226 'account-type' => $owner['contact-type'], 'community' => ($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY),
2227 'keywords' => $owner['keywords'], 'location' => $owner['location'], 'about' => $owner['about'],
2228 'xmpp' => $owner['xmpp'], 'matrix' => $owner['matrix'],
2229 'hide' => !$owner['net-publish'], 'batch' => '', 'notify' => $owner['notify'],
2230 'poll' => $owner['poll'], 'request' => $owner['request'], 'confirm' => $owner['confirm'],
2231 'subscribe' => $approfile['generator']['url'] . '/contact/follow?url={uri}', 'poco' => $owner['poco'],
2232 'following' => $approfile['following'], 'followers' => $approfile['followers'],
2233 'inbox' => $approfile['inbox'], 'outbox' => $approfile['outbox'],
2234 'sharedinbox' => $approfile['endpoints']['sharedInbox'], 'network' => Protocol::DFRN,
2235 'pubkey' => $owner['upubkey'], 'baseurl' => $approfile['generator']['url'], 'gsid' => $owner['gsid'],
2236 'manually-approve' => in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]),
2238 Protocol::DIASPORA => [
2239 'name' => $owner['name'],
2240 'given_name' => $firstname,
2241 'family_name' => $lastname,
2242 'nick' => $owner['nick'],
2243 'guid' => $approfile['diaspora:guid'],
2244 'url' => $owner['url'],
2245 'addr' => $owner['addr'],
2246 'alias' => $owner['alias'],
2247 'photo' => $owner['photo'],
2248 'photo_medium' => $owner['thumb'],
2249 'photo_small' => $owner['micro'],
2250 'batch' => $approfile['generator']['url'] . '/receive/public',
2251 'notify' => $owner['notify'],
2252 'poll' => $owner['poll'],
2253 'poco' => $owner['poco'],
2254 'network' => Protocol::DIASPORA,
2255 'pubkey' => $owner['upubkey'],
2259 } catch (Exception $e) {
2260 // Default values for non existing targets
2262 'name' => $url, 'nick' => $url, 'url' => $url, 'network' => Protocol::PHANTOM,
2263 'photo' => DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO
2267 return self::rearrangeData($data);