3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Network;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
33 use Friendica\Model\Contact;
34 use Friendica\Model\GServer;
35 use Friendica\Model\Profile;
36 use Friendica\Model\User;
37 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
38 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
39 use Friendica\Protocol\ActivityNamespace;
40 use Friendica\Protocol\ActivityPub;
41 use Friendica\Protocol\Email;
42 use Friendica\Protocol\Feed;
43 use Friendica\Protocol\Salmon;
44 use Friendica\Util\Crypto;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Network;
47 use Friendica\Util\Strings;
48 use Friendica\Util\XML;
49 use GuzzleHttp\Psr7\Uri;
52 * This class contain functions for probing URL
56 const HOST_META = '/.well-known/host-meta';
57 const WEBFINGER = '/.well-known/webfinger?resource={uri}';
60 * @var string Base URL
62 private static $baseurl;
65 * @var boolean Whether a timeout has occured
67 private static $isTimeout;
70 * Checks if the provided network can be probed
72 * @param string $network
76 public static function isProbable(string $network): bool
78 return (in_array($network, array_merge(Protocol::FEDERATED, [Protocol::ZOT, Protocol::PHANTOM])));
82 * Remove stuff from an URI that doesn't belong there
84 * @param string $rawUri
85 * @return string Cleaned URI
87 public static function cleanURI(string $rawUri): string
89 // At first remove leading and trailing junk
90 $rawUri = trim($rawUri, "@#?: \t\n\r\0\x0B");
92 $rawUri = Network::convertToIdn($rawUri);
94 $uri = new Uri($rawUri);
95 if (!$uri->getScheme()) {
96 return $uri->__toString();
99 // Remove the URL fragment, since these shouldn't be part of any profile URL
100 $uri = $uri->withFragment('');
102 return $uri->__toString();
106 * Rearrange the array so that it always has the same order
108 * @param array $data Unordered data
109 * @return array Ordered data
111 private static function rearrangeData(array $data): array
113 $fields = ['name', 'given_name', 'family_name', 'nick', 'guid', 'url', 'addr', 'alias',
114 'photo', 'photo_medium', 'photo_small', 'header',
115 'account-type', 'community', 'keywords', 'location', 'about', 'xmpp', 'matrix',
116 'hide', 'batch', 'notify', 'poll', 'request', 'confirm', 'subscribe', 'poco',
117 'following', 'followers', 'inbox', 'outbox', 'sharedinbox',
118 'priority', 'network', 'pubkey', 'manually-approve', 'baseurl', 'gsid'];
120 $numeric_fields = ['gsid', 'hide', 'account-type', 'manually-approve'];
123 foreach ($fields as $field) {
124 if (isset($data[$field])) {
125 if (in_array($field, $numeric_fields)) {
126 $newdata[$field] = (int)$data[$field];
128 $newdata[$field] = trim($data[$field]);
130 } elseif (!in_array($field, $numeric_fields)) {
131 $newdata[$field] = '';
133 $newdata[$field] = null;
137 $newdata['networks'] = $data['networks'] ?? [];
138 foreach ([Protocol::DIASPORA, Protocol::OSTATUS] as $network) {
139 if (empty($newdata['networks'][$network])) {
140 unset($newdata['networks'][$network]);
144 // We don't use the "priority" field anymore and replace it with a dummy.
145 $newdata['priority'] = 0;
151 * Check if the hostname belongs to the own server
153 * @param string $host The hostname that is to be checked
154 * @return bool Does the testes hostname belongs to the own server?
156 private static function ownHost(string $host): bool
158 $own_host = DI::baseUrl()->getHostname();
160 $parts = parse_url($host);
162 if (!isset($parts['scheme'])) {
163 $parts = parse_url('http://' . $host);
166 if (!isset($parts['host'])) {
169 return $parts['host'] == $own_host;
173 * Probes for webfinger path via "host-meta"
175 * We have to check if the servers in the future still will offer this.
176 * It seems as if it was dropped from the standard.
178 * @param string $host The host part of an url
180 * @return array with template and type of the webfinger template for JSON or XML
181 * @throws HTTPException\InternalServerErrorException
183 private static function hostMeta(string $host): array
185 // Reset the static variable
188 // Handles the case when the hostname contains the scheme
189 if (!parse_url($host, PHP_URL_SCHEME)) {
190 $ssl_url = 'https://' . $host . self::HOST_META;
191 $url = 'http://' . $host . self::HOST_META;
193 $ssl_url = $host . self::HOST_META;
197 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
199 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
202 $curlResult = DI::httpClient()->get($ssl_url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
203 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
204 if ($curlResult->isSuccess()) {
205 $xml = $curlResult->getBody();
206 $xrd = XML::parseString($xml, true);
208 $host_url = 'https://' . $host;
212 } elseif ($curlResult->isTimeout()) {
213 Logger::info('Probing timeout', ['url' => $ssl_url]);
214 self::$isTimeout = true;
218 if (!is_object($xrd) && !empty($url)) {
219 $curlResult = DI::httpClient()->get($url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
220 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
221 if ($curlResult->isTimeout()) {
222 Logger::info('Probing timeout', ['url' => $url]);
223 self::$isTimeout = true;
225 } elseif ($connection_error && $ssl_connection_error) {
226 self::$isTimeout = true;
230 $xml = $curlResult->getBody();
231 $xrd = XML::parseString($xml, true);
232 $host_url = 'http://'.$host;
234 if (!is_object($xrd)) {
235 Logger::info('No xrd object found', ['host' => $host]);
239 $links = XML::elementToArray($xrd);
240 if (!isset($links['xrd']['link'])) {
241 Logger::info('No xrd data found', ['host' => $host]);
247 foreach ($links['xrd']['link'] as $value => $link) {
248 if (!empty($link['@attributes'])) {
249 $attributes = $link['@attributes'];
250 } elseif ($value == '@attributes') {
256 if (!empty($attributes['rel']) && $attributes['rel'] == 'lrdd' && !empty($attributes['template'])) {
257 $type = (empty($attributes['type']) ? '' : $attributes['type']);
259 $lrdd[$type] = $attributes['template'];
263 if (Network::isUrlBlocked($host_url)) {
264 Logger::info('Domain is blocked', ['url' => $host]);
268 self::$baseurl = $host_url;
270 Logger::info('Probing successful', ['host' => $host]);
276 * Check an URI for LRDD data
278 * @param string $uri Address that should be probed
279 * @return array uri data
280 * @throws HTTPException\InternalServerErrorException
282 public static function lrdd(string $uri): array
284 $data = self::getWebfingerArray($uri);
288 $webfinger = $data['webfinger'];
290 if (empty($webfinger['links'])) {
291 Logger::info('No webfinger links found', ['uri' => $uri]);
297 foreach ($webfinger['links'] as $link) {
298 $data[] = ['@attributes' => $link];
301 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
302 foreach ($webfinger['aliases'] as $alias) {
316 * Fetch information (protocol endpoints and user information) about a given uri
318 * @param string $uri Address that should be probed
319 * @param string $network Test for this specific network
320 * @param integer $uid User ID for the probe (only used for mails)
321 * @param boolean $cache Use cached values?
323 * @return array uri data
324 * @throws HTTPException\InternalServerErrorException
325 * @throws \ImagickException
327 public static function uri(string $uri, string $network = '', int $uid = -1): array
329 // Local profiles aren't probed via network
330 if (empty($network) && Contact::isLocal($uri)) {
331 $data = self::localProbe($uri);
338 $uid = DI::userSession()->getLocalUserId();
341 if (empty($network) || ($network == Protocol::ACTIVITYPUB)) {
342 $ap_profile = ActivityPub::probeProfile($uri);
347 self::$isTimeout = false;
349 if ($network != Protocol::ACTIVITYPUB) {
350 $data = self::detect($uri, $network, $uid, $ap_profile);
351 if (!is_array($data)) {
354 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
355 $networks = $data['networks'] ?? [];
356 unset($data['networks']);
357 $networks[$data['network']] = $data;
359 $data['networks'] = $networks;
360 } elseif (!empty($ap_profile)) {
361 $ap_profile['batch'] = '';
362 $data = array_merge($ap_profile, $data);
368 if (!isset($data['url'])) {
372 if (empty($data['photo'])) {
373 $data['photo'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
376 if (empty($data['name'])) {
377 if (!empty($data['nick'])) {
378 $data['name'] = $data['nick'];
381 if (empty($data['name'])) {
382 $data['name'] = $data['url'];
386 if (empty($data['nick'])) {
387 $data['nick'] = strtolower($data['name']);
389 if (strpos($data['nick'], ' ')) {
390 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
394 if (!empty($data['baseurl']) && empty($data['gsid'])) {
395 $data['gsid'] = GServer::getID($data['baseurl']);
398 if (empty($data['network'])) {
399 $data['network'] = Protocol::PHANTOM;
402 // Ensure that local connections always are DFRN
403 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
404 $data['network'] = Protocol::DFRN;
407 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
408 $data['hide'] = self::getHideStatus($data['url']);
411 return self::rearrangeData($data);
416 * Fetches the "hide" status from the profile
418 * @param string $url URL of the profile
419 * @return boolean "hide" status
421 private static function getHideStatus(string $url): bool
423 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::CONTENT_LENGTH => 1000000]);
424 if (!$curlResult->isSuccess()) {
428 // If it isn't a HTML file then exit
429 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
433 $body = $curlResult->getBody();
438 $doc = new DOMDocument();
439 @$doc->loadHTML($body);
441 $xpath = new DOMXPath($doc);
443 $list = $xpath->query('//meta[@name]');
444 foreach ($list as $node) {
446 if ($node->attributes->length) {
447 foreach ($node->attributes as $attribute) {
448 $meta_tag[$attribute->name] = $attribute->value;
452 if (empty($meta_tag['content'])) {
456 $content = strtolower(trim($meta_tag['content']));
458 switch (strtolower(trim($meta_tag['name']))) {
459 case 'dfrn-global-visibility':
460 if ($content == 'false') {
465 if (strpos($content, 'noindex') !== false) {
476 * Fetch the "subscribe" and add it to the result
478 * @param array $result Result array
479 * @param array $webfinger Webfinger data
481 * @return array result Altered/unaltered result array
483 private static function getSubscribeLink(array $result, array $webfinger): array
485 if (empty($webfinger['links'])) {
489 foreach ($webfinger['links'] as $link) {
490 if (!empty($link['template']) && ($link['rel'] === ActivityNamespace::OSTATUSSUB)) {
491 $result['subscribe'] = $link['template'];
499 * Get webfinger data from a given URI
501 * @param string $uri URI
503 * @return array Webfinger data
504 * @throws HTTPException\InternalServerErrorException
506 private static function getWebfingerArray(string $uri): array
508 $parts = parse_url($uri);
510 if (!empty($parts['scheme']) && !empty($parts['host'])) {
511 $host = $parts['host'];
512 if (!empty($parts['port'])) {
513 $host .= ':' . $parts['port'];
516 $baseurl = $parts['scheme'] . '://' . $host;
521 $path_parts = explode('/', trim($parts['path'] ?? '', '/'));
522 if (!empty($path_parts)) {
523 $nick = ltrim(end($path_parts), '@');
524 $addr = $nick . '@' . $host;
527 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
528 if (empty($webfinger)) {
529 $lrdd = self::hostMeta($host);
532 if (empty($webfinger) && empty($lrdd)) {
533 while (empty($lrdd) && empty($webfinger) && (sizeof($path_parts) > 1)) {
534 $host .= '/' . array_shift($path_parts);
535 $baseurl = $parts['scheme'] . '://' . $host;
538 $addr = $nick . '@' . $host;
541 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
542 if (empty($webfinger)) {
543 $lrdd = self::hostMeta($host);
547 if (empty($lrdd) && empty($webfinger)) {
551 } elseif (strstr($uri, '@')) {
552 // Remove "acct:" from the URI
553 $uri = str_replace('acct:', '', $uri);
555 $host = substr($uri, strpos($uri, '@') + 1);
556 $nick = substr($uri, 0, strpos($uri, '@'));
559 $webfinger = self::getWebfinger('https://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
560 if (self::$isTimeout) {
564 if (empty($webfinger)) {
565 $webfinger = self::getWebfinger('http://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
566 if (self::$isTimeout) {
570 $baseurl = 'https://' . $host;
573 if (empty($webfinger)) {
574 $lrdd = self::hostMeta($host);
575 if (self::$isTimeout) {
578 $baseurl = self::$baseurl;
580 $baseurl = 'http://' . $host;
583 Logger::info('URI was not detectable', ['uri' => $uri]);
587 if (empty($webfinger)) {
588 foreach ($lrdd as $type => $template) {
593 $webfinger = self::getWebfinger($template, $type, $uri, $addr);
597 if (empty($webfinger)) {
601 if ($webfinger['detected'] == $addr) {
602 $webfinger['nick'] = $nick;
603 $webfinger['addr'] = $addr;
606 $webfinger['baseurl'] = $baseurl;
612 * Perform network request for webfinger data
614 * @param string $template
615 * @param string $type
617 * @param string $addr
619 * @return array webfinger results
621 private static function getWebfinger(string $template, string $type, string $uri, string $addr): array
623 if (Network::isUrlBlocked($template)) {
624 Logger::info('Domain is blocked', ['url' => $template]);
628 // First try the address because this is the primary purpose of webfinger
631 $path = str_replace('{uri}', urlencode('acct:' . $addr), $template);
632 $webfinger = self::webfinger($path, $type);
633 if (self::$isTimeout) {
639 if (empty($webfinger) && $uri != $addr) {
641 $path = str_replace('{uri}', urlencode($uri), $template);
642 $webfinger = self::webfinger($path, $type);
643 if (self::$isTimeout) {
648 if (empty($webfinger)) {
652 return ['webfinger' => $webfinger, 'detected' => $detected];
656 * Fetch information (protocol endpoints and user information) about a given uri
658 * This function is only called by the "uri" function that adds caching and rearranging of data.
660 * @param string $uri Address that should be probed
661 * @param string $network Test for this specific network
662 * @param integer $uid User ID for the probe (only used for mails)
663 * @param array $ap_profile Previously probed AP profile
664 * @return array URI data
665 * @throws HTTPException\InternalServerErrorException
667 private static function detect(string $uri, string $network, int $uid, array $ap_profile): array
671 'network' => $network,
676 Hook::callAll('probe_detect', $hookData);
678 if (isset($hookData['result'])) {
679 return is_array($hookData['result']) ? $hookData['result'] : [];
682 $parts = parse_url($uri);
683 if (empty($parts['scheme']) && empty($parts['host']) && !strstr($parts['path'], '@')) {
684 Logger::info('URI was not detectable', ['uri' => $uri]);
688 // If the URI starts with "mailto:" then jump directly to the mail detection
689 if (strpos($uri, 'mailto:') !== false) {
690 $uri = str_replace('mailto:', '', $uri);
691 return self::mail($uri, $uid);
694 if ($network == Protocol::MAIL) {
695 return self::mail($uri, $uid);
698 Logger::info('Probing start', ['uri' => $uri]);
700 if (!empty($ap_profile['addr']) && ($ap_profile['addr'] != $uri)) {
701 $data = self::getWebfingerArray($ap_profile['addr']);
705 $data = self::getWebfingerArray($uri);
709 if (!empty($parts['scheme'])) {
710 return self::feed($uri);
711 } elseif (!empty($uid)) {
712 return self::mail($uri, $uid);
718 $webfinger = $data['webfinger'];
719 $nick = $data['nick'] ?? '';
720 $addr = $data['addr'] ?? '';
721 $baseurl = $data['baseurl'] ?? '';
725 if (in_array($network, ['', Protocol::DFRN])) {
726 $result = self::dfrn($webfinger);
728 if ((!$result && ($network == '')) || ($network == Protocol::DIASPORA)) {
729 $result = self::diaspora($webfinger);
731 $result['networks'][Protocol::DIASPORA] = self::diaspora($webfinger);
733 if ((!$result && ($network == '')) || ($network == Protocol::OSTATUS)) {
734 $result = self::ostatus($webfinger);
736 $result['networks'][Protocol::OSTATUS] = self::ostatus($webfinger);
738 if (in_array($network, ['', Protocol::ZOT])) {
739 $result = self::zot($webfinger, $result, $baseurl);
741 if ((!$result && ($network == '')) || ($network == Protocol::PUMPIO)) {
742 $result = self::pumpio($webfinger, $addr);
744 if (empty($result['network']) && empty($ap_profile['network']) || ($network == Protocol::FEED)) {
745 $result = self::feed($uri);
747 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
748 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
749 if ((empty($result['nick']) || (strstr($result['nick'], ' '))) && ($nick != '')) {
750 $result['nick'] = $nick;
753 if (empty($result['addr']) && ($addr != '')) {
754 $result['addr'] = $addr;
758 $result = self::getSubscribeLink($result, $webfinger);
760 if (empty($result['network'])) {
761 $result['network'] = Protocol::PHANTOM;
764 if (empty($result['baseurl']) && !empty($baseurl)) {
765 $result['baseurl'] = $baseurl;
768 if (empty($result['url'])) {
769 $result['url'] = $uri;
772 Logger::info('Probing done', ['uri' => $uri, 'network' => $result['network']]);
778 * Check for Zot contact
780 * @param array $webfinger Webfinger data
781 * @param array $data previously probed data
782 * @param string $baseUrl Base URL
784 * @return array Zot data
785 * @throws HTTPException\InternalServerErrorException
787 private static function zot(array $webfinger, array $data, string $baseurl): array
789 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
790 foreach ($webfinger['aliases'] as $alias) {
791 if (substr($alias, 0, 5) == 'acct:') {
792 $data['addr'] = substr($alias, 5);
797 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
798 $data['addr'] = substr($webfinger['subject'], 5);
802 foreach ($webfinger['links'] as $link) {
803 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
804 $zot_url = $link['href'];
808 if (empty($zot_url) && !empty($data['addr']) && !empty($baseurl)) {
809 $condition = ['nurl' => Strings::normaliseLink($baseurl), 'platform' => ['hubzilla']];
810 if (!DBA::exists('gserver', $condition)) {
813 $zot_url = $baseurl . '/.well-known/zot-info?address=' . $data['addr'];
816 if (empty($zot_url)) {
820 $data = self::pollZot($zot_url, $data);
822 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
823 foreach ($webfinger['aliases'] as $alias) {
824 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
825 $data['alias'] = $alias;
833 public static function pollZot(string $url, array $data): array
835 $curlResult = DI::httpClient()->get($url, HttpClientAccept::JSON);
836 if ($curlResult->isTimeout()) {
839 $content = $curlResult->getBody();
844 $json = json_decode($content, true);
845 if (!is_array($json)) {
849 if (empty($data['network'])) {
850 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
851 $data['network'] = Protocol::ZOT;
852 } elseif (!isset($json['protocols'])) {
853 $data['network'] = Protocol::ZOT;
857 if (!empty($json['guid']) && empty($data['guid'])) {
858 $data['guid'] = $json['guid'];
860 if (!empty($json['key']) && empty($data['pubkey'])) {
861 $data['pubkey'] = $json['key'];
863 if (!empty($json['name'])) {
864 $data['name'] = $json['name'];
866 if (!empty($json['photo'])) {
867 $data['photo'] = $json['photo'];
868 if (!empty($json['photo_updated'])) {
869 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
872 if (!empty($json['address'])) {
873 $data['addr'] = $json['address'];
875 if (!empty($json['url'])) {
876 $data['url'] = $json['url'];
878 if (!empty($json['connections_url'])) {
879 $data['poco'] = $json['connections_url'];
881 if (isset($json['searchable'])) {
882 $data['hide'] = !$json['searchable'];
884 if (!empty($json['public_forum'])) {
885 $data['community'] = $json['public_forum'];
886 $data['account-type'] = User::PAGE_FLAGS_COMMUNITY;
889 if (!empty($json['profile'])) {
890 $profile = $json['profile'];
891 if (!empty($profile['description'])) {
892 $data['about'] = $profile['description'];
894 if (!empty($profile['keywords'])) {
895 $keywords = implode(', ', $profile['keywords']);
896 if (!empty($keywords)) {
897 $data['keywords'] = $keywords;
902 if (!empty($profile['region'])) {
903 $loc['region'] = $profile['region'];
905 if (!empty($profile['country'])) {
906 $loc['country-name'] = $profile['country'];
908 $location = Profile::formatLocation($loc);
909 if (!empty($location)) {
910 $data['location'] = $location;
918 * Perform a webfinger request.
920 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
922 * @param string $url Address that should be probed
923 * @param string $type type
925 * @return array webfinger data
926 * @throws HTTPException\InternalServerErrorException
928 public static function webfinger(string $url, string $type): array
930 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
932 $curlResult = DI::httpClient()->get($url, $type, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
933 if ($curlResult->isTimeout()) {
934 self::$isTimeout = true;
937 $data = $curlResult->getBody();
939 $webfinger = json_decode($data, true);
940 if (!empty($webfinger)) {
941 if (!isset($webfinger['links'])) {
942 Logger::info('No json webfinger links', ['url' => $url]);
948 // If it is not JSON, maybe it is XML
949 $xrd = XML::parseString($data, true);
950 if (!is_object($xrd)) {
951 Logger::info('No webfinger data retrievable', ['url' => $url]);
955 $xrd_arr = XML::elementToArray($xrd);
956 if (!isset($xrd_arr['xrd']['link'])) {
957 Logger::info('No XML webfinger links', ['url' => $url]);
963 if (!empty($xrd_arr['xrd']['subject'])) {
964 $webfinger['subject'] = $xrd_arr['xrd']['subject'];
967 if (!empty($xrd_arr['xrd']['alias'])) {
968 $webfinger['aliases'] = $xrd_arr['xrd']['alias'];
971 $webfinger['links'] = [];
973 foreach ($xrd_arr['xrd']['link'] as $value => $data) {
974 if (!empty($data['@attributes'])) {
975 $attributes = $data['@attributes'];
976 } elseif ($value == '@attributes') {
982 $webfinger['links'][] = $attributes;
988 * Poll the Friendica specific noscrape page.
990 * "noscrape" is a faster alternative to fetch the data from the hcard.
991 * This functionality was originally created for the directory.
993 * @param string $noscrape_url Link to the noscrape page
994 * @param array $data The already fetched data
996 * @return array noscrape data
997 * @throws HTTPException\InternalServerErrorException
999 private static function pollNoscrape(string $noscrape_url, array $data): array
1001 $curlResult = DI::httpClient()->get($noscrape_url, HttpClientAccept::JSON);
1002 if ($curlResult->isTimeout()) {
1003 self::$isTimeout = true;
1006 $content = $curlResult->getBody();
1008 Logger::info('Empty body', ['url' => $noscrape_url]);
1012 $json = json_decode($content, true);
1013 if (!is_array($json)) {
1014 Logger::info('No json data', ['url' => $noscrape_url]);
1018 if (!empty($json['fn'])) {
1019 $data['name'] = $json['fn'];
1022 if (!empty($json['addr'])) {
1023 $data['addr'] = $json['addr'];
1026 if (!empty($json['nick'])) {
1027 $data['nick'] = $json['nick'];
1030 if (!empty($json['guid'])) {
1031 $data['guid'] = $json['guid'];
1034 if (!empty($json['comm'])) {
1035 $data['community'] = $json['comm'];
1038 if (!empty($json['tags'])) {
1039 $keywords = implode(', ', $json['tags']);
1040 if ($keywords != '') {
1041 $data['keywords'] = $keywords;
1045 $location = Profile::formatLocation($json);
1047 $data['location'] = $location;
1050 if (!empty($json['about'])) {
1051 $data['about'] = $json['about'];
1054 if (!empty($json['xmpp'])) {
1055 $data['xmpp'] = $json['xmpp'];
1058 if (!empty($json['matrix'])) {
1059 $data['matrix'] = $json['matrix'];
1062 if (!empty($json['key'])) {
1063 $data['pubkey'] = $json['key'];
1066 if (!empty($json['photo'])) {
1067 $data['photo'] = $json['photo'];
1070 if (!empty($json['dfrn-request'])) {
1071 $data['request'] = $json['dfrn-request'];
1074 if (!empty($json['dfrn-confirm'])) {
1075 $data['confirm'] = $json['dfrn-confirm'];
1078 if (!empty($json['dfrn-notify'])) {
1079 $data['notify'] = $json['dfrn-notify'];
1082 if (!empty($json['dfrn-poll'])) {
1083 $data['poll'] = $json['dfrn-poll'];
1086 if (isset($json['hide'])) {
1087 $data['hide'] = (bool)$json['hide'];
1089 $data['hide'] = false;
1096 * Check for valid DFRN data
1098 * @param array $data DFRN data
1100 * @return int Number of errors
1102 public static function validDfrn(array $data): int
1105 if (!isset($data['key'])) {
1108 if (!isset($data['dfrn-request'])) {
1111 if (!isset($data['dfrn-confirm'])) {
1114 if (!isset($data['dfrn-notify'])) {
1117 if (!isset($data['dfrn-poll'])) {
1124 * Fetch data from a DFRN profile page and via "noscrape"
1126 * @param string $profile_link Link to the profile page
1127 * @return array profile data
1128 * @throws HTTPException\InternalServerErrorException
1129 * @throws \ImagickException
1131 public static function profile(string $profile_link): array
1135 Logger::info('Check profile', ['link' => $profile_link]);
1137 // Fetch data via noscrape - this is faster
1138 $noscrape_url = str_replace(['/hcard/', '/profile/'], '/noscrape/', $profile_link);
1139 $data = self::pollNoscrape($noscrape_url, $data);
1141 if (!isset($data['notify'])
1142 || !isset($data['confirm'])
1143 || !isset($data['request'])
1144 || !isset($data['poll'])
1145 || !isset($data['name'])
1146 || !isset($data['photo'])
1148 $data = self::pollHcard($profile_link, $data, true);
1153 if (empty($data['addr']) || empty($data['nick'])) {
1154 $probe_data = self::uri($profile_link);
1155 $data['addr'] = ($data['addr'] ?? '') ?: $probe_data['addr'];
1156 $data['nick'] = ($data['nick'] ?? '') ?: $probe_data['nick'];
1159 $prof_data['addr'] = $data['addr'];
1160 $prof_data['nick'] = $data['nick'];
1161 $prof_data['dfrn-request'] = $data['request'] ?? null;
1162 $prof_data['dfrn-confirm'] = $data['confirm'] ?? null;
1163 $prof_data['dfrn-notify'] = $data['notify'] ?? null;
1164 $prof_data['dfrn-poll'] = $data['poll'] ?? null;
1165 $prof_data['photo'] = $data['photo'] ?? null;
1166 $prof_data['fn'] = $data['name'] ?? null;
1167 $prof_data['key'] = $data['pubkey'] ?? null;
1169 Logger::debug('Result', ['link' => $profile_link, 'data' => $prof_data]);
1175 * Check for DFRN contact
1177 * @param array $webfinger Webfinger data
1178 * @return array DFRN data
1179 * @throws HTTPException\InternalServerErrorException
1181 private static function dfrn(array $webfinger): array
1185 // The array is reversed to take into account the order of preference for same-rel links
1186 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1187 foreach (array_reverse($webfinger['links']) as $link) {
1188 if (($link['rel'] == ActivityNamespace::DFRN) && !empty($link['href'])) {
1189 $data['network'] = Protocol::DFRN;
1190 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1191 $data['poll'] = $link['href'];
1192 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1193 $data['url'] = $link['href'];
1194 } elseif (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1195 $hcard_url = $link['href'];
1196 } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1197 $data['poco'] = $link['href'];
1198 } elseif (($link['rel'] == 'http://webfinger.net/rel/avatar') && !empty($link['href'])) {
1199 $data['photo'] = $link['href'];
1200 } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1201 $data['baseurl'] = trim($link['href'], '/');
1202 } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1203 $data['guid'] = $link['href'];
1204 } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1205 $data['pubkey'] = base64_decode($link['href']);
1207 if (strstr($data['pubkey'], 'RSA ')) {
1208 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1213 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1214 foreach ($webfinger['aliases'] as $alias) {
1215 if (empty($data['url']) && !strstr($alias, '@')) {
1216 $data['url'] = $alias;
1217 } elseif (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
1218 $data['alias'] = $alias;
1219 } elseif (substr($alias, 0, 5) == 'acct:') {
1220 $data['addr'] = substr($alias, 5);
1225 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1226 $data['addr'] = substr($webfinger['subject'], 5);
1229 if (!isset($data['network']) || ($hcard_url == '')) {
1233 // Fetch data via noscrape - this is faster
1234 $noscrape_url = str_replace('/hcard/', '/noscrape/', $hcard_url);
1235 $data = self::pollNoscrape($noscrape_url, $data);
1237 if (isset($data['notify'])
1238 && isset($data['confirm'])
1239 && isset($data['request'])
1240 && isset($data['poll'])
1241 && isset($data['name'])
1242 && isset($data['photo'])
1247 $data = self::pollHcard($hcard_url, $data, true);
1253 * Poll the hcard page (Diaspora and Friendica specific)
1255 * @param string $hcard_url Link to the hcard page
1256 * @param array $data The already fetched data
1257 * @param boolean $dfrn Poll DFRN specific data
1258 * @return array hcard data
1259 * @throws HTTPException\InternalServerErrorException
1261 private static function pollHcard(string $hcard_url, array $data, bool $dfrn = false): array
1263 $curlResult = DI::httpClient()->get($hcard_url, HttpClientAccept::HTML);
1264 if ($curlResult->isTimeout()) {
1265 self::$isTimeout = true;
1268 $content = $curlResult->getBody();
1269 if (empty($content)) {
1273 $doc = new DOMDocument();
1274 if (!@$doc->loadHTML($content)) {
1278 $xpath = new DomXPath($doc);
1280 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1281 if (!is_object($vcards)) {
1285 if (!isset($data['baseurl'])) {
1286 $data['baseurl'] = '';
1289 if ($vcards->length > 0) {
1290 $vcard = $vcards->item(0);
1292 // We have to discard the guid from the hcard in favour of the guid from lrdd
1293 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1294 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1295 if (($search->length > 0) && empty($data['guid'])) {
1296 $data['guid'] = $search->item(0)->nodeValue;
1299 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1300 if ($search->length > 0) {
1301 $data['nick'] = $search->item(0)->nodeValue;
1304 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1305 if ($search->length > 0) {
1306 $data['name'] = $search->item(0)->nodeValue;
1309 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' given_name ')]", $vcard); // */
1310 if ($search->length > 0) {
1311 $data["given_name"] = $search->item(0)->nodeValue;
1314 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' family_name ')]", $vcard); // */
1315 if ($search->length > 0) {
1316 $data["family_name"] = $search->item(0)->nodeValue;
1319 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1320 if ($search->length > 0) {
1321 $data['hide'] = (strtolower($search->item(0)->nodeValue) != 'true');
1324 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1325 if ($search->length > 0) {
1326 $data['pubkey'] = $search->item(0)->nodeValue;
1327 if (strstr($data['pubkey'], 'RSA ')) {
1328 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1332 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1333 if ($search->length > 0) {
1334 $data['baseurl'] = trim($search->item(0)->nodeValue, '/');
1339 if (!empty($vcard)) {
1340 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1341 foreach ($photos as $photo) {
1343 foreach ($photo->attributes as $attribute) {
1344 $attr[$attribute->name] = trim($attribute->value);
1347 if (isset($attr['src']) && isset($attr['width'])) {
1348 $avatars[$attr['width']] = self::fixAvatar($attr['src'], $data['baseurl']);
1351 // We don't have a width. So we just take everything that we got.
1352 // This is a Hubzilla workaround which doesn't send a width.
1353 if (!$avatars && !empty($attr['src'])) {
1354 $avatars[] = self::fixAvatar($attr['src'], $data['baseurl']);
1361 $data['photo'] = array_pop($avatars);
1363 $data['photo_medium'] = array_pop($avatars);
1367 $data['photo_small'] = array_pop($avatars);
1372 // Poll DFRN specific data
1373 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1374 if ($search->length > 0) {
1375 foreach ($search as $link) {
1376 //$data['request'] = $search->item(0)->nodeValue;
1378 foreach ($link->attributes as $attribute) {
1379 $attr[$attribute->name] = trim($attribute->value);
1382 $data[substr($attr['rel'], 5)] = $attr['href'];
1386 // Older Friendica versions had used the "uid" field differently than newer versions
1387 if (!empty($data['nick']) && !empty($data['guid']) && ($data['nick'] == $data['guid'])) {
1388 unset($data['guid']);
1396 * Check for Diaspora contact
1398 * @param array $webfinger Webfinger data
1400 * @return array Diaspora data
1401 * @throws HTTPException\InternalServerErrorException
1403 private static function diaspora(array $webfinger): array
1408 // The array is reversed to take into account the order of preference for same-rel links
1409 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1410 foreach (array_reverse($webfinger['links']) as $link) {
1411 if (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1412 $hcard_url = $link['href'];
1413 } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1414 $data['baseurl'] = trim($link['href'], '/');
1415 } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1416 $data['guid'] = $link['href'];
1417 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1418 $data['url'] = $link['href'];
1419 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && empty($link['type']) && !empty($link['href'])) {
1420 $profile_url = $link['href'];
1421 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1422 $data['poll'] = $link['href'];
1423 } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1424 $data['poco'] = $link['href'];
1425 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1426 $data['notify'] = $link['href'];
1427 } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1428 $data['pubkey'] = base64_decode($link['href']);
1430 if (strstr($data['pubkey'], 'RSA ')) {
1431 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1436 if (empty($data['url']) && !empty($profile_url)) {
1437 $data['url'] = $profile_url;
1440 if (empty($data['url']) || empty($hcard_url)) {
1444 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1445 foreach ($webfinger['aliases'] as $alias) {
1446 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data['url']) && ! strstr($alias, '@')) {
1447 $data['alias'] = $alias;
1448 } elseif (substr($alias, 0, 5) == 'acct:') {
1449 $data['addr'] = substr($alias, 5);
1454 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1455 $data['addr'] = substr($webfinger['subject'], 5);
1458 // Fetch further information from the hcard
1459 $data = self::pollHcard($hcard_url, $data);
1465 if (!empty($data['url'])
1466 && !empty($data['guid'])
1467 && !empty($data['baseurl'])
1468 && !empty($data['pubkey'])
1469 && !empty($hcard_url)
1471 $data['network'] = Protocol::DIASPORA;
1472 $data['manually-approve'] = false;
1474 // The Diaspora handle must always be lowercase
1475 if (!empty($data['addr'])) {
1476 $data['addr'] = strtolower($data['addr']);
1479 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1480 $data['notify'] = $data['baseurl'] . '/receive/users/' . $data['guid'];
1481 $data['batch'] = $data['baseurl'] . '/receive/public';
1490 * Check for OStatus contact
1492 * @param array $webfinger Webfinger data
1493 * @param bool $short Short detection mode
1495 * @return array|bool OStatus data or "false" on error or "true" on short mode
1496 * @throws HTTPException\InternalServerErrorException
1498 private static function ostatus(array $webfinger, bool $short = false)
1502 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1503 foreach ($webfinger['aliases'] as $alias) {
1504 if (strstr($alias, '@') && !strstr(Strings::normaliseLink($alias), 'http://')) {
1505 $data['addr'] = str_replace('acct:', '', $alias);
1510 if (!empty($webfinger['subject']) && strstr($webfinger['subject'], '@')
1511 && !strstr(Strings::normaliseLink($webfinger['subject']), 'http://')
1513 $data['addr'] = str_replace('acct:', '', $webfinger['subject']);
1516 if (!empty($webfinger['links'])) {
1517 // The array is reversed to take into account the order of preference for same-rel links
1518 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1519 foreach (array_reverse($webfinger['links']) as $link) {
1520 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1521 && (($link['type'] ?? '') == 'text/html')
1522 && ($link['href'] != '')
1524 $data['url'] = $data['alias'] = $link['href'];
1525 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1526 $data['notify'] = $link['href'];
1527 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1528 $data['poll'] = $link['href'];
1529 } elseif (($link['rel'] == 'magic-public-key') && !empty($link['href'])) {
1530 $pubkey = $link['href'];
1532 if (substr($pubkey, 0, 5) === 'data:') {
1533 if (strstr($pubkey, ',')) {
1534 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1536 $pubkey = substr($pubkey, 5);
1538 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1539 $curlResult = DI::httpClient()->get($pubkey, HttpClientAccept::MAGIC_KEY);
1540 if ($curlResult->isTimeout()) {
1541 self::$isTimeout = true;
1542 return $short ? false : [];
1544 Logger::debug('Fetched public key', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $pubkey]);
1545 $pubkey = $curlResult->getBody();
1549 $data['pubkey'] = Salmon::magicKeyToPem($pubkey);
1550 } catch (\Throwable $e) {
1557 if (isset($data['notify']) && isset($data['pubkey'])
1558 && isset($data['poll'])
1559 && isset($data['url'])
1561 $data['network'] = Protocol::OSTATUS;
1562 $data['manually-approve'] = false;
1564 return $short ? false : [];
1571 // Fetch all additional data from the feed
1572 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::FEED_XML);
1573 if ($curlResult->isTimeout()) {
1574 self::$isTimeout = true;
1577 $feed = $curlResult->getBody();
1578 $feed_data = Feed::import($feed);
1583 if (!empty($feed_data['header']['author-name'])) {
1584 $data['name'] = $feed_data['header']['author-name'];
1586 if (!empty($feed_data['header']['author-nick'])) {
1587 $data['nick'] = $feed_data['header']['author-nick'];
1589 if (!empty($feed_data['header']['author-avatar'])) {
1590 $data['photo'] = self::fixAvatar($feed_data['header']['author-avatar'], $data['url']);
1592 if (!empty($feed_data['header']['author-id'])) {
1593 $data['alias'] = $feed_data['header']['author-id'];
1595 if (!empty($feed_data['header']['author-location'])) {
1596 $data['location'] = $feed_data['header']['author-location'];
1598 if (!empty($feed_data['header']['author-about'])) {
1599 $data['about'] = $feed_data['header']['author-about'];
1601 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1602 // So we take the value that we just fetched, although the other one worked as well
1603 if (!empty($feed_data['header']['author-link'])) {
1604 $data['url'] = $feed_data['header']['author-link'];
1607 if ($data['url'] == $data['alias']) {
1608 $data['alias'] = '';
1611 /// @todo Fetch location and "about" from the feed as well
1616 * Fetch data from a pump.io profile page
1618 * @param string $profile_link Link to the profile page
1620 * @return array Profile data
1622 private static function pumpioProfileData(string $profile_link): array
1624 $curlResult = DI::httpClient()->get($profile_link, HttpClientAccept::HTML);
1625 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
1629 $doc = new DOMDocument();
1630 if (!@$doc->loadHTML($curlResult->getBody())) {
1634 $xpath = new DomXPath($doc);
1637 $data['name'] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1639 if ($data['name'] == '') {
1640 // This is ugly - but pump.io doesn't seem to know a better way for it
1641 $data['name'] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1642 $pos = strpos($data['name'], chr(10));
1644 $data['name'] = trim(substr($data['name'], 0, $pos));
1648 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1650 if ($data['location'] == '') {
1651 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1654 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1656 if ($data['about'] == '') {
1657 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1660 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1662 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1665 foreach ($avatar->attributes as $attribute) {
1666 if ($attribute->name == 'src') {
1667 $data['photo'] = trim($attribute->value);
1676 * Check for pump.io contact
1678 * @param array $webfinger Webfinger data
1679 * @param string $addr
1681 * @return array pump.io data
1683 private static function pumpio(array $webfinger, string $addr): array
1686 // The array is reversed to take into account the order of preference for same-rel links
1687 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1688 foreach (array_reverse($webfinger['links']) as $link) {
1689 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1690 && (($link['type'] ?? '') == 'text/html')
1691 && ($link['href'] != '')
1693 $data['url'] = $link['href'];
1694 } elseif (($link['rel'] == 'activity-inbox') && ($link['href'] != '')) {
1695 $data['notify'] = $link['href'];
1696 } elseif (($link['rel'] == 'activity-outbox') && ($link['href'] != '')) {
1697 $data['poll'] = $link['href'];
1698 } elseif (($link['rel'] == 'dialback') && ($link['href'] != '')) {
1699 $data['dialback'] = $link['href'];
1702 if (isset($data['poll']) && isset($data['notify'])
1703 && isset($data['dialback'])
1704 && isset($data['url'])
1706 // by now we use these fields only for the network type detection
1707 // So we unset all data that isn't used at the moment
1708 unset($data['dialback']);
1710 $data['network'] = Protocol::PUMPIO;
1715 $profile_data = self::pumpioProfileData($data['url']);
1717 if (!$profile_data) {
1721 $data = array_merge($data, $profile_data);
1723 if (($addr != '') && ($data['name'] != '')) {
1724 $name = trim(str_replace($addr, '', $data['name']));
1726 $data['name'] = $name;
1734 * Checks HTML page for RSS feed link
1736 * @param string $url Page link
1737 * @param string $body Page body string
1739 * @return string|false Feed link or false if body was invalid HTML document
1741 public static function getFeedLink(string $url, string $body)
1747 $doc = new DOMDocument();
1748 if (!@$doc->loadHTML($body)) {
1752 $xpath = new DOMXPath($doc);
1754 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1755 $feedUrl = $feedUrl ?: $xpath->evaluate('string(/html/head/link[@type="application/atom+xml" and @rel="alternate"]/@href)');
1757 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1763 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1765 * Loosely based on RFC 1808
1767 * @see https://tools.ietf.org/html/rfc1808
1769 * @param string $href The potential relative href found in the HTML document
1770 * @param string $base The HTML document URL
1771 * @param DOMXPath $xpath The HTML document XPath
1773 * @return string Absolute URL
1775 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath): string
1777 if (filter_var($href, FILTER_VALIDATE_URL)) {
1781 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1783 $baseParts = parse_url($base);
1784 if (empty($baseParts['host'])) {
1788 // Naked domain case (scheme://basehost)
1789 $path = $baseParts['path'] ?? '/';
1791 // Remove the filename part of the path if it exists (/base/path/file)
1792 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1794 $hrefParts = parse_url($href);
1796 if (!empty($hrefParts['path'])) {
1797 // Root path case (/path) including relative scheme case (//host/path)
1798 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1799 $path = $hrefParts['path'];
1801 $path = $path . '/' . $hrefParts['path'];
1803 // Resolve arbitrary relative path
1804 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1805 $parts = array_filter(explode('/', $path), 'strlen');
1807 foreach ($parts as $part) {
1808 if ('.' == $part) continue;
1809 if ('..' == $part) {
1810 array_pop($absolutes);
1812 $absolutes[] = $part;
1816 $path = '/' . implode('/', $absolutes);
1820 // Relative scheme case (//host/path)
1821 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1822 $baseParts['path'] = $path;
1823 unset($baseParts['query']);
1824 unset($baseParts['fragment']);
1826 return Network::unparseURL($baseParts);
1830 * Check for feed contact
1832 * @param string $url Profile link
1833 * @param boolean $probe Do a probe if the page contains a feed link
1835 * @return array feed data
1836 * @throws HTTPException\InternalServerErrorException
1838 private static function feed(string $url, bool $probe = true): array
1840 $curlResult = DI::httpClient()->get($url, HttpClientAccept::FEED_XML);
1841 if ($curlResult->isTimeout()) {
1842 self::$isTimeout = true;
1845 $feed = $curlResult->getBody();
1846 $feed_data = Feed::import($feed);
1853 $feed_url = self::getFeedLink($url, $feed);
1859 return self::feed($feed_url, false);
1862 if (!empty($feed_data['header']['author-name'])) {
1863 $data['name'] = $feed_data['header']['author-name'];
1866 if (!empty($feed_data['header']['author-nick'])) {
1867 $data['nick'] = $feed_data['header']['author-nick'];
1870 if (!empty($feed_data['header']['author-avatar'])) {
1871 $data['photo'] = $feed_data['header']['author-avatar'];
1874 if (!empty($feed_data['header']['author-id'])) {
1875 $data['alias'] = $feed_data['header']['author-id'];
1878 $data['url'] = $url;
1879 $data['poll'] = $url;
1881 $data['network'] = Protocol::FEED;
1887 * Check for mail contact
1889 * @param string $uri Profile link
1890 * @param integer $uid User ID
1892 * @return array mail data
1893 * @throws \Exception
1895 private static function mail(string $uri, int $uid): array
1897 if (!Network::isEmailDomainValid($uri)) {
1905 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1907 $condition = ["`uid` = ? AND `server` != ''", $uid];
1908 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1909 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1911 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1915 $mailbox = Email::constructMailboxName($mailacct);
1917 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1918 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1923 $msgs = Email::poll($mbox, $uri);
1924 Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
1926 if (!count($msgs)) {
1930 $phost = substr($uri, strpos($uri, '@') + 1);
1934 'network' => Protocol::MAIL,
1935 'name' => substr($uri, 0, strpos($uri, '@')),
1936 'photo' => Network::lookupAvatarByEmail($uri),
1937 'url' => 'mailto:' . $uri,
1938 'notify' => 'smtp ' . Strings::getRandomHex(),
1939 'poll' => 'email ' . Strings::getRandomHex(),
1942 $data['nick'] = $data['name'];
1944 $x = Email::messageMeta($mbox, $msgs[0]);
1946 if (stristr($x[0]->from, $uri)) {
1947 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1948 } elseif (stristr($x[0]->to, $uri)) {
1949 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1953 foreach ($adr as $feadr) {
1954 if ((strcasecmp($feadr->mailbox, $data['name']) == 0)
1955 &&(strcasecmp($feadr->host, $phost) == 0)
1956 && (strlen($feadr->personal))
1958 $personal = imap_mime_header_decode($feadr->personal);
1960 foreach ($personal as $perspart) {
1961 if ($perspart->charset != 'default') {
1962 $data['name'] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1964 $data['name'] .= $perspart->text;
1971 if (!empty($mbox)) {
1979 * Mix two paths together to possibly fix missing parts
1981 * @param string $avatar Path to the avatar
1982 * @param string $base Another path that is hopefully complete
1984 * @return string fixed avatar path
1985 * @throws \Exception
1987 public static function fixAvatar(string $avatar, string $base): string
1989 $base_parts = parse_url($base);
1991 // Remove all parts that could create a problem
1992 unset($base_parts['path']);
1993 unset($base_parts['query']);
1994 unset($base_parts['fragment']);
1996 $avatar_parts = parse_url($avatar);
1999 $parts = array_merge($base_parts, $avatar_parts);
2001 // And put them together again
2002 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
2003 $host = isset($parts['host']) ? $parts['host'] : '';
2004 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
2005 $path = isset($parts['path']) ? $parts['path'] : '';
2006 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
2007 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
2009 $fixed = $scheme.$host.$port.$path.$query.$fragment;
2011 Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
2017 * Fetch the last date that the contact had posted something (publically)
2019 * @param array $data probing result
2021 * @return string last activity
2023 public static function getLastUpdate(array $data): string
2025 $uid = User::getIdForURL($data['url']);
2027 $contact = Contact::selectFirst(['url', 'last-item'], ['self' => true, 'uid' => $uid]);
2028 if (!empty($contact['last-item'])) {
2029 return $contact['last-item'];
2033 if ($lastUpdate = self::updateFromNoScrape($data)) {
2037 if (!empty($data['outbox'])) {
2038 return self::updateFromOutbox($data['outbox'], $data);
2039 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
2040 return self::updateFromOutbox($data['poll'], $data);
2041 } elseif (!empty($data['poll'])) {
2042 return self::updateFromFeed($data);
2049 * Fetch the last activity date from the "noscrape" endpoint
2051 * @param array $data Probing result
2053 * @return string last activity or true if update was successful or the server was unreachable
2055 private static function updateFromNoScrape(array $data): string
2057 if (empty($data['baseurl'])) {
2061 // Check the 'noscrape' endpoint when it is a Friendica server
2062 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
2063 Strings::normaliseLink($data['baseurl'])]);
2064 if (!DBA::isResult($gserver)) {
2068 $curlResult = DI::httpClient()->get($gserver['noscrape'] . '/' . $data['nick'], HttpClientAccept::JSON);
2070 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
2071 $noscrape = json_decode($curlResult->getBody(), true);
2072 if (!empty($noscrape) && !empty($noscrape['updated'])) {
2073 return DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2081 * Fetch the last activity date from an ActivityPub Outbox
2083 * @param string $feed
2084 * @param array $data Probing result
2086 * @return string last activity
2087 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2089 private static function updateFromOutbox(string $feed, array $data): string
2091 $outbox = ActivityPub::fetchContent($feed);
2092 if (empty($outbox)) {
2096 if (!empty($outbox['orderedItems'])) {
2097 $items = $outbox['orderedItems'];
2098 } elseif (!empty($outbox['first']['orderedItems'])) {
2099 $items = $outbox['first']['orderedItems'];
2100 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2101 return self::updateFromOutbox($outbox['first']['href'], $data);
2102 } elseif (!empty($outbox['first'])) {
2103 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2104 return self::updateFromOutbox($outbox['first'], $data);
2106 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2114 foreach ($items as $activity) {
2115 if (!empty($activity['published'])) {
2116 $published = DateTimeFormat::utc($activity['published']);
2117 } elseif (!empty($activity['object']['published'])) {
2118 $published = DateTimeFormat::utc($activity['object']['published']);
2123 if ($last_updated < $published) {
2124 $last_updated = $published;
2128 if (!empty($last_updated)) {
2129 return $last_updated;
2136 * Fetch the last activity date from an XML feed
2138 * @param array $data Probing result
2139 * @return string last activity
2141 private static function updateFromFeed(array $data): string
2143 // Search for the newest entry in the feed
2144 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::ATOM_XML);
2145 if (!$curlResult->isSuccess() || !$curlResult->getBody()) {
2149 $doc = new DOMDocument();
2150 @$doc->loadXML($curlResult->getBody());
2152 $xpath = new DOMXPath($doc);
2153 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2155 $entries = $xpath->query('/atom:feed/atom:entry');
2159 foreach ($entries as $entry) {
2160 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2161 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
2162 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2163 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2165 if (empty($published) || empty($updated)) {
2166 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2170 if ($last_updated < $published) {
2171 $last_updated = $published;
2174 if ($last_updated < $updated) {
2175 $last_updated = $updated;
2179 if (!empty($last_updated)) {
2180 return $last_updated;
2187 * Probe data from local profiles without network traffic
2189 * @param string $url
2191 * @return array probed data
2192 * @throws HTTPException\InternalServerErrorException
2193 * @throws HTTPException\NotFoundException
2195 private static function localProbe(string $url): array
2198 $uid = User::getIdForURL($url);
2200 throw new HTTPException\NotFoundException('User not found.');
2203 $owner = User::getOwnerDataById($uid);
2204 $approfile = ActivityPub\Transmitter::getProfile($uid);
2206 if (empty($owner['gsid'])) {
2207 $owner['gsid'] = GServer::getID($approfile['generator']['url']);
2211 'name' => $owner['name'], 'nick' => $owner['nick'], 'guid' => $approfile['diaspora:guid'] ?? '',
2212 'url' => $owner['url'], 'addr' => $owner['addr'], 'alias' => $owner['alias'],
2213 'photo' => User::getAvatarUrl($owner),
2214 'header' => $owner['header'] ? Contact::getHeaderUrlForId($owner['id'], $owner['updated']) : '',
2215 'account-type' => $owner['contact-type'], 'community' => ($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY),
2216 'keywords' => $owner['keywords'], 'location' => $owner['location'], 'about' => $owner['about'],
2217 'xmpp' => $owner['xmpp'], 'matrix' => $owner['matrix'],
2218 'hide' => !$owner['net-publish'], 'batch' => '', 'notify' => $owner['notify'],
2219 'poll' => $owner['poll'], 'request' => $owner['request'], 'confirm' => $owner['confirm'],
2220 'subscribe' => $approfile['generator']['url'] . '/contact/follow?url={uri}', 'poco' => $owner['poco'],
2221 'following' => $approfile['following'], 'followers' => $approfile['followers'],
2222 'inbox' => $approfile['inbox'], 'outbox' => $approfile['outbox'],
2223 'sharedinbox' => $approfile['endpoints']['sharedInbox'], 'network' => Protocol::DFRN,
2224 'pubkey' => $owner['upubkey'], 'baseurl' => $approfile['generator']['url'], 'gsid' => $owner['gsid'],
2225 'manually-approve' => in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])
2227 } catch (Exception $e) {
2228 // Default values for non existing targets
2230 'name' => $url, 'nick' => $url, 'url' => $url, 'network' => Protocol::PHANTOM,
2231 'photo' => DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO
2235 return self::rearrangeData($data);