3 * @copyright Copyright (C) 2010-2023, 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 if (empty($data['networks'][$network]['baseurl'])) {
143 $data['networks'][$network]['baseurl'] = $newdata['baseurl'] ?? '';
145 $newdata['baseurl'] = $data['networks'][$network]['baseurl'];
147 if (!empty($newdata['baseurl'])) {
148 $newdata['gsid'] = $data['networks'][$network]['gsid'] = GServer::getID($newdata['baseurl']);
150 $newdata['gsid'] = $data['networks'][$network]['gsid'] = null;
153 $newdata['networks'][$network] = self::rearrangeData($data['networks'][$network]);
154 unset($newdata['networks'][$network]['networks']);
158 // We don't use the "priority" field anymore and replace it with a dummy.
159 $newdata['priority'] = 0;
165 * Check if the hostname belongs to the own server
167 * @param string $host The hostname that is to be checked
168 * @return bool Does the testes hostname belongs to the own server?
170 private static function ownHost(string $host): bool
172 $own_host = DI::baseUrl()->getHostname();
174 $parts = parse_url($host);
176 if (!isset($parts['scheme'])) {
177 $parts = parse_url('http://' . $host);
180 if (!isset($parts['host'])) {
183 return $parts['host'] == $own_host;
187 * Probes for webfinger path via "host-meta"
189 * We have to check if the servers in the future still will offer this.
190 * It seems as if it was dropped from the standard.
192 * @param string $host The host part of an url
194 * @return array with template and type of the webfinger template for JSON or XML
195 * @throws HTTPException\InternalServerErrorException
197 private static function hostMeta(string $host): array
199 // Reset the static variable
202 // Handles the case when the hostname contains the scheme
203 if (!parse_url($host, PHP_URL_SCHEME)) {
204 $ssl_url = 'https://' . $host . self::HOST_META;
205 $url = 'http://' . $host . self::HOST_META;
207 $ssl_url = $host . self::HOST_META;
211 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
213 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
216 $curlResult = DI::httpClient()->get($ssl_url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
217 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
218 if ($curlResult->isSuccess()) {
219 $xml = $curlResult->getBody();
220 $xrd = XML::parseString($xml, true);
222 $host_url = 'https://' . $host;
226 } elseif ($curlResult->isTimeout()) {
227 Logger::info('Probing timeout', ['url' => $ssl_url]);
228 self::$isTimeout = true;
232 if (!is_object($xrd) && !empty($url)) {
233 $curlResult = DI::httpClient()->get($url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
234 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
235 if ($curlResult->isTimeout()) {
236 Logger::info('Probing timeout', ['url' => $url]);
237 self::$isTimeout = true;
239 } elseif ($connection_error && $ssl_connection_error) {
240 self::$isTimeout = true;
244 $xml = $curlResult->getBody();
245 $xrd = XML::parseString($xml, true);
246 $host_url = 'http://'.$host;
248 if (!is_object($xrd)) {
249 Logger::info('No xrd object found', ['host' => $host]);
253 $links = XML::elementToArray($xrd);
254 if (!isset($links['xrd']['link'])) {
255 Logger::info('No xrd data found', ['host' => $host]);
261 foreach ($links['xrd']['link'] as $value => $link) {
262 if (!empty($link['@attributes'])) {
263 $attributes = $link['@attributes'];
264 } elseif ($value == '@attributes') {
270 if (!empty($attributes['rel']) && $attributes['rel'] == 'lrdd' && !empty($attributes['template'])) {
271 $type = (empty($attributes['type']) ? '' : $attributes['type']);
273 $lrdd[$type] = $attributes['template'];
277 if (Network::isUrlBlocked($host_url)) {
278 Logger::info('Domain is blocked', ['url' => $host]);
282 self::$baseurl = $host_url;
284 Logger::info('Probing successful', ['host' => $host]);
290 * Check an URI for LRDD data
292 * @param string $uri Address that should be probed
293 * @return array uri data
294 * @throws HTTPException\InternalServerErrorException
296 public static function lrdd(string $uri): array
298 $data = self::getWebfingerArray($uri);
302 $webfinger = $data['webfinger'];
304 if (empty($webfinger['links'])) {
305 Logger::info('No webfinger links found', ['uri' => $uri]);
311 foreach ($webfinger['links'] as $link) {
312 $data[] = ['@attributes' => $link];
315 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
316 foreach ($webfinger['aliases'] as $alias) {
330 * Fetch information (protocol endpoints and user information) about a given uri
332 * @param string $uri Address that should be probed
333 * @param string $network Test for this specific network
334 * @param integer $uid User ID for the probe (only used for mails)
335 * @param boolean $cache Use cached values?
337 * @return array uri data
338 * @throws HTTPException\InternalServerErrorException
339 * @throws \ImagickException
341 public static function uri(string $uri, string $network = '', int $uid = -1): array
343 // Local profiles aren't probed via network
344 if (empty($network) && Contact::isLocal($uri)) {
345 $data = self::localProbe($uri);
352 $uid = DI::userSession()->getLocalUserId();
355 if (empty($network) || ($network == Protocol::ACTIVITYPUB)) {
356 $ap_profile = ActivityPub::probeProfile($uri);
361 self::$isTimeout = false;
363 if ($network != Protocol::ACTIVITYPUB) {
364 $data = self::detect($uri, $network, $uid, $ap_profile);
365 if (!is_array($data)) {
368 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
369 $networks = $data['networks'] ?? [];
370 unset($data['networks']);
371 if (!empty($data['network'])) {
372 $networks[$data['network']] = $data;
375 $data['networks'] = $networks;
376 } elseif (!empty($ap_profile)) {
377 $ap_profile['batch'] = '';
378 $data = array_merge($ap_profile, $data);
384 if (!isset($data['url'])) {
388 if (empty($data['photo'])) {
389 $data['photo'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
392 if (empty($data['name'])) {
393 if (!empty($data['nick'])) {
394 $data['name'] = $data['nick'];
397 if (empty($data['name'])) {
398 $data['name'] = $data['url'];
402 if (empty($data['nick'])) {
403 $data['nick'] = strtolower($data['name']);
405 if (strpos($data['nick'], ' ')) {
406 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
410 if (!empty($data['baseurl']) && empty($data['gsid'])) {
411 $data['gsid'] = GServer::getID($data['baseurl']);
414 if (empty($data['network'])) {
415 $data['network'] = Protocol::PHANTOM;
418 // Ensure that local connections always are DFRN
419 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
420 $data['network'] = Protocol::DFRN;
423 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
424 $data['hide'] = self::getHideStatus($data['url']);
427 return self::rearrangeData($data);
432 * Fetches the "hide" status from the profile
434 * @param string $url URL of the profile
435 * @return boolean "hide" status
437 private static function getHideStatus(string $url): bool
439 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::CONTENT_LENGTH => 1000000]);
440 if (!$curlResult->isSuccess()) {
444 // If it isn't a HTML file then exit
445 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
449 $body = $curlResult->getBody();
454 $doc = new DOMDocument();
455 @$doc->loadHTML($body);
457 $xpath = new DOMXPath($doc);
459 $list = $xpath->query('//meta[@name]');
460 foreach ($list as $node) {
462 if ($node->attributes->length) {
463 foreach ($node->attributes as $attribute) {
464 $meta_tag[$attribute->name] = $attribute->value;
468 if (empty($meta_tag['content'])) {
472 $content = strtolower(trim($meta_tag['content']));
474 switch (strtolower(trim($meta_tag['name']))) {
475 case 'dfrn-global-visibility':
476 if ($content == 'false') {
481 if (strpos($content, 'noindex') !== false) {
492 * Fetch the "subscribe" and add it to the result
494 * @param array $result Result array
495 * @param array $webfinger Webfinger data
497 * @return array result Altered/unaltered result array
499 private static function getSubscribeLink(array $result, array $webfinger): array
501 if (empty($webfinger['links'])) {
505 foreach ($webfinger['links'] as $link) {
506 if (!empty($link['template']) && ($link['rel'] === ActivityNamespace::OSTATUSSUB)) {
507 $result['subscribe'] = $link['template'];
515 * Get webfinger data from a given URI
517 * @param string $uri URI
519 * @return array Webfinger data
520 * @throws HTTPException\InternalServerErrorException
522 private static function getWebfingerArray(string $uri): array
524 $parts = parse_url($uri);
526 if (!empty($parts['scheme']) && !empty($parts['host'])) {
527 $host = $parts['host'];
528 if (!empty($parts['port'])) {
529 $host .= ':' . $parts['port'];
532 $baseurl = $parts['scheme'] . '://' . $host;
537 $path_parts = explode('/', trim($parts['path'] ?? '', '/'));
538 if (!empty($path_parts)) {
539 $nick = ltrim(end($path_parts), '@');
540 $addr = $nick . '@' . $host;
543 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
544 if (empty($webfinger)) {
545 $lrdd = self::hostMeta($host);
548 if (empty($webfinger) && empty($lrdd)) {
549 while (empty($lrdd) && empty($webfinger) && (sizeof($path_parts) > 1)) {
550 $host .= '/' . array_shift($path_parts);
551 $baseurl = $parts['scheme'] . '://' . $host;
554 $addr = $nick . '@' . $host;
557 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
558 if (empty($webfinger)) {
559 $lrdd = self::hostMeta($host);
563 if (empty($lrdd) && empty($webfinger)) {
567 } elseif (strstr($uri, '@')) {
568 // Remove "acct:" from the URI
569 $uri = str_replace('acct:', '', $uri);
571 $host = substr($uri, strpos($uri, '@') + 1);
572 $nick = substr($uri, 0, strpos($uri, '@'));
575 $webfinger = self::getWebfinger('https://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
576 if (self::$isTimeout) {
580 if (empty($webfinger)) {
581 $webfinger = self::getWebfinger('http://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
582 if (self::$isTimeout) {
586 $baseurl = 'https://' . $host;
589 if (empty($webfinger)) {
590 $lrdd = self::hostMeta($host);
591 if (self::$isTimeout) {
594 $baseurl = self::$baseurl;
596 $baseurl = 'http://' . $host;
599 Logger::info('URI was not detectable', ['uri' => $uri]);
603 if (empty($webfinger)) {
604 foreach ($lrdd as $type => $template) {
609 $webfinger = self::getWebfinger($template, $type, $uri, $addr);
613 if (empty($webfinger)) {
617 if ($webfinger['detected'] == $addr) {
618 $webfinger['nick'] = $nick;
619 $webfinger['addr'] = $addr;
622 $webfinger['baseurl'] = $baseurl;
628 * Perform network request for webfinger data
630 * @param string $template
631 * @param string $type
633 * @param string $addr
635 * @return array webfinger results
637 private static function getWebfinger(string $template, string $type, string $uri, string $addr): array
639 if (Network::isUrlBlocked($template)) {
640 Logger::info('Domain is blocked', ['url' => $template]);
644 // First try the address because this is the primary purpose of webfinger
647 $path = str_replace('{uri}', urlencode('acct:' . $addr), $template);
648 $webfinger = self::webfinger($path, $type);
649 if (self::$isTimeout) {
655 if (empty($webfinger) && $uri != $addr) {
657 $path = str_replace('{uri}', urlencode($uri), $template);
658 $webfinger = self::webfinger($path, $type);
659 if (self::$isTimeout) {
664 if (empty($webfinger)) {
668 return ['webfinger' => $webfinger, 'detected' => $detected];
672 * Fetch information (protocol endpoints and user information) about a given uri
674 * This function is only called by the "uri" function that adds caching and rearranging of data.
676 * @param string $uri Address that should be probed
677 * @param string $network Test for this specific network
678 * @param integer $uid User ID for the probe (only used for mails)
679 * @param array $ap_profile Previously probed AP profile
680 * @return array URI data
681 * @throws HTTPException\InternalServerErrorException
683 private static function detect(string $uri, string $network, int $uid, array $ap_profile): array
687 'network' => $network,
692 Hook::callAll('probe_detect', $hookData);
694 if (isset($hookData['result'])) {
695 return is_array($hookData['result']) ? $hookData['result'] : [];
698 $parts = parse_url($uri);
699 if (empty($parts['scheme']) && empty($parts['host']) && (empty($parts['path']) || strpos($parts['path'], '@') === false)) {
700 Logger::info('URI was not detectable', ['uri' => $uri]);
704 // If the URI starts with "mailto:" then jump directly to the mail detection
705 if (strpos($uri, 'mailto:') !== false) {
706 $uri = str_replace('mailto:', '', $uri);
707 return self::mail($uri, $uid);
710 if ($network == Protocol::MAIL) {
711 return self::mail($uri, $uid);
714 Logger::info('Probing start', ['uri' => $uri]);
716 if (!empty($ap_profile['addr']) && ($ap_profile['addr'] != $uri)) {
717 $data = self::getWebfingerArray($ap_profile['addr']);
721 $data = self::getWebfingerArray($uri);
725 if (!empty($parts['scheme'])) {
726 return self::feed($uri);
727 } elseif (!empty($uid)) {
728 return self::mail($uri, $uid);
734 $webfinger = $data['webfinger'];
735 $nick = $data['nick'] ?? '';
736 $addr = $data['addr'] ?? '';
737 $baseurl = $data['baseurl'] ?? '';
741 if (in_array($network, ['', Protocol::DFRN])) {
742 $result = self::dfrn($webfinger);
744 if ((!$result && ($network == '')) || ($network == Protocol::DIASPORA)) {
745 $result = self::diaspora($webfinger);
747 $result['networks'][Protocol::DIASPORA] = self::diaspora($webfinger);
749 if ((!$result && ($network == '')) || ($network == Protocol::OSTATUS)) {
750 $result = self::ostatus($webfinger);
752 $result['networks'][Protocol::OSTATUS] = self::ostatus($webfinger);
754 if (in_array($network, ['', Protocol::ZOT])) {
755 $result = self::zot($webfinger, $result, $baseurl);
757 if ((!$result && ($network == '')) || ($network == Protocol::PUMPIO)) {
758 $result = self::pumpio($webfinger, $addr);
760 if (empty($result['network']) && empty($ap_profile['network']) || ($network == Protocol::FEED)) {
761 $result = self::feed($uri);
763 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
764 // Additionally, it is overwritten when the nickname doesn't make sense (contains spaces).
765 if ((empty($result['nick']) || (strstr($result['nick'], ' '))) && ($nick != '')) {
766 $result['nick'] = $nick;
769 if (empty($result['addr']) && ($addr != '')) {
770 $result['addr'] = $addr;
774 $result = self::getSubscribeLink($result, $webfinger);
776 if (empty($result['network'])) {
777 $result['network'] = Protocol::PHANTOM;
780 if (empty($result['baseurl']) && !empty($baseurl)) {
781 $result['baseurl'] = $baseurl;
784 if (empty($result['url'])) {
785 $result['url'] = $uri;
788 Logger::info('Probing done', ['uri' => $uri, 'network' => $result['network']]);
794 * Check for Zot contact
796 * @param array $webfinger Webfinger data
797 * @param array $data previously probed data
798 * @param string $baseUrl Base URL
800 * @return array Zot data
801 * @throws HTTPException\InternalServerErrorException
803 private static function zot(array $webfinger, array $data, string $baseurl): array
805 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
806 foreach ($webfinger['aliases'] as $alias) {
807 if (substr($alias, 0, 5) == 'acct:') {
808 $data['addr'] = substr($alias, 5);
813 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
814 $data['addr'] = substr($webfinger['subject'], 5);
818 foreach ($webfinger['links'] as $link) {
819 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
820 $zot_url = $link['href'];
824 if (empty($zot_url) && !empty($data['addr']) && !empty($baseurl)) {
825 $condition = ['nurl' => Strings::normaliseLink($baseurl), 'platform' => ['hubzilla']];
826 if (!DBA::exists('gserver', $condition)) {
829 $zot_url = $baseurl . '/.well-known/zot-info?address=' . $data['addr'];
832 if (empty($zot_url)) {
836 $data = self::pollZot($zot_url, $data);
838 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
839 foreach ($webfinger['aliases'] as $alias) {
840 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
841 $data['alias'] = $alias;
849 public static function pollZot(string $url, array $data): array
851 $curlResult = DI::httpClient()->get($url, HttpClientAccept::JSON);
852 if ($curlResult->isTimeout()) {
855 $content = $curlResult->getBody();
860 $json = json_decode($content, true);
861 if (!is_array($json)) {
865 if (empty($data['network'])) {
866 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
867 $data['network'] = Protocol::ZOT;
868 } elseif (!isset($json['protocols'])) {
869 $data['network'] = Protocol::ZOT;
873 if (!empty($json['guid']) && empty($data['guid'])) {
874 $data['guid'] = $json['guid'];
876 if (!empty($json['key']) && empty($data['pubkey'])) {
877 $data['pubkey'] = $json['key'];
879 if (!empty($json['name'])) {
880 $data['name'] = $json['name'];
882 if (!empty($json['photo'])) {
883 $data['photo'] = $json['photo'];
884 if (!empty($json['photo_updated'])) {
885 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
888 if (!empty($json['address'])) {
889 $data['addr'] = $json['address'];
891 if (!empty($json['url'])) {
892 $data['url'] = $json['url'];
894 if (!empty($json['connections_url'])) {
895 $data['poco'] = $json['connections_url'];
897 if (isset($json['searchable'])) {
898 $data['hide'] = !$json['searchable'];
900 if (!empty($json['public_forum'])) {
901 $data['community'] = $json['public_forum'];
902 $data['account-type'] = User::PAGE_FLAGS_COMMUNITY;
905 if (!empty($json['profile'])) {
906 $profile = $json['profile'];
907 if (!empty($profile['description'])) {
908 $data['about'] = $profile['description'];
910 if (!empty($profile['keywords'])) {
911 $keywords = implode(', ', $profile['keywords']);
912 if (!empty($keywords)) {
913 $data['keywords'] = $keywords;
918 if (!empty($profile['region'])) {
919 $loc['region'] = $profile['region'];
921 if (!empty($profile['country'])) {
922 $loc['country-name'] = $profile['country'];
924 $location = Profile::formatLocation($loc);
925 if (!empty($location)) {
926 $data['location'] = $location;
934 * Perform a webfinger request.
936 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
938 * @param string $url Address that should be probed
939 * @param string $type type
941 * @return array webfinger data
942 * @throws HTTPException\InternalServerErrorException
944 public static function webfinger(string $url, string $type): array
946 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
948 $curlResult = DI::httpClient()->get($url, $type, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
949 if ($curlResult->isTimeout()) {
950 self::$isTimeout = true;
953 $data = $curlResult->getBody();
955 $webfinger = json_decode($data, true);
956 if (!empty($webfinger)) {
957 if (!isset($webfinger['links'])) {
958 Logger::info('No json webfinger links', ['url' => $url]);
964 // If it is not JSON, maybe it is XML
965 $xrd = XML::parseString($data, true);
966 if (!is_object($xrd)) {
967 Logger::info('No webfinger data retrievable', ['url' => $url]);
971 $xrd_arr = XML::elementToArray($xrd);
972 if (!isset($xrd_arr['xrd']['link'])) {
973 Logger::info('No XML webfinger links', ['url' => $url]);
979 if (!empty($xrd_arr['xrd']['subject'])) {
980 $webfinger['subject'] = $xrd_arr['xrd']['subject'];
983 if (!empty($xrd_arr['xrd']['alias'])) {
984 $webfinger['aliases'] = $xrd_arr['xrd']['alias'];
987 $webfinger['links'] = [];
989 foreach ($xrd_arr['xrd']['link'] as $value => $data) {
990 if (!empty($data['@attributes'])) {
991 $attributes = $data['@attributes'];
992 } elseif ($value == '@attributes') {
998 $webfinger['links'][] = $attributes;
1004 * Poll the Friendica specific noscrape page.
1006 * "noscrape" is a faster alternative to fetch the data from the hcard.
1007 * This functionality was originally created for the directory.
1009 * @param string $noscrape_url Link to the noscrape page
1010 * @param array $data The already fetched data
1012 * @return array noscrape data
1013 * @throws HTTPException\InternalServerErrorException
1015 private static function pollNoscrape(string $noscrape_url, array $data): array
1017 $curlResult = DI::httpClient()->get($noscrape_url, HttpClientAccept::JSON);
1018 if ($curlResult->isTimeout()) {
1019 self::$isTimeout = true;
1022 $content = $curlResult->getBody();
1024 Logger::info('Empty body', ['url' => $noscrape_url]);
1028 $json = json_decode($content, true);
1029 if (!is_array($json)) {
1030 Logger::info('No json data', ['url' => $noscrape_url]);
1034 if (!empty($json['fn'])) {
1035 $data['name'] = $json['fn'];
1038 if (!empty($json['addr'])) {
1039 $data['addr'] = $json['addr'];
1042 if (!empty($json['nick'])) {
1043 $data['nick'] = $json['nick'];
1046 if (!empty($json['guid'])) {
1047 $data['guid'] = $json['guid'];
1050 if (!empty($json['comm'])) {
1051 $data['community'] = $json['comm'];
1054 if (!empty($json['tags'])) {
1055 $keywords = implode(', ', $json['tags']);
1056 if ($keywords != '') {
1057 $data['keywords'] = $keywords;
1061 $location = Profile::formatLocation($json);
1063 $data['location'] = $location;
1066 if (!empty($json['about'])) {
1067 $data['about'] = $json['about'];
1070 if (!empty($json['xmpp'])) {
1071 $data['xmpp'] = $json['xmpp'];
1074 if (!empty($json['matrix'])) {
1075 $data['matrix'] = $json['matrix'];
1078 if (!empty($json['key'])) {
1079 $data['pubkey'] = $json['key'];
1082 if (!empty($json['photo'])) {
1083 $data['photo'] = $json['photo'];
1086 if (!empty($json['dfrn-request'])) {
1087 $data['request'] = $json['dfrn-request'];
1090 if (!empty($json['dfrn-confirm'])) {
1091 $data['confirm'] = $json['dfrn-confirm'];
1094 if (!empty($json['dfrn-notify'])) {
1095 $data['notify'] = $json['dfrn-notify'];
1098 if (!empty($json['dfrn-poll'])) {
1099 $data['poll'] = $json['dfrn-poll'];
1102 if (isset($json['hide'])) {
1103 $data['hide'] = (bool)$json['hide'];
1105 $data['hide'] = false;
1112 * Check for valid DFRN data
1114 * @param array $data DFRN data
1116 * @return int Number of errors
1118 public static function validDfrn(array $data): int
1121 if (!isset($data['key'])) {
1124 if (!isset($data['dfrn-request'])) {
1127 if (!isset($data['dfrn-confirm'])) {
1130 if (!isset($data['dfrn-notify'])) {
1133 if (!isset($data['dfrn-poll'])) {
1140 * Fetch data from a DFRN profile page and via "noscrape"
1142 * @param string $profile_link Link to the profile page
1143 * @return array profile data
1144 * @throws HTTPException\InternalServerErrorException
1145 * @throws \ImagickException
1147 public static function profile(string $profile_link): array
1151 Logger::info('Check profile', ['link' => $profile_link]);
1153 // Fetch data via noscrape - this is faster
1154 $noscrape_url = str_replace(['/hcard/', '/profile/'], '/noscrape/', $profile_link);
1155 $data = self::pollNoscrape($noscrape_url, $data);
1157 if (!isset($data['notify'])
1158 || !isset($data['confirm'])
1159 || !isset($data['request'])
1160 || !isset($data['poll'])
1161 || !isset($data['name'])
1162 || !isset($data['photo'])
1164 $data = self::pollHcard($profile_link, $data, true);
1169 if (empty($data['addr']) || empty($data['nick'])) {
1170 $probe_data = self::uri($profile_link);
1171 $data['addr'] = ($data['addr'] ?? '') ?: $probe_data['addr'];
1172 $data['nick'] = ($data['nick'] ?? '') ?: $probe_data['nick'];
1175 $prof_data['addr'] = $data['addr'];
1176 $prof_data['nick'] = $data['nick'];
1177 $prof_data['dfrn-request'] = $data['request'] ?? null;
1178 $prof_data['dfrn-confirm'] = $data['confirm'] ?? null;
1179 $prof_data['dfrn-notify'] = $data['notify'] ?? null;
1180 $prof_data['dfrn-poll'] = $data['poll'] ?? null;
1181 $prof_data['photo'] = $data['photo'] ?? null;
1182 $prof_data['fn'] = $data['name'] ?? null;
1183 $prof_data['key'] = $data['pubkey'] ?? null;
1185 Logger::debug('Result', ['link' => $profile_link, 'data' => $prof_data]);
1191 * Check for DFRN contact
1193 * @param array $webfinger Webfinger data
1194 * @return array DFRN data
1195 * @throws HTTPException\InternalServerErrorException
1197 private static function dfrn(array $webfinger): array
1201 // The array is reversed to take into account the order of preference for same-rel links
1202 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1203 foreach (array_reverse($webfinger['links']) as $link) {
1204 if (($link['rel'] == ActivityNamespace::DFRN) && !empty($link['href'])) {
1205 $data['network'] = Protocol::DFRN;
1206 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1207 $data['poll'] = $link['href'];
1208 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1209 $data['url'] = $link['href'];
1210 } elseif (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1211 $hcard_url = $link['href'];
1212 } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1213 $data['poco'] = $link['href'];
1214 } elseif (($link['rel'] == 'http://webfinger.net/rel/avatar') && !empty($link['href'])) {
1215 $data['photo'] = $link['href'];
1216 } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1217 $data['baseurl'] = trim($link['href'], '/');
1218 } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1219 $data['guid'] = $link['href'];
1220 } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1221 $data['pubkey'] = base64_decode($link['href']);
1223 if (strstr($data['pubkey'], 'RSA ')) {
1224 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1229 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1230 foreach ($webfinger['aliases'] as $alias) {
1231 if (empty($data['url']) && !strstr($alias, '@')) {
1232 $data['url'] = $alias;
1233 } elseif (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
1234 $data['alias'] = $alias;
1235 } elseif (substr($alias, 0, 5) == 'acct:') {
1236 $data['addr'] = substr($alias, 5);
1241 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1242 $data['addr'] = substr($webfinger['subject'], 5);
1245 if (!isset($data['network']) || ($hcard_url == '')) {
1249 // Fetch data via noscrape - this is faster
1250 $noscrape_url = str_replace('/hcard/', '/noscrape/', $hcard_url);
1251 $data = self::pollNoscrape($noscrape_url, $data);
1253 if (isset($data['notify'])
1254 && isset($data['confirm'])
1255 && isset($data['request'])
1256 && isset($data['poll'])
1257 && isset($data['name'])
1258 && isset($data['photo'])
1263 $data = self::pollHcard($hcard_url, $data, true);
1269 * Poll the hcard page (Diaspora and Friendica specific)
1271 * @param string $hcard_url Link to the hcard page
1272 * @param array $data The already fetched data
1273 * @param boolean $dfrn Poll DFRN specific data
1274 * @return array hcard data
1275 * @throws HTTPException\InternalServerErrorException
1277 private static function pollHcard(string $hcard_url, array $data, bool $dfrn = false): array
1279 $curlResult = DI::httpClient()->get($hcard_url, HttpClientAccept::HTML);
1280 if ($curlResult->isTimeout()) {
1281 self::$isTimeout = true;
1284 $content = $curlResult->getBody();
1285 if (empty($content)) {
1289 $doc = new DOMDocument();
1290 if (!@$doc->loadHTML($content)) {
1294 $xpath = new DomXPath($doc);
1296 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1297 if (!is_object($vcards)) {
1301 if (!isset($data['baseurl'])) {
1302 $data['baseurl'] = '';
1305 if ($vcards->length > 0) {
1306 $vcard = $vcards->item(0);
1308 // We have to discard the guid from the hcard in favour of the guid from lrdd
1309 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1310 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1311 if (($search->length > 0) && empty($data['guid'])) {
1312 $data['guid'] = $search->item(0)->nodeValue;
1315 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1316 if ($search->length > 0) {
1317 $data['nick'] = $search->item(0)->nodeValue;
1320 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1321 if ($search->length > 0) {
1322 $data['name'] = $search->item(0)->nodeValue;
1325 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' given_name ')]", $vcard); // */
1326 if ($search->length > 0) {
1327 $data["given_name"] = $search->item(0)->nodeValue;
1330 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' family_name ')]", $vcard); // */
1331 if ($search->length > 0) {
1332 $data["family_name"] = $search->item(0)->nodeValue;
1335 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1336 if ($search->length > 0) {
1337 $data['hide'] = (strtolower($search->item(0)->nodeValue) != 'true');
1340 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1341 if ($search->length > 0) {
1342 $data['pubkey'] = $search->item(0)->nodeValue;
1343 if (strstr($data['pubkey'], 'RSA ')) {
1344 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1348 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1349 if ($search->length > 0) {
1350 $data['baseurl'] = trim($search->item(0)->nodeValue, '/');
1355 if (!empty($vcard)) {
1356 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1357 foreach ($photos as $photo) {
1359 foreach ($photo->attributes as $attribute) {
1360 $attr[$attribute->name] = trim($attribute->value);
1363 if (isset($attr['src']) && isset($attr['width'])) {
1364 $avatars[$attr['width']] = self::fixAvatar($attr['src'], $data['baseurl']);
1367 // We don't have a width. So we just take everything that we got.
1368 // This is a Hubzilla workaround which doesn't send a width.
1369 if (!$avatars && !empty($attr['src'])) {
1370 $avatars[] = self::fixAvatar($attr['src'], $data['baseurl']);
1377 $data['photo'] = array_pop($avatars);
1379 $data['photo_medium'] = array_pop($avatars);
1383 $data['photo_small'] = array_pop($avatars);
1388 // Poll DFRN specific data
1389 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1390 if ($search->length > 0) {
1391 foreach ($search as $link) {
1392 //$data['request'] = $search->item(0)->nodeValue;
1394 foreach ($link->attributes as $attribute) {
1395 $attr[$attribute->name] = trim($attribute->value);
1398 $data[substr($attr['rel'], 5)] = $attr['href'];
1402 // Older Friendica versions had used the "uid" field differently than newer versions
1403 if (!empty($data['nick']) && !empty($data['guid']) && ($data['nick'] == $data['guid'])) {
1404 unset($data['guid']);
1412 * Check for Diaspora contact
1414 * @param array $webfinger Webfinger data
1416 * @return array Diaspora data
1417 * @throws HTTPException\InternalServerErrorException
1419 private static function diaspora(array $webfinger): array
1424 // The array is reversed to take into account the order of preference for same-rel links
1425 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1426 foreach (array_reverse($webfinger['links']) as $link) {
1427 if (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1428 $hcard_url = $link['href'];
1429 } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1430 $data['baseurl'] = trim($link['href'], '/');
1431 } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1432 $data['guid'] = $link['href'];
1433 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1434 $data['url'] = $link['href'];
1435 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && empty($link['type']) && !empty($link['href'])) {
1436 $profile_url = $link['href'];
1437 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1438 $data['poll'] = $link['href'];
1439 } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1440 $data['poco'] = $link['href'];
1441 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1442 $data['notify'] = $link['href'];
1443 } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1444 $data['pubkey'] = base64_decode($link['href']);
1446 if (strstr($data['pubkey'], 'RSA ')) {
1447 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1452 if (empty($data['url']) && !empty($profile_url)) {
1453 $data['url'] = $profile_url;
1456 if (empty($data['url']) || empty($hcard_url)) {
1460 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1461 foreach ($webfinger['aliases'] as $alias) {
1462 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data['url']) && ! strstr($alias, '@')) {
1463 $data['alias'] = $alias;
1464 } elseif (substr($alias, 0, 5) == 'acct:') {
1465 $data['addr'] = substr($alias, 5);
1470 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1471 $data['addr'] = substr($webfinger['subject'], 5);
1474 // Fetch further information from the hcard
1475 $data = self::pollHcard($hcard_url, $data);
1481 if (!empty($data['url'])
1482 && !empty($data['guid'])
1483 && !empty($data['baseurl'])
1484 && !empty($data['pubkey'])
1485 && !empty($hcard_url)
1487 $data['network'] = Protocol::DIASPORA;
1488 $data['manually-approve'] = false;
1490 // The Diaspora handle must always be lowercase
1491 if (!empty($data['addr'])) {
1492 $data['addr'] = strtolower($data['addr']);
1495 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1496 $data['notify'] = $data['baseurl'] . '/receive/users/' . $data['guid'];
1497 $data['batch'] = $data['baseurl'] . '/receive/public';
1506 * Check for OStatus contact
1508 * @param array $webfinger Webfinger data
1509 * @param bool $short Short detection mode
1511 * @return array|bool OStatus data or "false" on error or "true" on short mode
1512 * @throws HTTPException\InternalServerErrorException
1514 private static function ostatus(array $webfinger, bool $short = false)
1518 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1519 foreach ($webfinger['aliases'] as $alias) {
1520 if (strstr($alias, '@') && !strstr(Strings::normaliseLink($alias), 'http://')) {
1521 $data['addr'] = str_replace('acct:', '', $alias);
1526 if (!empty($webfinger['subject']) && strstr($webfinger['subject'], '@')
1527 && !strstr(Strings::normaliseLink($webfinger['subject']), 'http://')
1529 $data['addr'] = str_replace('acct:', '', $webfinger['subject']);
1532 if (!empty($webfinger['links'])) {
1533 // The array is reversed to take into account the order of preference for same-rel links
1534 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1535 foreach (array_reverse($webfinger['links']) as $link) {
1536 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1537 && (($link['type'] ?? '') == 'text/html')
1538 && ($link['href'] != '')
1540 $data['url'] = $data['alias'] = $link['href'];
1541 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1542 $data['notify'] = $link['href'];
1543 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1544 $data['poll'] = $link['href'];
1545 } elseif (($link['rel'] == 'magic-public-key') && !empty($link['href'])) {
1546 $pubkey = $link['href'];
1548 if (substr($pubkey, 0, 5) === 'data:') {
1549 if (strstr($pubkey, ',')) {
1550 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1552 $pubkey = substr($pubkey, 5);
1554 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1555 $curlResult = DI::httpClient()->get($pubkey, HttpClientAccept::MAGIC_KEY);
1556 if ($curlResult->isTimeout()) {
1557 self::$isTimeout = true;
1558 return $short ? false : [];
1560 Logger::debug('Fetched public key', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $pubkey]);
1561 $pubkey = $curlResult->getBody();
1565 $data['pubkey'] = Salmon::magicKeyToPem($pubkey);
1566 } catch (\Throwable $e) {
1573 if (isset($data['notify']) && isset($data['pubkey'])
1574 && isset($data['poll'])
1575 && isset($data['url'])
1577 $data['network'] = Protocol::OSTATUS;
1578 $data['manually-approve'] = false;
1580 return $short ? false : [];
1587 // Fetch all additional data from the feed
1588 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::FEED_XML);
1589 if ($curlResult->isTimeout()) {
1590 self::$isTimeout = true;
1593 $feed = $curlResult->getBody();
1594 $feed_data = Feed::import($feed);
1599 if (!empty($feed_data['header']['author-name'])) {
1600 $data['name'] = $feed_data['header']['author-name'];
1602 if (!empty($feed_data['header']['author-nick'])) {
1603 $data['nick'] = $feed_data['header']['author-nick'];
1605 if (!empty($feed_data['header']['author-avatar'])) {
1606 $data['photo'] = self::fixAvatar($feed_data['header']['author-avatar'], $data['url']);
1608 if (!empty($feed_data['header']['author-id'])) {
1609 $data['alias'] = $feed_data['header']['author-id'];
1611 if (!empty($feed_data['header']['author-location'])) {
1612 $data['location'] = $feed_data['header']['author-location'];
1614 if (!empty($feed_data['header']['author-about'])) {
1615 $data['about'] = $feed_data['header']['author-about'];
1617 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1618 // So we take the value that we just fetched, although the other one worked as well
1619 if (!empty($feed_data['header']['author-link'])) {
1620 $data['url'] = $feed_data['header']['author-link'];
1623 if ($data['url'] == $data['alias']) {
1624 $data['alias'] = '';
1627 /// @todo Fetch location and "about" from the feed as well
1632 * Fetch data from a pump.io profile page
1634 * @param string $profile_link Link to the profile page
1636 * @return array Profile data
1638 private static function pumpioProfileData(string $profile_link): array
1640 $curlResult = DI::httpClient()->get($profile_link, HttpClientAccept::HTML);
1641 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
1645 $doc = new DOMDocument();
1646 if (!@$doc->loadHTML($curlResult->getBody())) {
1650 $xpath = new DomXPath($doc);
1653 $data['name'] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1655 if ($data['name'] == '') {
1656 // This is ugly - but pump.io doesn't seem to know a better way for it
1657 $data['name'] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1658 $pos = strpos($data['name'], chr(10));
1660 $data['name'] = trim(substr($data['name'], 0, $pos));
1664 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1666 if ($data['location'] == '') {
1667 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1670 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1672 if ($data['about'] == '') {
1673 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1676 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1678 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1681 foreach ($avatar->attributes as $attribute) {
1682 if ($attribute->name == 'src') {
1683 $data['photo'] = trim($attribute->value);
1692 * Check for pump.io contact
1694 * @param array $webfinger Webfinger data
1695 * @param string $addr
1697 * @return array pump.io data
1699 private static function pumpio(array $webfinger, string $addr): array
1702 // The array is reversed to take into account the order of preference for same-rel links
1703 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1704 foreach (array_reverse($webfinger['links']) as $link) {
1705 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1706 && (($link['type'] ?? '') == 'text/html')
1707 && ($link['href'] != '')
1709 $data['url'] = $link['href'];
1710 } elseif (($link['rel'] == 'activity-inbox') && ($link['href'] != '')) {
1711 $data['notify'] = $link['href'];
1712 } elseif (($link['rel'] == 'activity-outbox') && ($link['href'] != '')) {
1713 $data['poll'] = $link['href'];
1714 } elseif (($link['rel'] == 'dialback') && ($link['href'] != '')) {
1715 $data['dialback'] = $link['href'];
1718 if (isset($data['poll']) && isset($data['notify'])
1719 && isset($data['dialback'])
1720 && isset($data['url'])
1722 // by now we use these fields only for the network type detection
1723 // So we unset all data that isn't used at the moment
1724 unset($data['dialback']);
1726 $data['network'] = Protocol::PUMPIO;
1731 $profile_data = self::pumpioProfileData($data['url']);
1733 if (!$profile_data) {
1737 $data = array_merge($data, $profile_data);
1739 if (($addr != '') && ($data['name'] != '')) {
1740 $name = trim(str_replace($addr, '', $data['name']));
1742 $data['name'] = $name;
1750 * Checks HTML page for RSS feed link
1752 * @param string $url Page link
1753 * @param string $body Page body string
1755 * @return string|false Feed link or false if body was invalid HTML document
1757 public static function getFeedLink(string $url, string $body)
1763 $doc = new DOMDocument();
1764 if (!@$doc->loadHTML($body)) {
1768 $xpath = new DOMXPath($doc);
1770 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1771 $feedUrl = $feedUrl ?: $xpath->evaluate('string(/html/head/link[@type="application/atom+xml" and @rel="alternate"]/@href)');
1773 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1779 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1781 * Loosely based on RFC 1808
1783 * @see https://tools.ietf.org/html/rfc1808
1785 * @param string $href The potential relative href found in the HTML document
1786 * @param string $base The HTML document URL
1787 * @param DOMXPath $xpath The HTML document XPath
1789 * @return string Absolute URL
1791 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath): string
1793 if (filter_var($href, FILTER_VALIDATE_URL)) {
1797 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1799 $baseParts = parse_url($base);
1800 if (empty($baseParts['host'])) {
1804 // Naked domain case (scheme://basehost)
1805 $path = $baseParts['path'] ?? '/';
1807 // Remove the filename part of the path if it exists (/base/path/file)
1808 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1810 $hrefParts = parse_url($href);
1812 if (!empty($hrefParts['path'])) {
1813 // Root path case (/path) including relative scheme case (//host/path)
1814 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1815 $path = $hrefParts['path'];
1817 $path = $path . '/' . $hrefParts['path'];
1819 // Resolve arbitrary relative path
1820 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1821 $parts = array_filter(explode('/', $path), 'strlen');
1823 foreach ($parts as $part) {
1824 if ('.' == $part) continue;
1825 if ('..' == $part) {
1826 array_pop($absolutes);
1828 $absolutes[] = $part;
1832 $path = '/' . implode('/', $absolutes);
1836 // Relative scheme case (//host/path)
1837 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1838 $baseParts['path'] = $path;
1839 unset($baseParts['query']);
1840 unset($baseParts['fragment']);
1842 return Network::unparseURL($baseParts);
1846 * Check for feed contact
1848 * @param string $url Profile link
1849 * @param boolean $probe Do a probe if the page contains a feed link
1851 * @return array feed data
1852 * @throws HTTPException\InternalServerErrorException
1854 private static function feed(string $url, bool $probe = true): array
1857 $curlResult = DI::httpClient()->get($url, HttpClientAccept::FEED_XML);
1858 } catch(\Throwable $e) {
1859 DI::logger()->info('Error requesting feed URL', ['url' => $url, 'exception' => $e]);
1863 if ($curlResult->isTimeout()) {
1864 self::$isTimeout = true;
1868 $feed = $curlResult->getBody();
1869 $feed_data = Feed::import($feed);
1876 $feed_url = self::getFeedLink($url, $feed);
1882 return self::feed($feed_url, false);
1885 if (!empty($feed_data['header']['author-name'])) {
1886 $data['name'] = $feed_data['header']['author-name'];
1889 if (!empty($feed_data['header']['author-nick'])) {
1890 $data['nick'] = $feed_data['header']['author-nick'];
1893 if (!empty($feed_data['header']['author-avatar'])) {
1894 $data['photo'] = $feed_data['header']['author-avatar'];
1897 if (!empty($feed_data['header']['author-id'])) {
1898 $data['alias'] = $feed_data['header']['author-id'];
1901 $data['url'] = $url;
1902 $data['poll'] = $url;
1904 $data['network'] = Protocol::FEED;
1910 * Check for mail contact
1912 * @param string $uri Profile link
1913 * @param integer $uid User ID
1915 * @return array mail data
1916 * @throws \Exception
1918 private static function mail(string $uri, int $uid): array
1920 if (!Network::isEmailDomainValid($uri)) {
1928 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1930 $condition = ["`uid` = ? AND `server` != ''", $uid];
1931 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1932 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1934 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1938 $mailbox = Email::constructMailboxName($mailacct);
1940 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1941 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1946 $msgs = Email::poll($mbox, $uri);
1947 Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
1949 if (!count($msgs)) {
1953 $phost = substr($uri, strpos($uri, '@') + 1);
1957 'network' => Protocol::MAIL,
1958 'name' => substr($uri, 0, strpos($uri, '@')),
1959 'photo' => Network::lookupAvatarByEmail($uri),
1960 'url' => 'mailto:' . $uri,
1961 'notify' => 'smtp ' . Strings::getRandomHex(),
1962 'poll' => 'email ' . Strings::getRandomHex(),
1965 $data['nick'] = $data['name'];
1967 $x = Email::messageMeta($mbox, $msgs[0]);
1969 if (stristr($x[0]->from, $uri)) {
1970 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1971 } elseif (stristr($x[0]->to, $uri)) {
1972 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1976 foreach ($adr as $feadr) {
1977 if ((strcasecmp($feadr->mailbox, $data['name']) == 0)
1978 &&(strcasecmp($feadr->host, $phost) == 0)
1979 && (strlen($feadr->personal))
1981 $personal = imap_mime_header_decode($feadr->personal);
1983 foreach ($personal as $perspart) {
1984 if ($perspart->charset != 'default') {
1985 $data['name'] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1987 $data['name'] .= $perspart->text;
1994 if (!empty($mbox)) {
2002 * Mix two paths together to possibly fix missing parts
2004 * @param string $avatar Path to the avatar
2005 * @param string $base Another path that is hopefully complete
2007 * @return string fixed avatar path
2008 * @throws \Exception
2010 public static function fixAvatar(string $avatar, string $base): string
2012 $base_parts = parse_url($base);
2014 // Remove all parts that could create a problem
2015 unset($base_parts['path']);
2016 unset($base_parts['query']);
2017 unset($base_parts['fragment']);
2019 $avatar_parts = parse_url($avatar);
2022 $parts = array_merge($base_parts, $avatar_parts);
2024 // And put them together again
2025 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
2026 $host = isset($parts['host']) ? $parts['host'] : '';
2027 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
2028 $path = isset($parts['path']) ? $parts['path'] : '';
2029 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
2030 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
2032 $fixed = $scheme.$host.$port.$path.$query.$fragment;
2034 Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
2040 * Fetch the last date that the contact had posted something (publically)
2042 * @param array $data probing result
2044 * @return string last activity
2046 public static function getLastUpdate(array $data): string
2048 $uid = User::getIdForURL($data['url']);
2050 $contact = Contact::selectFirst(['url', 'last-item'], ['self' => true, 'uid' => $uid]);
2051 if (!empty($contact['last-item'])) {
2052 return $contact['last-item'];
2056 if ($lastUpdate = self::updateFromNoScrape($data)) {
2060 if (!empty($data['outbox'])) {
2061 return self::updateFromOutbox($data['outbox'], $data);
2062 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
2063 return self::updateFromOutbox($data['poll'], $data);
2064 } elseif (!empty($data['poll'])) {
2065 return self::updateFromFeed($data);
2072 * Fetch the last activity date from the "noscrape" endpoint
2074 * @param array $data Probing result
2076 * @return string last activity or true if update was successful or the server was unreachable
2078 private static function updateFromNoScrape(array $data): string
2080 if (empty($data['baseurl'])) {
2084 // Check the 'noscrape' endpoint when it is a Friendica server
2085 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
2086 Strings::normaliseLink($data['baseurl'])]);
2087 if (!DBA::isResult($gserver)) {
2091 $curlResult = DI::httpClient()->get($gserver['noscrape'] . '/' . $data['nick'], HttpClientAccept::JSON);
2093 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
2094 $noscrape = json_decode($curlResult->getBody(), true);
2095 if (!empty($noscrape) && !empty($noscrape['updated'])) {
2096 return DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2104 * Fetch the last activity date from an ActivityPub Outbox
2106 * @param string $feed
2107 * @param array $data Probing result
2109 * @return string last activity
2110 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2112 private static function updateFromOutbox(string $feed, array $data): string
2114 $outbox = ActivityPub::fetchContent($feed);
2115 if (empty($outbox)) {
2119 if (!empty($outbox['orderedItems'])) {
2120 $items = $outbox['orderedItems'];
2121 } elseif (!empty($outbox['first']['orderedItems'])) {
2122 $items = $outbox['first']['orderedItems'];
2123 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2124 return self::updateFromOutbox($outbox['first']['href'], $data);
2125 } elseif (!empty($outbox['first'])) {
2126 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2127 return self::updateFromOutbox($outbox['first'], $data);
2129 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2137 foreach ($items as $activity) {
2138 if (!empty($activity['published'])) {
2139 $published = DateTimeFormat::utc($activity['published']);
2140 } elseif (!empty($activity['object']['published'])) {
2141 $published = DateTimeFormat::utc($activity['object']['published']);
2146 if ($last_updated < $published) {
2147 $last_updated = $published;
2151 if (!empty($last_updated)) {
2152 return $last_updated;
2159 * Fetch the last activity date from an XML feed
2161 * @param array $data Probing result
2162 * @return string last activity
2164 private static function updateFromFeed(array $data): string
2166 // Search for the newest entry in the feed
2167 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::ATOM_XML);
2168 if (!$curlResult->isSuccess() || !$curlResult->getBody()) {
2172 $doc = new DOMDocument();
2173 @$doc->loadXML($curlResult->getBody());
2175 $xpath = new DOMXPath($doc);
2176 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2178 $entries = $xpath->query('/atom:feed/atom:entry');
2182 foreach ($entries as $entry) {
2183 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2184 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
2185 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2186 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2188 if (empty($published) || empty($updated)) {
2189 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2193 if ($last_updated < $published) {
2194 $last_updated = $published;
2197 if ($last_updated < $updated) {
2198 $last_updated = $updated;
2202 if (!empty($last_updated)) {
2203 return $last_updated;
2210 * Probe data from local profiles without network traffic
2212 * @param string $url
2214 * @return array probed data
2215 * @throws HTTPException\InternalServerErrorException
2216 * @throws HTTPException\NotFoundException
2218 private static function localProbe(string $url): array
2221 $uid = User::getIdForURL($url);
2223 throw new HTTPException\NotFoundException('User not found.');
2226 $owner = User::getOwnerDataById($uid);
2227 $approfile = ActivityPub\Transmitter::getProfile($uid);
2229 $split_name = Diaspora::splitName($owner['name']);
2231 if (empty($owner['gsid'])) {
2232 $owner['gsid'] = GServer::getID($approfile['generator']['url']);
2236 'name' => $owner['name'], 'nick' => $owner['nick'], 'guid' => $approfile['diaspora:guid'] ?? '',
2237 'url' => $owner['url'], 'addr' => $owner['addr'], 'alias' => $owner['alias'],
2238 'photo' => User::getAvatarUrl($owner),
2239 'header' => $owner['header'] ? Contact::getHeaderUrlForId($owner['id'], $owner['updated']) : '',
2240 'account-type' => $owner['contact-type'], 'community' => ($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY),
2241 'keywords' => $owner['keywords'], 'location' => $owner['location'], 'about' => $owner['about'],
2242 'xmpp' => $owner['xmpp'], 'matrix' => $owner['matrix'],
2243 'hide' => !$owner['net-publish'], 'batch' => '', 'notify' => $owner['notify'],
2244 'poll' => $owner['poll'], 'request' => $owner['request'], 'confirm' => $owner['confirm'],
2245 'subscribe' => $approfile['generator']['url'] . '/contact/follow?url={uri}', 'poco' => $owner['poco'],
2246 'following' => $approfile['following'], 'followers' => $approfile['followers'],
2247 'inbox' => $approfile['inbox'], 'outbox' => $approfile['outbox'],
2248 'sharedinbox' => $approfile['endpoints']['sharedInbox'], 'network' => Protocol::DFRN,
2249 'pubkey' => $owner['upubkey'], 'baseurl' => $approfile['generator']['url'], 'gsid' => $owner['gsid'],
2250 'manually-approve' => in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]),
2252 Protocol::DIASPORA => [
2253 'name' => $owner['name'],
2254 'given_name' => $split_name['first'],
2255 'family_name' => $split_name['last'],
2256 'nick' => $owner['nick'],
2257 'guid' => $approfile['diaspora:guid'],
2258 'url' => $owner['url'],
2259 'addr' => $owner['addr'],
2260 'alias' => $owner['alias'],
2261 'photo' => $owner['photo'],
2262 'photo_medium' => $owner['thumb'],
2263 'photo_small' => $owner['micro'],
2264 'batch' => $approfile['generator']['url'] . '/receive/public',
2265 'notify' => $owner['notify'],
2266 'poll' => $owner['poll'],
2267 'poco' => $owner['poco'],
2268 'network' => Protocol::DIASPORA,
2269 'pubkey' => $owner['upubkey'],
2273 } catch (Exception $e) {
2274 // Default values for non existing targets
2276 'name' => $url, 'nick' => $url, 'url' => $url, 'network' => Protocol::PHANTOM,
2277 'photo' => DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO
2281 return self::rearrangeData($data);