3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Network;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
33 use Friendica\Model\Contact;
34 use Friendica\Model\GServer;
35 use Friendica\Model\Profile;
36 use Friendica\Model\User;
37 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
38 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
39 use Friendica\Protocol\ActivityNamespace;
40 use Friendica\Protocol\ActivityPub;
41 use Friendica\Protocol\Email;
42 use Friendica\Protocol\Feed;
43 use Friendica\Protocol\Salmon;
44 use Friendica\Util\Crypto;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Network;
47 use Friendica\Util\Strings;
48 use Friendica\Util\XML;
49 use GuzzleHttp\Psr7\Uri;
52 * This class contain functions for probing URL
56 const HOST_META = '/.well-known/host-meta';
57 const WEBFINGER = '/.well-known/webfinger?resource={uri}';
60 * @var string Base URL
62 private static $baseurl;
65 * @var boolean Whether a timeout has occured
67 private static $isTimeout;
70 * Checks if the provided network can be probed
72 * @param string $network
76 public static function isProbable(string $network): bool
78 return (in_array($network, array_merge(Protocol::FEDERATED, [Protocol::ZOT, Protocol::PHANTOM])));
82 * Remove stuff from an URI that doesn't belong there
84 * @param string $rawUri
85 * @return string Cleaned URI
87 public static function cleanURI(string $rawUri): string
89 // At first remove leading and trailing junk
90 $rawUri = trim($rawUri, "@#?: \t\n\r\0\x0B");
92 $rawUri = Network::convertToIdn($rawUri);
94 $uri = new Uri($rawUri);
95 if (!$uri->getScheme()) {
96 return $uri->__toString();
99 // Remove the URL fragment, since these shouldn't be part of any profile URL
100 $uri = $uri->withFragment('');
102 return $uri->__toString();
106 * Rearrange the array so that it always has the same order
108 * @param array $data Unordered data
109 * @return array Ordered data
111 private static function rearrangeData(array $data): array
113 $fields = ['name', 'given_name', 'family_name', 'nick', 'guid', 'url', 'addr', 'alias',
114 'photo', 'photo_medium', 'photo_small', 'header',
115 'account-type', 'community', 'keywords', 'location', 'about', 'xmpp', 'matrix',
116 'hide', 'batch', 'notify', 'poll', 'request', 'confirm', 'subscribe', 'poco',
117 'following', 'followers', 'inbox', 'outbox', 'sharedinbox',
118 'priority', 'network', 'pubkey', 'manually-approve', 'baseurl', 'gsid'];
120 $numeric_fields = ['gsid', 'hide', 'account-type', 'manually-approve'];
123 foreach ($fields as $field) {
124 if (isset($data[$field])) {
125 if (in_array($field, $numeric_fields)) {
126 $newdata[$field] = (int)$data[$field];
128 $newdata[$field] = trim($data[$field]);
130 } elseif (!in_array($field, $numeric_fields)) {
131 $newdata[$field] = '';
133 $newdata[$field] = null;
137 // We don't use the "priority" field anymore and replace it with a dummy.
138 $newdata['priority'] = 0;
144 * Check if the hostname belongs to the own server
146 * @param string $host The hostname that is to be checked
147 * @return bool Does the testes hostname belongs to the own server?
149 private static function ownHost(string $host): bool
151 $own_host = DI::baseUrl()->getHostname();
153 $parts = parse_url($host);
155 if (!isset($parts['scheme'])) {
156 $parts = parse_url('http://' . $host);
159 if (!isset($parts['host'])) {
162 return $parts['host'] == $own_host;
166 * Probes for webfinger path via "host-meta"
168 * We have to check if the servers in the future still will offer this.
169 * It seems as if it was dropped from the standard.
171 * @param string $host The host part of an url
173 * @return array with template and type of the webfinger template for JSON or XML
174 * @throws HTTPException\InternalServerErrorException
176 private static function hostMeta(string $host): array
178 // Reset the static variable
181 // Handles the case when the hostname contains the scheme
182 if (!parse_url($host, PHP_URL_SCHEME)) {
183 $ssl_url = 'https://' . $host . self::HOST_META;
184 $url = 'http://' . $host . self::HOST_META;
186 $ssl_url = $host . self::HOST_META;
190 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
192 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
195 $curlResult = DI::httpClient()->get($ssl_url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
196 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
197 if ($curlResult->isSuccess()) {
198 $xml = $curlResult->getBody();
199 $xrd = XML::parseString($xml, true);
201 $host_url = 'https://' . $host;
205 } elseif ($curlResult->isTimeout()) {
206 Logger::info('Probing timeout', ['url' => $ssl_url]);
207 self::$isTimeout = true;
211 if (!is_object($xrd) && !empty($url)) {
212 $curlResult = DI::httpClient()->get($url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
213 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
214 if ($curlResult->isTimeout()) {
215 Logger::info('Probing timeout', ['url' => $url]);
216 self::$isTimeout = true;
218 } elseif ($connection_error && $ssl_connection_error) {
219 self::$isTimeout = true;
223 $xml = $curlResult->getBody();
224 $xrd = XML::parseString($xml, true);
225 $host_url = 'http://'.$host;
227 if (!is_object($xrd)) {
228 Logger::info('No xrd object found', ['host' => $host]);
232 $links = XML::elementToArray($xrd);
233 if (!isset($links['xrd']['link'])) {
234 Logger::info('No xrd data found', ['host' => $host]);
240 foreach ($links['xrd']['link'] as $value => $link) {
241 if (!empty($link['@attributes'])) {
242 $attributes = $link['@attributes'];
243 } elseif ($value == '@attributes') {
249 if (!empty($attributes['rel']) && $attributes['rel'] == 'lrdd' && !empty($attributes['template'])) {
250 $type = (empty($attributes['type']) ? '' : $attributes['type']);
252 $lrdd[$type] = $attributes['template'];
256 if (Network::isUrlBlocked($host_url)) {
257 Logger::info('Domain is blocked', ['url' => $host]);
261 self::$baseurl = $host_url;
263 Logger::info('Probing successful', ['host' => $host]);
269 * Check an URI for LRDD data
271 * @param string $uri Address that should be probed
272 * @return array uri data
273 * @throws HTTPException\InternalServerErrorException
275 public static function lrdd(string $uri): array
277 $data = self::getWebfingerArray($uri);
281 $webfinger = $data['webfinger'];
283 if (empty($webfinger['links'])) {
284 Logger::info('No webfinger links found', ['uri' => $uri]);
290 foreach ($webfinger['links'] as $link) {
291 $data[] = ['@attributes' => $link];
294 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
295 foreach ($webfinger['aliases'] as $alias) {
309 * Fetch information (protocol endpoints and user information) about a given uri
311 * @param string $uri Address that should be probed
312 * @param string $network Test for this specific network
313 * @param integer $uid User ID for the probe (only used for mails)
314 * @param boolean $cache Use cached values?
316 * @return array uri data
317 * @throws HTTPException\InternalServerErrorException
318 * @throws \ImagickException
320 public static function uri(string $uri, string $network = '', int $uid = -1): array
322 // Local profiles aren't probed via network
323 if (empty($network) && Contact::isLocal($uri)) {
324 $data = self::localProbe($uri);
331 $uid = DI::userSession()->getLocalUserId();
334 if (empty($network) || ($network == Protocol::ACTIVITYPUB)) {
335 $ap_profile = ActivityPub::probeProfile($uri);
340 self::$isTimeout = false;
342 if ($network != Protocol::ACTIVITYPUB) {
343 $data = self::detect($uri, $network, $uid, $ap_profile);
344 if (!is_array($data)) {
347 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
349 } elseif (!empty($ap_profile)) {
350 $ap_profile['batch'] = '';
351 $data = array_merge($ap_profile, $data);
357 if (!isset($data['url'])) {
361 if (empty($data['photo'])) {
362 $data['photo'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
365 if (empty($data['name'])) {
366 if (!empty($data['nick'])) {
367 $data['name'] = $data['nick'];
370 if (empty($data['name'])) {
371 $data['name'] = $data['url'];
375 if (empty($data['nick'])) {
376 $data['nick'] = strtolower($data['name']);
378 if (strpos($data['nick'], ' ')) {
379 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
383 if (!empty($data['baseurl']) && empty($data['gsid'])) {
384 $data['gsid'] = GServer::getID($data['baseurl']);
387 if (empty($data['network'])) {
388 $data['network'] = Protocol::PHANTOM;
391 // Ensure that local connections always are DFRN
392 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
393 $data['network'] = Protocol::DFRN;
396 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
397 $data['hide'] = self::getHideStatus($data['url']);
400 return self::rearrangeData($data);
405 * Fetches the "hide" status from the profile
407 * @param string $url URL of the profile
408 * @return boolean "hide" status
410 private static function getHideStatus(string $url): bool
412 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::CONTENT_LENGTH => 1000000]);
413 if (!$curlResult->isSuccess()) {
417 // If it isn't a HTML file then exit
418 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
422 $body = $curlResult->getBody();
427 $doc = new DOMDocument();
428 @$doc->loadHTML($body);
430 $xpath = new DOMXPath($doc);
432 $list = $xpath->query('//meta[@name]');
433 foreach ($list as $node) {
435 if ($node->attributes->length) {
436 foreach ($node->attributes as $attribute) {
437 $meta_tag[$attribute->name] = $attribute->value;
441 if (empty($meta_tag['content'])) {
445 $content = strtolower(trim($meta_tag['content']));
447 switch (strtolower(trim($meta_tag['name']))) {
448 case 'dfrn-global-visibility':
449 if ($content == 'false') {
454 if (strpos($content, 'noindex') !== false) {
465 * Fetch the "subscribe" and add it to the result
467 * @param array $result Result array
468 * @param array $webfinger Webfinger data
470 * @return array result Altered/unaltered result array
472 private static function getSubscribeLink(array $result, array $webfinger): array
474 if (empty($webfinger['links'])) {
478 foreach ($webfinger['links'] as $link) {
479 if (!empty($link['template']) && ($link['rel'] === ActivityNamespace::OSTATUSSUB)) {
480 $result['subscribe'] = $link['template'];
488 * Get webfinger data from a given URI
490 * @param string $uri URI
492 * @return array Webfinger data
493 * @throws HTTPException\InternalServerErrorException
495 private static function getWebfingerArray(string $uri): array
497 $parts = parse_url($uri);
499 if (!empty($parts['scheme']) && !empty($parts['host'])) {
500 $host = $parts['host'];
501 if (!empty($parts['port'])) {
502 $host .= ':' . $parts['port'];
505 $baseurl = $parts['scheme'] . '://' . $host;
510 $path_parts = explode('/', trim($parts['path'] ?? '', '/'));
511 if (!empty($path_parts)) {
512 $nick = ltrim(end($path_parts), '@');
513 $addr = $nick . '@' . $host;
516 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
517 if (empty($webfinger)) {
518 $lrdd = self::hostMeta($host);
521 if (empty($webfinger) && empty($lrdd)) {
522 while (empty($lrdd) && empty($webfinger) && (sizeof($path_parts) > 1)) {
523 $host .= '/' . array_shift($path_parts);
524 $baseurl = $parts['scheme'] . '://' . $host;
527 $addr = $nick . '@' . $host;
530 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
531 if (empty($webfinger)) {
532 $lrdd = self::hostMeta($host);
536 if (empty($lrdd) && empty($webfinger)) {
540 } elseif (strstr($uri, '@')) {
541 // Remove "acct:" from the URI
542 $uri = str_replace('acct:', '', $uri);
544 $host = substr($uri, strpos($uri, '@') + 1);
545 $nick = substr($uri, 0, strpos($uri, '@'));
548 $webfinger = self::getWebfinger('https://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
549 if (self::$isTimeout) {
553 if (empty($webfinger)) {
554 $webfinger = self::getWebfinger('http://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
555 if (self::$isTimeout) {
559 $baseurl = 'https://' . $host;
562 if (empty($webfinger)) {
563 $lrdd = self::hostMeta($host);
564 if (self::$isTimeout) {
567 $baseurl = self::$baseurl;
569 $baseurl = 'http://' . $host;
572 Logger::info('URI was not detectable', ['uri' => $uri]);
576 if (empty($webfinger)) {
577 foreach ($lrdd as $type => $template) {
582 $webfinger = self::getWebfinger($template, $type, $uri, $addr);
586 if (empty($webfinger)) {
590 if ($webfinger['detected'] == $addr) {
591 $webfinger['nick'] = $nick;
592 $webfinger['addr'] = $addr;
595 $webfinger['baseurl'] = $baseurl;
601 * Perform network request for webfinger data
603 * @param string $template
604 * @param string $type
606 * @param string $addr
608 * @return array webfinger results
610 private static function getWebfinger(string $template, string $type, string $uri, string $addr): array
612 if (Network::isUrlBlocked($template)) {
613 Logger::info('Domain is blocked', ['url' => $template]);
617 // First try the address because this is the primary purpose of webfinger
620 $path = str_replace('{uri}', urlencode('acct:' . $addr), $template);
621 $webfinger = self::webfinger($path, $type);
622 if (self::$isTimeout) {
628 if (empty($webfinger) && $uri != $addr) {
630 $path = str_replace('{uri}', urlencode($uri), $template);
631 $webfinger = self::webfinger($path, $type);
632 if (self::$isTimeout) {
637 if (empty($webfinger)) {
641 return ['webfinger' => $webfinger, 'detected' => $detected];
645 * Fetch information (protocol endpoints and user information) about a given uri
647 * This function is only called by the "uri" function that adds caching and rearranging of data.
649 * @param string $uri Address that should be probed
650 * @param string $network Test for this specific network
651 * @param integer $uid User ID for the probe (only used for mails)
652 * @param array $ap_profile Previously probed AP profile
653 * @return array URI data
654 * @throws HTTPException\InternalServerErrorException
656 private static function detect(string $uri, string $network, int $uid, array $ap_profile): array
660 'network' => $network,
665 Hook::callAll('probe_detect', $hookData);
667 if (isset($hookData['result'])) {
668 return is_array($hookData['result']) ? $hookData['result'] : [];
671 $parts = parse_url($uri);
672 if (empty($parts['scheme']) && empty($parts['host']) && !strstr($parts['path'], '@')) {
673 Logger::info('URI was not detectable', ['uri' => $uri]);
677 // If the URI starts with "mailto:" then jump directly to the mail detection
678 if (strpos($uri, 'mailto:') !== false) {
679 $uri = str_replace('mailto:', '', $uri);
680 return self::mail($uri, $uid);
683 if ($network == Protocol::MAIL) {
684 return self::mail($uri, $uid);
687 Logger::info('Probing start', ['uri' => $uri]);
689 if (!empty($ap_profile['addr']) && ($ap_profile['addr'] != $uri)) {
690 $data = self::getWebfingerArray($ap_profile['addr']);
694 $data = self::getWebfingerArray($uri);
698 if (!empty($parts['scheme'])) {
699 return self::feed($uri);
700 } elseif (!empty($uid)) {
701 return self::mail($uri, $uid);
707 $webfinger = $data['webfinger'];
708 $nick = $data['nick'] ?? '';
709 $addr = $data['addr'] ?? '';
710 $baseurl = $data['baseurl'] ?? '';
714 if (in_array($network, ['', Protocol::DFRN])) {
715 $result = self::dfrn($webfinger);
717 if ((!$result && ($network == '')) || ($network == Protocol::DIASPORA)) {
718 $result = self::diaspora($webfinger);
720 if ((!$result && ($network == '')) || ($network == Protocol::OSTATUS)) {
721 $result = self::ostatus($webfinger);
723 if (in_array($network, ['', Protocol::ZOT])) {
724 $result = self::zot($webfinger, $result, $baseurl);
726 if ((!$result && ($network == '')) || ($network == Protocol::PUMPIO)) {
727 $result = self::pumpio($webfinger, $addr);
729 if (empty($result['network']) && empty($ap_profile['network']) || ($network == Protocol::FEED)) {
730 $result = self::feed($uri);
732 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
733 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
734 if ((empty($result['nick']) || (strstr($result['nick'], ' '))) && ($nick != '')) {
735 $result['nick'] = $nick;
738 if (empty($result['addr']) && ($addr != '')) {
739 $result['addr'] = $addr;
743 $result = self::getSubscribeLink($result, $webfinger);
745 if (empty($result['network'])) {
746 $result['network'] = Protocol::PHANTOM;
749 if (empty($result['baseurl']) && !empty($baseurl)) {
750 $result['baseurl'] = $baseurl;
753 if (empty($result['url'])) {
754 $result['url'] = $uri;
757 Logger::info('Probing done', ['uri' => $uri, 'network' => $result['network']]);
763 * Check for Zot contact
765 * @param array $webfinger Webfinger data
766 * @param array $data previously probed data
767 * @param string $baseUrl Base URL
769 * @return array Zot data
770 * @throws HTTPException\InternalServerErrorException
772 private static function zot(array $webfinger, array $data, string $baseurl): array
774 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
775 foreach ($webfinger['aliases'] as $alias) {
776 if (substr($alias, 0, 5) == 'acct:') {
777 $data['addr'] = substr($alias, 5);
782 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
783 $data['addr'] = substr($webfinger['subject'], 5);
787 foreach ($webfinger['links'] as $link) {
788 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
789 $zot_url = $link['href'];
793 if (empty($zot_url) && !empty($data['addr']) && !empty($baseurl)) {
794 $condition = ['nurl' => Strings::normaliseLink($baseurl), 'platform' => ['hubzilla']];
795 if (!DBA::exists('gserver', $condition)) {
798 $zot_url = $baseurl . '/.well-known/zot-info?address=' . $data['addr'];
801 if (empty($zot_url)) {
805 $data = self::pollZot($zot_url, $data);
807 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
808 foreach ($webfinger['aliases'] as $alias) {
809 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
810 $data['alias'] = $alias;
818 public static function pollZot(string $url, array $data): array
820 $curlResult = DI::httpClient()->get($url, HttpClientAccept::JSON);
821 if ($curlResult->isTimeout()) {
824 $content = $curlResult->getBody();
829 $json = json_decode($content, true);
830 if (!is_array($json)) {
834 if (empty($data['network'])) {
835 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
836 $data['network'] = Protocol::ZOT;
837 } elseif (!isset($json['protocols'])) {
838 $data['network'] = Protocol::ZOT;
842 if (!empty($json['guid']) && empty($data['guid'])) {
843 $data['guid'] = $json['guid'];
845 if (!empty($json['key']) && empty($data['pubkey'])) {
846 $data['pubkey'] = $json['key'];
848 if (!empty($json['name'])) {
849 $data['name'] = $json['name'];
851 if (!empty($json['photo'])) {
852 $data['photo'] = $json['photo'];
853 if (!empty($json['photo_updated'])) {
854 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
857 if (!empty($json['address'])) {
858 $data['addr'] = $json['address'];
860 if (!empty($json['url'])) {
861 $data['url'] = $json['url'];
863 if (!empty($json['connections_url'])) {
864 $data['poco'] = $json['connections_url'];
866 if (isset($json['searchable'])) {
867 $data['hide'] = !$json['searchable'];
869 if (!empty($json['public_forum'])) {
870 $data['community'] = $json['public_forum'];
871 $data['account-type'] = User::PAGE_FLAGS_COMMUNITY;
874 if (!empty($json['profile'])) {
875 $profile = $json['profile'];
876 if (!empty($profile['description'])) {
877 $data['about'] = $profile['description'];
879 if (!empty($profile['keywords'])) {
880 $keywords = implode(', ', $profile['keywords']);
881 if (!empty($keywords)) {
882 $data['keywords'] = $keywords;
887 if (!empty($profile['region'])) {
888 $loc['region'] = $profile['region'];
890 if (!empty($profile['country'])) {
891 $loc['country-name'] = $profile['country'];
893 $location = Profile::formatLocation($loc);
894 if (!empty($location)) {
895 $data['location'] = $location;
903 * Perform a webfinger request.
905 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
907 * @param string $url Address that should be probed
908 * @param string $type type
910 * @return array webfinger data
911 * @throws HTTPException\InternalServerErrorException
913 public static function webfinger(string $url, string $type): array
915 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
917 $curlResult = DI::httpClient()->get($url, $type, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
918 if ($curlResult->isTimeout()) {
919 self::$isTimeout = true;
922 $data = $curlResult->getBody();
924 $webfinger = json_decode($data, true);
925 if (!empty($webfinger)) {
926 if (!isset($webfinger['links'])) {
927 Logger::info('No json webfinger links', ['url' => $url]);
933 // If it is not JSON, maybe it is XML
934 $xrd = XML::parseString($data, true);
935 if (!is_object($xrd)) {
936 Logger::info('No webfinger data retrievable', ['url' => $url]);
940 $xrd_arr = XML::elementToArray($xrd);
941 if (!isset($xrd_arr['xrd']['link'])) {
942 Logger::info('No XML webfinger links', ['url' => $url]);
948 if (!empty($xrd_arr['xrd']['subject'])) {
949 $webfinger['subject'] = $xrd_arr['xrd']['subject'];
952 if (!empty($xrd_arr['xrd']['alias'])) {
953 $webfinger['aliases'] = $xrd_arr['xrd']['alias'];
956 $webfinger['links'] = [];
958 foreach ($xrd_arr['xrd']['link'] as $value => $data) {
959 if (!empty($data['@attributes'])) {
960 $attributes = $data['@attributes'];
961 } elseif ($value == '@attributes') {
967 $webfinger['links'][] = $attributes;
973 * Poll the Friendica specific noscrape page.
975 * "noscrape" is a faster alternative to fetch the data from the hcard.
976 * This functionality was originally created for the directory.
978 * @param string $noscrape_url Link to the noscrape page
979 * @param array $data The already fetched data
981 * @return array noscrape data
982 * @throws HTTPException\InternalServerErrorException
984 private static function pollNoscrape(string $noscrape_url, array $data): array
986 $curlResult = DI::httpClient()->get($noscrape_url, HttpClientAccept::JSON);
987 if ($curlResult->isTimeout()) {
988 self::$isTimeout = true;
991 $content = $curlResult->getBody();
993 Logger::info('Empty body', ['url' => $noscrape_url]);
997 $json = json_decode($content, true);
998 if (!is_array($json)) {
999 Logger::info('No json data', ['url' => $noscrape_url]);
1003 if (!empty($json['fn'])) {
1004 $data['name'] = $json['fn'];
1007 if (!empty($json['addr'])) {
1008 $data['addr'] = $json['addr'];
1011 if (!empty($json['nick'])) {
1012 $data['nick'] = $json['nick'];
1015 if (!empty($json['guid'])) {
1016 $data['guid'] = $json['guid'];
1019 if (!empty($json['comm'])) {
1020 $data['community'] = $json['comm'];
1023 if (!empty($json['tags'])) {
1024 $keywords = implode(', ', $json['tags']);
1025 if ($keywords != '') {
1026 $data['keywords'] = $keywords;
1030 $location = Profile::formatLocation($json);
1032 $data['location'] = $location;
1035 if (!empty($json['about'])) {
1036 $data['about'] = $json['about'];
1039 if (!empty($json['xmpp'])) {
1040 $data['xmpp'] = $json['xmpp'];
1043 if (!empty($json['matrix'])) {
1044 $data['matrix'] = $json['matrix'];
1047 if (!empty($json['key'])) {
1048 $data['pubkey'] = $json['key'];
1051 if (!empty($json['photo'])) {
1052 $data['photo'] = $json['photo'];
1055 if (!empty($json['dfrn-request'])) {
1056 $data['request'] = $json['dfrn-request'];
1059 if (!empty($json['dfrn-confirm'])) {
1060 $data['confirm'] = $json['dfrn-confirm'];
1063 if (!empty($json['dfrn-notify'])) {
1064 $data['notify'] = $json['dfrn-notify'];
1067 if (!empty($json['dfrn-poll'])) {
1068 $data['poll'] = $json['dfrn-poll'];
1071 if (isset($json['hide'])) {
1072 $data['hide'] = (bool)$json['hide'];
1074 $data['hide'] = false;
1081 * Check for valid DFRN data
1083 * @param array $data DFRN data
1085 * @return int Number of errors
1087 public static function validDfrn(array $data): int
1090 if (!isset($data['key'])) {
1093 if (!isset($data['dfrn-request'])) {
1096 if (!isset($data['dfrn-confirm'])) {
1099 if (!isset($data['dfrn-notify'])) {
1102 if (!isset($data['dfrn-poll'])) {
1109 * Fetch data from a DFRN profile page and via "noscrape"
1111 * @param string $profile_link Link to the profile page
1112 * @return array profile data
1113 * @throws HTTPException\InternalServerErrorException
1114 * @throws \ImagickException
1116 public static function profile(string $profile_link): array
1120 Logger::info('Check profile', ['link' => $profile_link]);
1122 // Fetch data via noscrape - this is faster
1123 $noscrape_url = str_replace(['/hcard/', '/profile/'], '/noscrape/', $profile_link);
1124 $data = self::pollNoscrape($noscrape_url, $data);
1126 if (!isset($data['notify'])
1127 || !isset($data['confirm'])
1128 || !isset($data['request'])
1129 || !isset($data['poll'])
1130 || !isset($data['name'])
1131 || !isset($data['photo'])
1133 $data = self::pollHcard($profile_link, $data, true);
1138 if (empty($data['addr']) || empty($data['nick'])) {
1139 $probe_data = self::uri($profile_link);
1140 $data['addr'] = ($data['addr'] ?? '') ?: $probe_data['addr'];
1141 $data['nick'] = ($data['nick'] ?? '') ?: $probe_data['nick'];
1144 $prof_data['addr'] = $data['addr'];
1145 $prof_data['nick'] = $data['nick'];
1146 $prof_data['dfrn-request'] = $data['request'] ?? null;
1147 $prof_data['dfrn-confirm'] = $data['confirm'] ?? null;
1148 $prof_data['dfrn-notify'] = $data['notify'] ?? null;
1149 $prof_data['dfrn-poll'] = $data['poll'] ?? null;
1150 $prof_data['photo'] = $data['photo'] ?? null;
1151 $prof_data['fn'] = $data['name'] ?? null;
1152 $prof_data['key'] = $data['pubkey'] ?? null;
1154 Logger::debug('Result', ['link' => $profile_link, 'data' => $prof_data]);
1160 * Check for DFRN contact
1162 * @param array $webfinger Webfinger data
1163 * @return array DFRN data
1164 * @throws HTTPException\InternalServerErrorException
1166 private static function dfrn(array $webfinger): array
1170 // The array is reversed to take into account the order of preference for same-rel links
1171 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1172 foreach (array_reverse($webfinger['links']) as $link) {
1173 if (($link['rel'] == ActivityNamespace::DFRN) && !empty($link['href'])) {
1174 $data['network'] = Protocol::DFRN;
1175 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1176 $data['poll'] = $link['href'];
1177 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1178 $data['url'] = $link['href'];
1179 } elseif (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1180 $hcard_url = $link['href'];
1181 } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1182 $data['poco'] = $link['href'];
1183 } elseif (($link['rel'] == 'http://webfinger.net/rel/avatar') && !empty($link['href'])) {
1184 $data['photo'] = $link['href'];
1185 } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1186 $data['baseurl'] = trim($link['href'], '/');
1187 } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1188 $data['guid'] = $link['href'];
1189 } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1190 $data['pubkey'] = base64_decode($link['href']);
1192 if (strstr($data['pubkey'], 'RSA ')) {
1193 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1198 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1199 foreach ($webfinger['aliases'] as $alias) {
1200 if (empty($data['url']) && !strstr($alias, '@')) {
1201 $data['url'] = $alias;
1202 } elseif (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
1203 $data['alias'] = $alias;
1204 } elseif (substr($alias, 0, 5) == 'acct:') {
1205 $data['addr'] = substr($alias, 5);
1210 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1211 $data['addr'] = substr($webfinger['subject'], 5);
1214 if (!isset($data['network']) || ($hcard_url == '')) {
1218 // Fetch data via noscrape - this is faster
1219 $noscrape_url = str_replace('/hcard/', '/noscrape/', $hcard_url);
1220 $data = self::pollNoscrape($noscrape_url, $data);
1222 if (isset($data['notify'])
1223 && isset($data['confirm'])
1224 && isset($data['request'])
1225 && isset($data['poll'])
1226 && isset($data['name'])
1227 && isset($data['photo'])
1232 $data = self::pollHcard($hcard_url, $data, true);
1238 * Poll the hcard page (Diaspora and Friendica specific)
1240 * @param string $hcard_url Link to the hcard page
1241 * @param array $data The already fetched data
1242 * @param boolean $dfrn Poll DFRN specific data
1243 * @return array hcard data
1244 * @throws HTTPException\InternalServerErrorException
1246 private static function pollHcard(string $hcard_url, array $data, bool $dfrn = false): array
1248 $curlResult = DI::httpClient()->get($hcard_url, HttpClientAccept::HTML);
1249 if ($curlResult->isTimeout()) {
1250 self::$isTimeout = true;
1253 $content = $curlResult->getBody();
1254 if (empty($content)) {
1258 $doc = new DOMDocument();
1259 if (!@$doc->loadHTML($content)) {
1263 $xpath = new DomXPath($doc);
1265 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1266 if (!is_object($vcards)) {
1270 if (!isset($data['baseurl'])) {
1271 $data['baseurl'] = '';
1274 if ($vcards->length > 0) {
1275 $vcard = $vcards->item(0);
1277 // We have to discard the guid from the hcard in favour of the guid from lrdd
1278 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1279 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1280 if (($search->length > 0) && empty($data['guid'])) {
1281 $data['guid'] = $search->item(0)->nodeValue;
1284 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1285 if ($search->length > 0) {
1286 $data['nick'] = $search->item(0)->nodeValue;
1289 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1290 if ($search->length > 0) {
1291 $data['name'] = $search->item(0)->nodeValue;
1294 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' given_name ')]", $vcard); // */
1295 if ($search->length > 0) {
1296 $data["given_name"] = $search->item(0)->nodeValue;
1299 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' family_name ')]", $vcard); // */
1300 if ($search->length > 0) {
1301 $data["family_name"] = $search->item(0)->nodeValue;
1304 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1305 if ($search->length > 0) {
1306 $data['hide'] = (strtolower($search->item(0)->nodeValue) != 'true');
1309 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1310 if ($search->length > 0) {
1311 $data['pubkey'] = $search->item(0)->nodeValue;
1312 if (strstr($data['pubkey'], 'RSA ')) {
1313 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1317 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1318 if ($search->length > 0) {
1319 $data['baseurl'] = trim($search->item(0)->nodeValue, '/');
1324 if (!empty($vcard)) {
1325 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1326 foreach ($photos as $photo) {
1328 foreach ($photo->attributes as $attribute) {
1329 $attr[$attribute->name] = trim($attribute->value);
1332 if (isset($attr['src']) && isset($attr['width'])) {
1333 $avatars[$attr['width']] = self::fixAvatar($attr['src'], $data['baseurl']);
1336 // We don't have a width. So we just take everything that we got.
1337 // This is a Hubzilla workaround which doesn't send a width.
1338 if (!$avatars && !empty($attr['src'])) {
1339 $avatars[] = self::fixAvatar($attr['src'], $data['baseurl']);
1346 $data['photo'] = array_pop($avatars);
1348 $data['photo_medium'] = array_pop($avatars);
1352 $data['photo_small'] = array_pop($avatars);
1357 // Poll DFRN specific data
1358 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1359 if ($search->length > 0) {
1360 foreach ($search as $link) {
1361 //$data['request'] = $search->item(0)->nodeValue;
1363 foreach ($link->attributes as $attribute) {
1364 $attr[$attribute->name] = trim($attribute->value);
1367 $data[substr($attr['rel'], 5)] = $attr['href'];
1371 // Older Friendica versions had used the "uid" field differently than newer versions
1372 if (!empty($data['nick']) && !empty($data['guid']) && ($data['nick'] == $data['guid'])) {
1373 unset($data['guid']);
1381 * Check for Diaspora contact
1383 * @param array $webfinger Webfinger data
1385 * @return array Diaspora data
1386 * @throws HTTPException\InternalServerErrorException
1388 private static function diaspora(array $webfinger): array
1393 // The array is reversed to take into account the order of preference for same-rel links
1394 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1395 foreach (array_reverse($webfinger['links']) as $link) {
1396 if (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1397 $hcard_url = $link['href'];
1398 } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1399 $data['baseurl'] = trim($link['href'], '/');
1400 } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1401 $data['guid'] = $link['href'];
1402 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1403 $data['url'] = $link['href'];
1404 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && empty($link['type']) && !empty($link['href'])) {
1405 $profile_url = $link['href'];
1406 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1407 $data['poll'] = $link['href'];
1408 } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1409 $data['poco'] = $link['href'];
1410 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1411 $data['notify'] = $link['href'];
1412 } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1413 $data['pubkey'] = base64_decode($link['href']);
1415 if (strstr($data['pubkey'], 'RSA ')) {
1416 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1421 if (empty($data['url']) && !empty($profile_url)) {
1422 $data['url'] = $profile_url;
1425 if (empty($data['url']) || empty($hcard_url)) {
1429 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1430 foreach ($webfinger['aliases'] as $alias) {
1431 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data['url']) && ! strstr($alias, '@')) {
1432 $data['alias'] = $alias;
1433 } elseif (substr($alias, 0, 5) == 'acct:') {
1434 $data['addr'] = substr($alias, 5);
1439 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1440 $data['addr'] = substr($webfinger['subject'], 5);
1443 // Fetch further information from the hcard
1444 $data = self::pollHcard($hcard_url, $data);
1450 if (!empty($data['url'])
1451 && !empty($data['guid'])
1452 && !empty($data['baseurl'])
1453 && !empty($data['pubkey'])
1454 && !empty($hcard_url)
1456 $data['network'] = Protocol::DIASPORA;
1457 $data['manually-approve'] = false;
1459 // The Diaspora handle must always be lowercase
1460 if (!empty($data['addr'])) {
1461 $data['addr'] = strtolower($data['addr']);
1464 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1465 $data['notify'] = $data['baseurl'] . '/receive/users/' . $data['guid'];
1466 $data['batch'] = $data['baseurl'] . '/receive/public';
1475 * Check for OStatus contact
1477 * @param array $webfinger Webfinger data
1478 * @param bool $short Short detection mode
1480 * @return array|bool OStatus data or "false" on error or "true" on short mode
1481 * @throws HTTPException\InternalServerErrorException
1483 private static function ostatus(array $webfinger, bool $short = false)
1487 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1488 foreach ($webfinger['aliases'] as $alias) {
1489 if (strstr($alias, '@') && !strstr(Strings::normaliseLink($alias), 'http://')) {
1490 $data['addr'] = str_replace('acct:', '', $alias);
1495 if (!empty($webfinger['subject']) && strstr($webfinger['subject'], '@')
1496 && !strstr(Strings::normaliseLink($webfinger['subject']), 'http://')
1498 $data['addr'] = str_replace('acct:', '', $webfinger['subject']);
1501 if (!empty($webfinger['links'])) {
1502 // The array is reversed to take into account the order of preference for same-rel links
1503 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1504 foreach (array_reverse($webfinger['links']) as $link) {
1505 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1506 && (($link['type'] ?? '') == 'text/html')
1507 && ($link['href'] != '')
1509 $data['url'] = $data['alias'] = $link['href'];
1510 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1511 $data['notify'] = $link['href'];
1512 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1513 $data['poll'] = $link['href'];
1514 } elseif (($link['rel'] == 'magic-public-key') && !empty($link['href'])) {
1515 $pubkey = $link['href'];
1517 if (substr($pubkey, 0, 5) === 'data:') {
1518 if (strstr($pubkey, ',')) {
1519 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1521 $pubkey = substr($pubkey, 5);
1523 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1524 $curlResult = DI::httpClient()->get($pubkey, HttpClientAccept::MAGIC_KEY);
1525 if ($curlResult->isTimeout()) {
1526 self::$isTimeout = true;
1527 return $short ? false : [];
1529 Logger::debug('Fetched public key', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $pubkey]);
1530 $pubkey = $curlResult->getBody();
1534 $data['pubkey'] = Salmon::magicKeyToPem($pubkey);
1535 } catch (\Throwable $e) {
1542 if (isset($data['notify']) && isset($data['pubkey'])
1543 && isset($data['poll'])
1544 && isset($data['url'])
1546 $data['network'] = Protocol::OSTATUS;
1547 $data['manually-approve'] = false;
1549 return $short ? false : [];
1556 // Fetch all additional data from the feed
1557 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::FEED_XML);
1558 if ($curlResult->isTimeout()) {
1559 self::$isTimeout = true;
1562 $feed = $curlResult->getBody();
1563 $feed_data = Feed::import($feed);
1568 if (!empty($feed_data['header']['author-name'])) {
1569 $data['name'] = $feed_data['header']['author-name'];
1571 if (!empty($feed_data['header']['author-nick'])) {
1572 $data['nick'] = $feed_data['header']['author-nick'];
1574 if (!empty($feed_data['header']['author-avatar'])) {
1575 $data['photo'] = self::fixAvatar($feed_data['header']['author-avatar'], $data['url']);
1577 if (!empty($feed_data['header']['author-id'])) {
1578 $data['alias'] = $feed_data['header']['author-id'];
1580 if (!empty($feed_data['header']['author-location'])) {
1581 $data['location'] = $feed_data['header']['author-location'];
1583 if (!empty($feed_data['header']['author-about'])) {
1584 $data['about'] = $feed_data['header']['author-about'];
1586 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1587 // So we take the value that we just fetched, although the other one worked as well
1588 if (!empty($feed_data['header']['author-link'])) {
1589 $data['url'] = $feed_data['header']['author-link'];
1592 if ($data['url'] == $data['alias']) {
1593 $data['alias'] = '';
1596 /// @todo Fetch location and "about" from the feed as well
1601 * Fetch data from a pump.io profile page
1603 * @param string $profile_link Link to the profile page
1605 * @return array Profile data
1607 private static function pumpioProfileData(string $profile_link): array
1609 $curlResult = DI::httpClient()->get($profile_link, HttpClientAccept::HTML);
1610 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
1614 $doc = new DOMDocument();
1615 if (!@$doc->loadHTML($curlResult->getBody())) {
1619 $xpath = new DomXPath($doc);
1622 $data['name'] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1624 if ($data['name'] == '') {
1625 // This is ugly - but pump.io doesn't seem to know a better way for it
1626 $data['name'] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1627 $pos = strpos($data['name'], chr(10));
1629 $data['name'] = trim(substr($data['name'], 0, $pos));
1633 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1635 if ($data['location'] == '') {
1636 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1639 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1641 if ($data['about'] == '') {
1642 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1645 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1647 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1650 foreach ($avatar->attributes as $attribute) {
1651 if ($attribute->name == 'src') {
1652 $data['photo'] = trim($attribute->value);
1661 * Check for pump.io contact
1663 * @param array $webfinger Webfinger data
1664 * @param string $addr
1666 * @return array pump.io data
1668 private static function pumpio(array $webfinger, string $addr): array
1671 // The array is reversed to take into account the order of preference for same-rel links
1672 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1673 foreach (array_reverse($webfinger['links']) as $link) {
1674 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1675 && (($link['type'] ?? '') == 'text/html')
1676 && ($link['href'] != '')
1678 $data['url'] = $link['href'];
1679 } elseif (($link['rel'] == 'activity-inbox') && ($link['href'] != '')) {
1680 $data['notify'] = $link['href'];
1681 } elseif (($link['rel'] == 'activity-outbox') && ($link['href'] != '')) {
1682 $data['poll'] = $link['href'];
1683 } elseif (($link['rel'] == 'dialback') && ($link['href'] != '')) {
1684 $data['dialback'] = $link['href'];
1687 if (isset($data['poll']) && isset($data['notify'])
1688 && isset($data['dialback'])
1689 && isset($data['url'])
1691 // by now we use these fields only for the network type detection
1692 // So we unset all data that isn't used at the moment
1693 unset($data['dialback']);
1695 $data['network'] = Protocol::PUMPIO;
1700 $profile_data = self::pumpioProfileData($data['url']);
1702 if (!$profile_data) {
1706 $data = array_merge($data, $profile_data);
1708 if (($addr != '') && ($data['name'] != '')) {
1709 $name = trim(str_replace($addr, '', $data['name']));
1711 $data['name'] = $name;
1719 * Checks HTML page for RSS feed link
1721 * @param string $url Page link
1722 * @param string $body Page body string
1724 * @return string|false Feed link or false if body was invalid HTML document
1726 public static function getFeedLink(string $url, string $body)
1732 $doc = new DOMDocument();
1733 if (!@$doc->loadHTML($body)) {
1737 $xpath = new DOMXPath($doc);
1739 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1740 $feedUrl = $feedUrl ?: $xpath->evaluate('string(/html/head/link[@type="application/atom+xml" and @rel="alternate"]/@href)');
1742 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1748 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1750 * Loosely based on RFC 1808
1752 * @see https://tools.ietf.org/html/rfc1808
1754 * @param string $href The potential relative href found in the HTML document
1755 * @param string $base The HTML document URL
1756 * @param DOMXPath $xpath The HTML document XPath
1758 * @return string Absolute URL
1760 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath): string
1762 if (filter_var($href, FILTER_VALIDATE_URL)) {
1766 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1768 $baseParts = parse_url($base);
1769 if (empty($baseParts['host'])) {
1773 // Naked domain case (scheme://basehost)
1774 $path = $baseParts['path'] ?? '/';
1776 // Remove the filename part of the path if it exists (/base/path/file)
1777 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1779 $hrefParts = parse_url($href);
1781 if (!empty($hrefParts['path'])) {
1782 // Root path case (/path) including relative scheme case (//host/path)
1783 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1784 $path = $hrefParts['path'];
1786 $path = $path . '/' . $hrefParts['path'];
1788 // Resolve arbitrary relative path
1789 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1790 $parts = array_filter(explode('/', $path), 'strlen');
1792 foreach ($parts as $part) {
1793 if ('.' == $part) continue;
1794 if ('..' == $part) {
1795 array_pop($absolutes);
1797 $absolutes[] = $part;
1801 $path = '/' . implode('/', $absolutes);
1805 // Relative scheme case (//host/path)
1806 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1807 $baseParts['path'] = $path;
1808 unset($baseParts['query']);
1809 unset($baseParts['fragment']);
1811 return Network::unparseURL($baseParts);
1815 * Check for feed contact
1817 * @param string $url Profile link
1818 * @param boolean $probe Do a probe if the page contains a feed link
1820 * @return array feed data
1821 * @throws HTTPException\InternalServerErrorException
1823 private static function feed(string $url, bool $probe = true): array
1825 $curlResult = DI::httpClient()->get($url, HttpClientAccept::FEED_XML);
1826 if ($curlResult->isTimeout()) {
1827 self::$isTimeout = true;
1830 $feed = $curlResult->getBody();
1831 $feed_data = Feed::import($feed);
1838 $feed_url = self::getFeedLink($url, $feed);
1844 return self::feed($feed_url, false);
1847 if (!empty($feed_data['header']['author-name'])) {
1848 $data['name'] = $feed_data['header']['author-name'];
1851 if (!empty($feed_data['header']['author-nick'])) {
1852 $data['nick'] = $feed_data['header']['author-nick'];
1855 if (!empty($feed_data['header']['author-avatar'])) {
1856 $data['photo'] = $feed_data['header']['author-avatar'];
1859 if (!empty($feed_data['header']['author-id'])) {
1860 $data['alias'] = $feed_data['header']['author-id'];
1863 $data['url'] = $url;
1864 $data['poll'] = $url;
1866 $data['network'] = Protocol::FEED;
1872 * Check for mail contact
1874 * @param string $uri Profile link
1875 * @param integer $uid User ID
1877 * @return array mail data
1878 * @throws \Exception
1880 private static function mail(string $uri, int $uid): array
1882 if (!Network::isEmailDomainValid($uri)) {
1890 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1892 $condition = ["`uid` = ? AND `server` != ''", $uid];
1893 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1894 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1896 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1900 $mailbox = Email::constructMailboxName($mailacct);
1902 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1903 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1908 $msgs = Email::poll($mbox, $uri);
1909 Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
1911 if (!count($msgs)) {
1915 $phost = substr($uri, strpos($uri, '@') + 1);
1919 'network' => Protocol::MAIL,
1920 'name' => substr($uri, 0, strpos($uri, '@')),
1921 'photo' => Network::lookupAvatarByEmail($uri),
1922 'url' => 'mailto:' . $uri,
1923 'notify' => 'smtp ' . Strings::getRandomHex(),
1924 'poll' => 'email ' . Strings::getRandomHex(),
1927 $data['nick'] = $data['name'];
1929 $x = Email::messageMeta($mbox, $msgs[0]);
1931 if (stristr($x[0]->from, $uri)) {
1932 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1933 } elseif (stristr($x[0]->to, $uri)) {
1934 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1938 foreach ($adr as $feadr) {
1939 if ((strcasecmp($feadr->mailbox, $data['name']) == 0)
1940 &&(strcasecmp($feadr->host, $phost) == 0)
1941 && (strlen($feadr->personal))
1943 $personal = imap_mime_header_decode($feadr->personal);
1945 foreach ($personal as $perspart) {
1946 if ($perspart->charset != 'default') {
1947 $data['name'] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1949 $data['name'] .= $perspart->text;
1956 if (!empty($mbox)) {
1964 * Mix two paths together to possibly fix missing parts
1966 * @param string $avatar Path to the avatar
1967 * @param string $base Another path that is hopefully complete
1969 * @return string fixed avatar path
1970 * @throws \Exception
1972 public static function fixAvatar(string $avatar, string $base): string
1974 $base_parts = parse_url($base);
1976 // Remove all parts that could create a problem
1977 unset($base_parts['path']);
1978 unset($base_parts['query']);
1979 unset($base_parts['fragment']);
1981 $avatar_parts = parse_url($avatar);
1984 $parts = array_merge($base_parts, $avatar_parts);
1986 // And put them together again
1987 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1988 $host = isset($parts['host']) ? $parts['host'] : '';
1989 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1990 $path = isset($parts['path']) ? $parts['path'] : '';
1991 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1992 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1994 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1996 Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
2002 * Fetch the last date that the contact had posted something (publically)
2004 * @param array $data probing result
2006 * @return string last activity
2008 public static function getLastUpdate(array $data): string
2010 $uid = User::getIdForURL($data['url']);
2012 $contact = Contact::selectFirst(['url', 'last-item'], ['self' => true, 'uid' => $uid]);
2013 if (!empty($contact['last-item'])) {
2014 return $contact['last-item'];
2018 if ($lastUpdate = self::updateFromNoScrape($data)) {
2022 if (!empty($data['outbox'])) {
2023 return self::updateFromOutbox($data['outbox'], $data);
2024 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
2025 return self::updateFromOutbox($data['poll'], $data);
2026 } elseif (!empty($data['poll'])) {
2027 return self::updateFromFeed($data);
2034 * Fetch the last activity date from the "noscrape" endpoint
2036 * @param array $data Probing result
2038 * @return string last activity or true if update was successful or the server was unreachable
2040 private static function updateFromNoScrape(array $data): string
2042 if (empty($data['baseurl'])) {
2046 // Check the 'noscrape' endpoint when it is a Friendica server
2047 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
2048 Strings::normaliseLink($data['baseurl'])]);
2049 if (!DBA::isResult($gserver)) {
2053 $curlResult = DI::httpClient()->get($gserver['noscrape'] . '/' . $data['nick'], HttpClientAccept::JSON);
2055 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
2056 $noscrape = json_decode($curlResult->getBody(), true);
2057 if (!empty($noscrape) && !empty($noscrape['updated'])) {
2058 return DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2066 * Fetch the last activity date from an ActivityPub Outbox
2068 * @param string $feed
2069 * @param array $data Probing result
2071 * @return string last activity
2072 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2074 private static function updateFromOutbox(string $feed, array $data): string
2076 $outbox = ActivityPub::fetchContent($feed);
2077 if (empty($outbox)) {
2081 if (!empty($outbox['orderedItems'])) {
2082 $items = $outbox['orderedItems'];
2083 } elseif (!empty($outbox['first']['orderedItems'])) {
2084 $items = $outbox['first']['orderedItems'];
2085 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2086 return self::updateFromOutbox($outbox['first']['href'], $data);
2087 } elseif (!empty($outbox['first'])) {
2088 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2089 return self::updateFromOutbox($outbox['first'], $data);
2091 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2099 foreach ($items as $activity) {
2100 if (!empty($activity['published'])) {
2101 $published = DateTimeFormat::utc($activity['published']);
2102 } elseif (!empty($activity['object']['published'])) {
2103 $published = DateTimeFormat::utc($activity['object']['published']);
2108 if ($last_updated < $published) {
2109 $last_updated = $published;
2113 if (!empty($last_updated)) {
2114 return $last_updated;
2121 * Fetch the last activity date from an XML feed
2123 * @param array $data Probing result
2124 * @return string last activity
2126 private static function updateFromFeed(array $data): string
2128 // Search for the newest entry in the feed
2129 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::ATOM_XML);
2130 if (!$curlResult->isSuccess() || !$curlResult->getBody()) {
2134 $doc = new DOMDocument();
2135 @$doc->loadXML($curlResult->getBody());
2137 $xpath = new DOMXPath($doc);
2138 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2140 $entries = $xpath->query('/atom:feed/atom:entry');
2144 foreach ($entries as $entry) {
2145 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2146 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
2147 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2148 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2150 if (empty($published) || empty($updated)) {
2151 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2155 if ($last_updated < $published) {
2156 $last_updated = $published;
2159 if ($last_updated < $updated) {
2160 $last_updated = $updated;
2164 if (!empty($last_updated)) {
2165 return $last_updated;
2172 * Probe data from local profiles without network traffic
2174 * @param string $url
2176 * @return array probed data
2177 * @throws HTTPException\InternalServerErrorException
2178 * @throws HTTPException\NotFoundException
2180 private static function localProbe(string $url): array
2183 $uid = User::getIdForURL($url);
2185 throw new HTTPException\NotFoundException('User not found.');
2188 $owner = User::getOwnerDataById($uid);
2189 $approfile = ActivityPub\Transmitter::getProfile($uid);
2191 if (empty($owner['gsid'])) {
2192 $owner['gsid'] = GServer::getID($approfile['generator']['url']);
2196 'name' => $owner['name'], 'nick' => $owner['nick'], 'guid' => $approfile['diaspora:guid'] ?? '',
2197 'url' => $owner['url'], 'addr' => $owner['addr'], 'alias' => $owner['alias'],
2198 'photo' => User::getAvatarUrl($owner),
2199 'header' => $owner['header'] ? Contact::getHeaderUrlForId($owner['id'], $owner['updated']) : '',
2200 'account-type' => $owner['contact-type'], 'community' => ($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY),
2201 'keywords' => $owner['keywords'], 'location' => $owner['location'], 'about' => $owner['about'],
2202 'xmpp' => $owner['xmpp'], 'matrix' => $owner['matrix'],
2203 'hide' => !$owner['net-publish'], 'batch' => '', 'notify' => $owner['notify'],
2204 'poll' => $owner['poll'], 'request' => $owner['request'], 'confirm' => $owner['confirm'],
2205 'subscribe' => $approfile['generator']['url'] . '/contact/follow?url={uri}', 'poco' => $owner['poco'],
2206 'following' => $approfile['following'], 'followers' => $approfile['followers'],
2207 'inbox' => $approfile['inbox'], 'outbox' => $approfile['outbox'],
2208 'sharedinbox' => $approfile['endpoints']['sharedInbox'], 'network' => Protocol::DFRN,
2209 'pubkey' => $owner['upubkey'], 'baseurl' => $approfile['generator']['url'], 'gsid' => $owner['gsid'],
2210 'manually-approve' => in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])
2212 } catch (Exception $e) {
2213 // Default values for non existing targets
2215 'name' => $url, 'nick' => $url, 'url' => $url, 'network' => Protocol::PHANTOM,
2216 'photo' => DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO
2220 return self::rearrangeData($data);