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', 'nick', 'guid', 'url', 'addr', 'alias', 'photo', 'header',
114 'account-type', 'community', 'keywords', 'location', 'about', 'xmpp', 'matrix',
115 'hide', 'batch', 'notify', 'poll', 'request', 'confirm', 'subscribe', 'poco',
116 'following', 'followers', 'inbox', 'outbox', 'sharedinbox',
117 'priority', 'network', 'pubkey', 'manually-approve', 'baseurl', 'gsid'];
119 $numeric_fields = ['gsid', 'hide', 'account-type', 'manually-approve'];
122 foreach ($fields as $field) {
123 if (isset($data[$field])) {
124 if (in_array($field, $numeric_fields)) {
125 $newdata[$field] = (int)$data[$field];
127 $newdata[$field] = $data[$field];
129 } elseif (!in_array($field, $numeric_fields)) {
130 $newdata[$field] = '';
132 $newdata[$field] = null;
136 // We don't use the "priority" field anymore and replace it with a dummy.
137 $newdata['priority'] = 0;
143 * Check if the hostname belongs to the own server
145 * @param string $host The hostname that is to be checked
146 * @return bool Does the testes hostname belongs to the own server?
148 private static function ownHost(string $host): bool
150 $own_host = DI::baseUrl()->getHostname();
152 $parts = parse_url($host);
154 if (!isset($parts['scheme'])) {
155 $parts = parse_url('http://' . $host);
158 if (!isset($parts['host'])) {
161 return $parts['host'] == $own_host;
165 * Probes for webfinger path via "host-meta"
167 * We have to check if the servers in the future still will offer this.
168 * It seems as if it was dropped from the standard.
170 * @param string $host The host part of an url
172 * @return array with template and type of the webfinger template for JSON or XML
173 * @throws HTTPException\InternalServerErrorException
175 private static function hostMeta(string $host): array
177 // Reset the static variable
180 // Handles the case when the hostname contains the scheme
181 if (!parse_url($host, PHP_URL_SCHEME)) {
182 $ssl_url = 'https://' . $host . self::HOST_META;
183 $url = 'http://' . $host . self::HOST_META;
185 $ssl_url = $host . self::HOST_META;
189 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
191 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
194 $curlResult = DI::httpClient()->get($ssl_url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
195 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
196 if ($curlResult->isSuccess()) {
197 $xml = $curlResult->getBody();
198 $xrd = XML::parseString($xml, true);
200 $host_url = 'https://' . $host;
204 } elseif ($curlResult->isTimeout()) {
205 Logger::info('Probing timeout', ['url' => $ssl_url]);
206 self::$isTimeout = true;
210 if (!is_object($xrd) && !empty($url)) {
211 $curlResult = DI::httpClient()->get($url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
212 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
213 if ($curlResult->isTimeout()) {
214 Logger::info('Probing timeout', ['url' => $url]);
215 self::$isTimeout = true;
217 } elseif ($connection_error && $ssl_connection_error) {
218 self::$isTimeout = true;
222 $xml = $curlResult->getBody();
223 $xrd = XML::parseString($xml, true);
224 $host_url = 'http://'.$host;
226 if (!is_object($xrd)) {
227 Logger::info('No xrd object found', ['host' => $host]);
231 $links = XML::elementToArray($xrd);
232 if (!isset($links['xrd']['link'])) {
233 Logger::info('No xrd data found', ['host' => $host]);
239 foreach ($links['xrd']['link'] as $value => $link) {
240 if (!empty($link['@attributes'])) {
241 $attributes = $link['@attributes'];
242 } elseif ($value == '@attributes') {
248 if (!empty($attributes['rel']) && $attributes['rel'] == 'lrdd' && !empty($attributes['template'])) {
249 $type = (empty($attributes['type']) ? '' : $attributes['type']);
251 $lrdd[$type] = $attributes['template'];
255 if (Network::isUrlBlocked($host_url)) {
256 Logger::info('Domain is blocked', ['url' => $host]);
260 self::$baseurl = $host_url;
262 Logger::info('Probing successful', ['host' => $host]);
268 * Check an URI for LRDD data
270 * @param string $uri Address that should be probed
271 * @return array uri data
272 * @throws HTTPException\InternalServerErrorException
274 public static function lrdd(string $uri): array
276 $data = self::getWebfingerArray($uri);
280 $webfinger = $data['webfinger'];
282 if (empty($webfinger['links'])) {
283 Logger::info('No webfinger links found', ['uri' => $uri]);
289 foreach ($webfinger['links'] as $link) {
290 $data[] = ['@attributes' => $link];
293 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
294 foreach ($webfinger['aliases'] as $alias) {
308 * Fetch information (protocol endpoints and user information) about a given uri
310 * @param string $uri Address that should be probed
311 * @param string $network Test for this specific network
312 * @param integer $uid User ID for the probe (only used for mails)
313 * @param boolean $cache Use cached values?
315 * @return array uri data
316 * @throws HTTPException\InternalServerErrorException
317 * @throws \ImagickException
319 public static function uri(string $uri, string $network = '', int $uid = -1): array
321 // Local profiles aren't probed via network
322 if (empty($network) && Contact::isLocal($uri)) {
323 $data = self::localProbe($uri);
330 $uid = DI::userSession()->getLocalUserId();
333 if (empty($network) || ($network == Protocol::ACTIVITYPUB)) {
334 $ap_profile = ActivityPub::probeProfile($uri);
339 self::$isTimeout = false;
341 if ($network != Protocol::ACTIVITYPUB) {
342 $data = self::detect($uri, $network, $uid, $ap_profile);
343 if (!is_array($data)) {
346 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
348 } elseif (!empty($ap_profile)) {
349 $ap_profile['batch'] = '';
350 $data = array_merge($ap_profile, $data);
356 if (!isset($data['url'])) {
360 if (empty($data['photo'])) {
361 $data['photo'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
364 if (empty($data['name'])) {
365 if (!empty($data['nick'])) {
366 $data['name'] = $data['nick'];
369 if (empty($data['name'])) {
370 $data['name'] = $data['url'];
374 if (empty($data['nick'])) {
375 $data['nick'] = strtolower($data['name']);
377 if (strpos($data['nick'], ' ')) {
378 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
382 if (!empty($data['baseurl']) && empty($data['gsid'])) {
383 $data['gsid'] = GServer::getID($data['baseurl']);
386 if (empty($data['network'])) {
387 $data['network'] = Protocol::PHANTOM;
390 // Ensure that local connections always are DFRN
391 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
392 $data['network'] = Protocol::DFRN;
395 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
396 $data['hide'] = self::getHideStatus($data['url']);
399 return self::rearrangeData($data);
404 * Fetches the "hide" status from the profile
406 * @param string $url URL of the profile
407 * @return boolean "hide" status
409 private static function getHideStatus(string $url): bool
411 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::CONTENT_LENGTH => 1000000]);
412 if (!$curlResult->isSuccess()) {
416 // If it isn't a HTML file then exit
417 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
421 $body = $curlResult->getBody();
426 $doc = new DOMDocument();
427 @$doc->loadHTML($body);
429 $xpath = new DOMXPath($doc);
431 $list = $xpath->query('//meta[@name]');
432 foreach ($list as $node) {
434 if ($node->attributes->length) {
435 foreach ($node->attributes as $attribute) {
436 $meta_tag[$attribute->name] = $attribute->value;
440 if (empty($meta_tag['content'])) {
444 $content = strtolower(trim($meta_tag['content']));
446 switch (strtolower(trim($meta_tag['name']))) {
447 case 'dfrn-global-visibility':
448 if ($content == 'false') {
453 if (strpos($content, 'noindex') !== false) {
464 * Fetch the "subscribe" and add it to the result
466 * @param array $result Result array
467 * @param array $webfinger Webfinger data
469 * @return array result Altered/unaltered result array
471 private static function getSubscribeLink(array $result, array $webfinger): array
473 if (empty($webfinger['links'])) {
477 foreach ($webfinger['links'] as $link) {
478 if (!empty($link['template']) && ($link['rel'] === ActivityNamespace::OSTATUSSUB)) {
479 $result['subscribe'] = $link['template'];
487 * Get webfinger data from a given URI
489 * @param string $uri URI
491 * @return array Webfinger data
492 * @throws HTTPException\InternalServerErrorException
494 private static function getWebfingerArray(string $uri): array
496 $parts = parse_url($uri);
498 if (!empty($parts['scheme']) && !empty($parts['host'])) {
499 $host = $parts['host'];
500 if (!empty($parts['port'])) {
501 $host .= ':' . $parts['port'];
504 $baseurl = $parts['scheme'] . '://' . $host;
509 $path_parts = explode('/', trim($parts['path'] ?? '', '/'));
510 if (!empty($path_parts)) {
511 $nick = ltrim(end($path_parts), '@');
512 $addr = $nick . '@' . $host;
515 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
516 if (empty($webfinger)) {
517 $lrdd = self::hostMeta($host);
520 if (empty($webfinger) && empty($lrdd)) {
521 while (empty($lrdd) && empty($webfinger) && (sizeof($path_parts) > 1)) {
522 $host .= '/' . array_shift($path_parts);
523 $baseurl = $parts['scheme'] . '://' . $host;
526 $addr = $nick . '@' . $host;
529 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
530 if (empty($webfinger)) {
531 $lrdd = self::hostMeta($host);
535 if (empty($lrdd) && empty($webfinger)) {
539 } elseif (strstr($uri, '@')) {
540 // Remove "acct:" from the URI
541 $uri = str_replace('acct:', '', $uri);
543 $host = substr($uri, strpos($uri, '@') + 1);
544 $nick = substr($uri, 0, strpos($uri, '@'));
547 $webfinger = self::getWebfinger('https://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
548 if (self::$isTimeout) {
552 if (empty($webfinger)) {
553 $webfinger = self::getWebfinger('http://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
554 if (self::$isTimeout) {
558 $baseurl = 'https://' . $host;
561 if (empty($webfinger)) {
562 $lrdd = self::hostMeta($host);
563 if (self::$isTimeout) {
566 $baseurl = self::$baseurl;
568 $baseurl = 'http://' . $host;
571 Logger::info('URI was not detectable', ['uri' => $uri]);
575 if (empty($webfinger)) {
576 foreach ($lrdd as $type => $template) {
581 $webfinger = self::getWebfinger($template, $type, $uri, $addr);
585 if (empty($webfinger)) {
589 if ($webfinger['detected'] == $addr) {
590 $webfinger['nick'] = $nick;
591 $webfinger['addr'] = $addr;
594 $webfinger['baseurl'] = $baseurl;
600 * Perform network request for webfinger data
602 * @param string $template
603 * @param string $type
605 * @param string $addr
607 * @return array webfinger results
609 private static function getWebfinger(string $template, string $type, string $uri, string $addr): array
611 if (Network::isUrlBlocked($template)) {
612 Logger::info('Domain is blocked', ['url' => $template]);
616 // First try the address because this is the primary purpose of webfinger
619 $path = str_replace('{uri}', urlencode('acct:' . $addr), $template);
620 $webfinger = self::webfinger($path, $type);
621 if (self::$isTimeout) {
627 if (empty($webfinger) && $uri != $addr) {
629 $path = str_replace('{uri}', urlencode($uri), $template);
630 $webfinger = self::webfinger($path, $type);
631 if (self::$isTimeout) {
636 if (empty($webfinger)) {
640 return ['webfinger' => $webfinger, 'detected' => $detected];
644 * Fetch information (protocol endpoints and user information) about a given uri
646 * This function is only called by the "uri" function that adds caching and rearranging of data.
648 * @param string $uri Address that should be probed
649 * @param string $network Test for this specific network
650 * @param integer $uid User ID for the probe (only used for mails)
651 * @param array $ap_profile Previously probed AP profile
652 * @return array URI data
653 * @throws HTTPException\InternalServerErrorException
655 private static function detect(string $uri, string $network, int $uid, array $ap_profile): array
659 'network' => $network,
664 Hook::callAll('probe_detect', $hookData);
666 if (isset($hookData['result'])) {
667 return is_array($hookData['result']) ? $hookData['result'] : [];
670 $parts = parse_url($uri);
671 if (empty($parts['scheme']) && empty($parts['host']) && !strstr($parts['path'], '@')) {
672 Logger::info('URI was not detectable', ['uri' => $uri]);
676 // If the URI starts with "mailto:" then jump directly to the mail detection
677 if (strpos($uri, 'mailto:') !== false) {
678 $uri = str_replace('mailto:', '', $uri);
679 return self::mail($uri, $uid);
682 if ($network == Protocol::MAIL) {
683 return self::mail($uri, $uid);
686 Logger::info('Probing start', ['uri' => $uri]);
688 if (!empty($ap_profile['addr']) && ($ap_profile['addr'] != $uri)) {
689 $data = self::getWebfingerArray($ap_profile['addr']);
693 $data = self::getWebfingerArray($uri);
697 if (!empty($parts['scheme'])) {
698 return self::feed($uri);
699 } elseif (!empty($uid)) {
700 return self::mail($uri, $uid);
706 $webfinger = $data['webfinger'];
707 $nick = $data['nick'] ?? '';
708 $addr = $data['addr'] ?? '';
709 $baseurl = $data['baseurl'] ?? '';
713 if (in_array($network, ['', Protocol::DFRN])) {
714 $result = self::dfrn($webfinger);
716 if ((!$result && ($network == '')) || ($network == Protocol::DIASPORA)) {
717 $result = self::diaspora($webfinger);
719 if ((!$result && ($network == '')) || ($network == Protocol::OSTATUS)) {
720 $result = self::ostatus($webfinger);
722 if (in_array($network, ['', Protocol::ZOT])) {
723 $result = self::zot($webfinger, $result, $baseurl);
725 if ((!$result && ($network == '')) || ($network == Protocol::PUMPIO)) {
726 $result = self::pumpio($webfinger, $addr);
728 if (empty($result['network']) && empty($ap_profile['network']) || ($network == Protocol::FEED)) {
729 $result = self::feed($uri);
731 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
732 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
733 if ((empty($result['nick']) || (strstr($result['nick'], ' '))) && ($nick != '')) {
734 $result['nick'] = $nick;
737 if (empty($result['addr']) && ($addr != '')) {
738 $result['addr'] = $addr;
742 $result = self::getSubscribeLink($result, $webfinger);
744 if (empty($result['network'])) {
745 $result['network'] = Protocol::PHANTOM;
748 if (empty($result['baseurl']) && !empty($baseurl)) {
749 $result['baseurl'] = $baseurl;
752 if (empty($result['url'])) {
753 $result['url'] = $uri;
756 Logger::info('Probing done', ['uri' => $uri, 'network' => $result['network']]);
762 * Check for Zot contact
764 * @param array $webfinger Webfinger data
765 * @param array $data previously probed data
766 * @param string $baseUrl Base URL
768 * @return array Zot data
769 * @throws HTTPException\InternalServerErrorException
771 private static function zot(array $webfinger, array $data, string $baseurl): array
773 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
774 foreach ($webfinger['aliases'] as $alias) {
775 if (substr($alias, 0, 5) == 'acct:') {
776 $data['addr'] = substr($alias, 5);
781 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
782 $data['addr'] = substr($webfinger['subject'], 5);
786 foreach ($webfinger['links'] as $link) {
787 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
788 $zot_url = $link['href'];
792 if (empty($zot_url) && !empty($data['addr']) && !empty($baseurl)) {
793 $condition = ['nurl' => Strings::normaliseLink($baseurl), 'platform' => ['hubzilla']];
794 if (!DBA::exists('gserver', $condition)) {
797 $zot_url = $baseurl . '/.well-known/zot-info?address=' . $data['addr'];
800 if (empty($zot_url)) {
804 $data = self::pollZot($zot_url, $data);
806 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
807 foreach ($webfinger['aliases'] as $alias) {
808 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
809 $data['alias'] = $alias;
817 public static function pollZot(string $url, array $data): array
819 $curlResult = DI::httpClient()->get($url, HttpClientAccept::JSON);
820 if ($curlResult->isTimeout()) {
823 $content = $curlResult->getBody();
828 $json = json_decode($content, true);
829 if (!is_array($json)) {
833 if (empty($data['network'])) {
834 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
835 $data['network'] = Protocol::ZOT;
836 } elseif (!isset($json['protocols'])) {
837 $data['network'] = Protocol::ZOT;
841 if (!empty($json['guid']) && empty($data['guid'])) {
842 $data['guid'] = $json['guid'];
844 if (!empty($json['key']) && empty($data['pubkey'])) {
845 $data['pubkey'] = $json['key'];
847 if (!empty($json['name'])) {
848 $data['name'] = $json['name'];
850 if (!empty($json['photo'])) {
851 $data['photo'] = $json['photo'];
852 if (!empty($json['photo_updated'])) {
853 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
856 if (!empty($json['address'])) {
857 $data['addr'] = $json['address'];
859 if (!empty($json['url'])) {
860 $data['url'] = $json['url'];
862 if (!empty($json['connections_url'])) {
863 $data['poco'] = $json['connections_url'];
865 if (isset($json['searchable'])) {
866 $data['hide'] = !$json['searchable'];
868 if (!empty($json['public_forum'])) {
869 $data['community'] = $json['public_forum'];
870 $data['account-type'] = User::PAGE_FLAGS_COMMUNITY;
873 if (!empty($json['profile'])) {
874 $profile = $json['profile'];
875 if (!empty($profile['description'])) {
876 $data['about'] = $profile['description'];
878 if (!empty($profile['keywords'])) {
879 $keywords = implode(', ', $profile['keywords']);
880 if (!empty($keywords)) {
881 $data['keywords'] = $keywords;
886 if (!empty($profile['region'])) {
887 $loc['region'] = $profile['region'];
889 if (!empty($profile['country'])) {
890 $loc['country-name'] = $profile['country'];
892 $location = Profile::formatLocation($loc);
893 if (!empty($location)) {
894 $data['location'] = $location;
902 * Perform a webfinger request.
904 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
906 * @param string $url Address that should be probed
907 * @param string $type type
909 * @return array webfinger data
910 * @throws HTTPException\InternalServerErrorException
912 public static function webfinger(string $url, string $type): array
914 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
916 $curlResult = DI::httpClient()->get($url, $type, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
917 if ($curlResult->isTimeout()) {
918 self::$isTimeout = true;
921 $data = $curlResult->getBody();
923 $webfinger = json_decode($data, true);
924 if (!empty($webfinger)) {
925 if (!isset($webfinger['links'])) {
926 Logger::info('No json webfinger links', ['url' => $url]);
932 // If it is not JSON, maybe it is XML
933 $xrd = XML::parseString($data, true);
934 if (!is_object($xrd)) {
935 Logger::info('No webfinger data retrievable', ['url' => $url]);
939 $xrd_arr = XML::elementToArray($xrd);
940 if (!isset($xrd_arr['xrd']['link'])) {
941 Logger::info('No XML webfinger links', ['url' => $url]);
947 if (!empty($xrd_arr['xrd']['subject'])) {
948 $webfinger['subject'] = $xrd_arr['xrd']['subject'];
951 if (!empty($xrd_arr['xrd']['alias'])) {
952 $webfinger['aliases'] = $xrd_arr['xrd']['alias'];
955 $webfinger['links'] = [];
957 foreach ($xrd_arr['xrd']['link'] as $value => $data) {
958 if (!empty($data['@attributes'])) {
959 $attributes = $data['@attributes'];
960 } elseif ($value == '@attributes') {
966 $webfinger['links'][] = $attributes;
972 * Poll the Friendica specific noscrape page.
974 * "noscrape" is a faster alternative to fetch the data from the hcard.
975 * This functionality was originally created for the directory.
977 * @param string $noscrape_url Link to the noscrape page
978 * @param array $data The already fetched data
980 * @return array noscrape data
981 * @throws HTTPException\InternalServerErrorException
983 private static function pollNoscrape(string $noscrape_url, array $data): array
985 $curlResult = DI::httpClient()->get($noscrape_url, HttpClientAccept::JSON);
986 if ($curlResult->isTimeout()) {
987 self::$isTimeout = true;
990 $content = $curlResult->getBody();
992 Logger::info('Empty body', ['url' => $noscrape_url]);
996 $json = json_decode($content, true);
997 if (!is_array($json)) {
998 Logger::info('No json data', ['url' => $noscrape_url]);
1002 if (!empty($json['fn'])) {
1003 $data['name'] = $json['fn'];
1006 if (!empty($json['addr'])) {
1007 $data['addr'] = $json['addr'];
1010 if (!empty($json['nick'])) {
1011 $data['nick'] = $json['nick'];
1014 if (!empty($json['guid'])) {
1015 $data['guid'] = $json['guid'];
1018 if (!empty($json['comm'])) {
1019 $data['community'] = $json['comm'];
1022 if (!empty($json['tags'])) {
1023 $keywords = implode(', ', $json['tags']);
1024 if ($keywords != '') {
1025 $data['keywords'] = $keywords;
1029 $location = Profile::formatLocation($json);
1031 $data['location'] = $location;
1034 if (!empty($json['about'])) {
1035 $data['about'] = $json['about'];
1038 if (!empty($json['xmpp'])) {
1039 $data['xmpp'] = $json['xmpp'];
1042 if (!empty($json['matrix'])) {
1043 $data['matrix'] = $json['matrix'];
1046 if (!empty($json['key'])) {
1047 $data['pubkey'] = $json['key'];
1050 if (!empty($json['photo'])) {
1051 $data['photo'] = $json['photo'];
1054 if (!empty($json['dfrn-request'])) {
1055 $data['request'] = $json['dfrn-request'];
1058 if (!empty($json['dfrn-confirm'])) {
1059 $data['confirm'] = $json['dfrn-confirm'];
1062 if (!empty($json['dfrn-notify'])) {
1063 $data['notify'] = $json['dfrn-notify'];
1066 if (!empty($json['dfrn-poll'])) {
1067 $data['poll'] = $json['dfrn-poll'];
1070 if (isset($json['hide'])) {
1071 $data['hide'] = (bool)$json['hide'];
1073 $data['hide'] = false;
1080 * Check for valid DFRN data
1082 * @param array $data DFRN data
1084 * @return int Number of errors
1086 public static function validDfrn(array $data): int
1089 if (!isset($data['key'])) {
1092 if (!isset($data['dfrn-request'])) {
1095 if (!isset($data['dfrn-confirm'])) {
1098 if (!isset($data['dfrn-notify'])) {
1101 if (!isset($data['dfrn-poll'])) {
1108 * Fetch data from a DFRN profile page and via "noscrape"
1110 * @param string $profile_link Link to the profile page
1111 * @return array profile data
1112 * @throws HTTPException\InternalServerErrorException
1113 * @throws \ImagickException
1115 public static function profile(string $profile_link): array
1119 Logger::info('Check profile', ['link' => $profile_link]);
1121 // Fetch data via noscrape - this is faster
1122 $noscrape_url = str_replace(['/hcard/', '/profile/'], '/noscrape/', $profile_link);
1123 $data = self::pollNoscrape($noscrape_url, $data);
1125 if (!isset($data['notify'])
1126 || !isset($data['confirm'])
1127 || !isset($data['request'])
1128 || !isset($data['poll'])
1129 || !isset($data['name'])
1130 || !isset($data['photo'])
1132 $data = self::pollHcard($profile_link, $data, true);
1137 if (empty($data['addr']) || empty($data['nick'])) {
1138 $probe_data = self::uri($profile_link);
1139 $data['addr'] = ($data['addr'] ?? '') ?: $probe_data['addr'];
1140 $data['nick'] = ($data['nick'] ?? '') ?: $probe_data['nick'];
1143 $prof_data['addr'] = $data['addr'];
1144 $prof_data['nick'] = $data['nick'];
1145 $prof_data['dfrn-request'] = $data['request'] ?? null;
1146 $prof_data['dfrn-confirm'] = $data['confirm'] ?? null;
1147 $prof_data['dfrn-notify'] = $data['notify'] ?? null;
1148 $prof_data['dfrn-poll'] = $data['poll'] ?? null;
1149 $prof_data['photo'] = $data['photo'] ?? null;
1150 $prof_data['fn'] = $data['name'] ?? null;
1151 $prof_data['key'] = $data['pubkey'] ?? null;
1153 Logger::debug('Result', ['link' => $profile_link, 'data' => $prof_data]);
1159 * Check for DFRN contact
1161 * @param array $webfinger Webfinger data
1162 * @return array DFRN data
1163 * @throws HTTPException\InternalServerErrorException
1165 private static function dfrn(array $webfinger): array
1169 // The array is reversed to take into account the order of preference for same-rel links
1170 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1171 foreach (array_reverse($webfinger['links']) as $link) {
1172 if (($link['rel'] == ActivityNamespace::DFRN) && !empty($link['href'])) {
1173 $data['network'] = Protocol::DFRN;
1174 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1175 $data['poll'] = $link['href'];
1176 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1177 $data['url'] = $link['href'];
1178 } elseif (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1179 $hcard_url = $link['href'];
1180 } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1181 $data['poco'] = $link['href'];
1182 } elseif (($link['rel'] == 'http://webfinger.net/rel/avatar') && !empty($link['href'])) {
1183 $data['photo'] = $link['href'];
1184 } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1185 $data['baseurl'] = trim($link['href'], '/');
1186 } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1187 $data['guid'] = $link['href'];
1188 } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1189 $data['pubkey'] = base64_decode($link['href']);
1191 if (strstr($data['pubkey'], 'RSA ')) {
1192 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1197 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1198 foreach ($webfinger['aliases'] as $alias) {
1199 if (empty($data['url']) && !strstr($alias, '@')) {
1200 $data['url'] = $alias;
1201 } elseif (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
1202 $data['alias'] = $alias;
1203 } elseif (substr($alias, 0, 5) == 'acct:') {
1204 $data['addr'] = substr($alias, 5);
1209 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1210 $data['addr'] = substr($webfinger['subject'], 5);
1213 if (!isset($data['network']) || ($hcard_url == '')) {
1217 // Fetch data via noscrape - this is faster
1218 $noscrape_url = str_replace('/hcard/', '/noscrape/', $hcard_url);
1219 $data = self::pollNoscrape($noscrape_url, $data);
1221 if (isset($data['notify'])
1222 && isset($data['confirm'])
1223 && isset($data['request'])
1224 && isset($data['poll'])
1225 && isset($data['name'])
1226 && isset($data['photo'])
1231 $data = self::pollHcard($hcard_url, $data, true);
1237 * Poll the hcard page (Diaspora and Friendica specific)
1239 * @param string $hcard_url Link to the hcard page
1240 * @param array $data The already fetched data
1241 * @param boolean $dfrn Poll DFRN specific data
1242 * @return array hcard data
1243 * @throws HTTPException\InternalServerErrorException
1245 private static function pollHcard(string $hcard_url, array $data, bool $dfrn = false): array
1247 $curlResult = DI::httpClient()->get($hcard_url, HttpClientAccept::HTML);
1248 if ($curlResult->isTimeout()) {
1249 self::$isTimeout = true;
1252 $content = $curlResult->getBody();
1253 if (empty($content)) {
1257 $doc = new DOMDocument();
1258 if (!@$doc->loadHTML($content)) {
1262 $xpath = new DomXPath($doc);
1264 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1265 if (!is_object($vcards)) {
1269 if (!isset($data['baseurl'])) {
1270 $data['baseurl'] = '';
1273 if ($vcards->length > 0) {
1274 $vcard = $vcards->item(0);
1276 // We have to discard the guid from the hcard in favour of the guid from lrdd
1277 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1278 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1279 if (($search->length > 0) && empty($data['guid'])) {
1280 $data['guid'] = $search->item(0)->nodeValue;
1283 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1284 if ($search->length > 0) {
1285 $data['nick'] = $search->item(0)->nodeValue;
1288 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1289 if ($search->length > 0) {
1290 $data['name'] = $search->item(0)->nodeValue;
1293 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1294 if ($search->length > 0) {
1295 $data['searchable'] = $search->item(0)->nodeValue;
1298 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1299 if ($search->length > 0) {
1300 $data['pubkey'] = $search->item(0)->nodeValue;
1301 if (strstr($data['pubkey'], 'RSA ')) {
1302 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1306 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1307 if ($search->length > 0) {
1308 $data['baseurl'] = trim($search->item(0)->nodeValue, '/');
1313 if (!empty($vcard)) {
1314 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1315 foreach ($photos as $photo) {
1317 foreach ($photo->attributes as $attribute) {
1318 $attr[$attribute->name] = trim($attribute->value);
1321 if (isset($attr['src']) && isset($attr['width'])) {
1322 $avatar[$attr['width']] = $attr['src'];
1325 // We don't have a width. So we just take everything that we got.
1326 // This is a Hubzilla workaround which doesn't send a width.
1327 if ((sizeof($avatar) == 0) && !empty($attr['src'])) {
1328 $avatar[] = $attr['src'];
1333 if (sizeof($avatar)) {
1335 $data['photo'] = self::fixAvatar(array_pop($avatar), $data['baseurl']);
1339 // Poll DFRN specific data
1340 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1341 if ($search->length > 0) {
1342 foreach ($search as $link) {
1343 //$data['request'] = $search->item(0)->nodeValue;
1345 foreach ($link->attributes as $attribute) {
1346 $attr[$attribute->name] = trim($attribute->value);
1349 $data[substr($attr['rel'], 5)] = $attr['href'];
1353 // Older Friendica versions had used the "uid" field differently than newer versions
1354 if (!empty($data['nick']) && !empty($data['guid']) && ($data['nick'] == $data['guid'])) {
1355 unset($data['guid']);
1364 * Check for Diaspora contact
1366 * @param array $webfinger Webfinger data
1368 * @return array Diaspora data
1369 * @throws HTTPException\InternalServerErrorException
1371 private static function diaspora(array $webfinger): array
1376 // The array is reversed to take into account the order of preference for same-rel links
1377 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1378 foreach (array_reverse($webfinger['links']) as $link) {
1379 if (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1380 $hcard_url = $link['href'];
1381 } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1382 $data['baseurl'] = trim($link['href'], '/');
1383 } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1384 $data['guid'] = $link['href'];
1385 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1386 $data['url'] = $link['href'];
1387 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && empty($link['type']) && !empty($link['href'])) {
1388 $profile_url = $link['href'];
1389 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1390 $data['poll'] = $link['href'];
1391 } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1392 $data['poco'] = $link['href'];
1393 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1394 $data['notify'] = $link['href'];
1395 } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1396 $data['pubkey'] = base64_decode($link['href']);
1398 if (strstr($data['pubkey'], 'RSA ')) {
1399 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1404 if (empty($data['url']) && !empty($profile_url)) {
1405 $data['url'] = $profile_url;
1408 if (empty($data['url']) || empty($hcard_url)) {
1412 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1413 foreach ($webfinger['aliases'] as $alias) {
1414 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data['url']) && ! strstr($alias, '@')) {
1415 $data['alias'] = $alias;
1416 } elseif (substr($alias, 0, 5) == 'acct:') {
1417 $data['addr'] = substr($alias, 5);
1422 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1423 $data['addr'] = substr($webfinger['subject'], 5);
1426 // Fetch further information from the hcard
1427 $data = self::pollHcard($hcard_url, $data);
1433 if (!empty($data['url'])
1434 && !empty($data['guid'])
1435 && !empty($data['baseurl'])
1436 && !empty($data['pubkey'])
1437 && !empty($hcard_url)
1439 $data['network'] = Protocol::DIASPORA;
1440 $data['manually-approve'] = false;
1442 // The Diaspora handle must always be lowercase
1443 if (!empty($data['addr'])) {
1444 $data['addr'] = strtolower($data['addr']);
1447 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1448 $data['notify'] = $data['baseurl'] . '/receive/users/' . $data['guid'];
1449 $data['batch'] = $data['baseurl'] . '/receive/public';
1458 * Check for OStatus contact
1460 * @param array $webfinger Webfinger data
1461 * @param bool $short Short detection mode
1463 * @return array|bool OStatus data or "false" on error or "true" on short mode
1464 * @throws HTTPException\InternalServerErrorException
1466 private static function ostatus(array $webfinger, bool $short = false)
1470 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1471 foreach ($webfinger['aliases'] as $alias) {
1472 if (strstr($alias, '@') && !strstr(Strings::normaliseLink($alias), 'http://')) {
1473 $data['addr'] = str_replace('acct:', '', $alias);
1478 if (!empty($webfinger['subject']) && strstr($webfinger['subject'], '@')
1479 && !strstr(Strings::normaliseLink($webfinger['subject']), 'http://')
1481 $data['addr'] = str_replace('acct:', '', $webfinger['subject']);
1484 if (!empty($webfinger['links'])) {
1485 // The array is reversed to take into account the order of preference for same-rel links
1486 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1487 foreach (array_reverse($webfinger['links']) as $link) {
1488 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1489 && (($link['type'] ?? '') == 'text/html')
1490 && ($link['href'] != '')
1492 $data['url'] = $data['alias'] = $link['href'];
1493 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1494 $data['notify'] = $link['href'];
1495 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1496 $data['poll'] = $link['href'];
1497 } elseif (($link['rel'] == 'magic-public-key') && !empty($link['href'])) {
1498 $pubkey = $link['href'];
1500 if (substr($pubkey, 0, 5) === 'data:') {
1501 if (strstr($pubkey, ',')) {
1502 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1504 $pubkey = substr($pubkey, 5);
1506 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1507 $curlResult = DI::httpClient()->get($pubkey, HttpClientAccept::MAGIC_KEY);
1508 if ($curlResult->isTimeout()) {
1509 self::$isTimeout = true;
1510 return $short ? false : [];
1512 Logger::debug('Fetched public key', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $pubkey]);
1513 $pubkey = $curlResult->getBody();
1517 $data['pubkey'] = Salmon::magicKeyToPem($pubkey);
1518 } catch (\Throwable $e) {
1525 if (isset($data['notify']) && isset($data['pubkey'])
1526 && isset($data['poll'])
1527 && isset($data['url'])
1529 $data['network'] = Protocol::OSTATUS;
1530 $data['manually-approve'] = false;
1532 return $short ? false : [];
1539 // Fetch all additional data from the feed
1540 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::FEED_XML);
1541 if ($curlResult->isTimeout()) {
1542 self::$isTimeout = true;
1545 $feed = $curlResult->getBody();
1546 $feed_data = Feed::import($feed);
1551 if (!empty($feed_data['header']['author-name'])) {
1552 $data['name'] = $feed_data['header']['author-name'];
1554 if (!empty($feed_data['header']['author-nick'])) {
1555 $data['nick'] = $feed_data['header']['author-nick'];
1557 if (!empty($feed_data['header']['author-avatar'])) {
1558 $data['photo'] = self::fixAvatar($feed_data['header']['author-avatar'], $data['url']);
1560 if (!empty($feed_data['header']['author-id'])) {
1561 $data['alias'] = $feed_data['header']['author-id'];
1563 if (!empty($feed_data['header']['author-location'])) {
1564 $data['location'] = $feed_data['header']['author-location'];
1566 if (!empty($feed_data['header']['author-about'])) {
1567 $data['about'] = $feed_data['header']['author-about'];
1569 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1570 // So we take the value that we just fetched, although the other one worked as well
1571 if (!empty($feed_data['header']['author-link'])) {
1572 $data['url'] = $feed_data['header']['author-link'];
1575 if ($data['url'] == $data['alias']) {
1576 $data['alias'] = '';
1579 /// @todo Fetch location and "about" from the feed as well
1584 * Fetch data from a pump.io profile page
1586 * @param string $profile_link Link to the profile page
1588 * @return array Profile data
1590 private static function pumpioProfileData(string $profile_link): array
1592 $curlResult = DI::httpClient()->get($profile_link, HttpClientAccept::HTML);
1593 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
1597 $doc = new DOMDocument();
1598 if (!@$doc->loadHTML($curlResult->getBody())) {
1602 $xpath = new DomXPath($doc);
1605 $data['name'] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1607 if ($data['name'] == '') {
1608 // This is ugly - but pump.io doesn't seem to know a better way for it
1609 $data['name'] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1610 $pos = strpos($data['name'], chr(10));
1612 $data['name'] = trim(substr($data['name'], 0, $pos));
1616 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1618 if ($data['location'] == '') {
1619 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1622 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1624 if ($data['about'] == '') {
1625 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1628 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1630 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1633 foreach ($avatar->attributes as $attribute) {
1634 if ($attribute->name == 'src') {
1635 $data['photo'] = trim($attribute->value);
1644 * Check for pump.io contact
1646 * @param array $webfinger Webfinger data
1647 * @param string $addr
1649 * @return array pump.io data
1651 private static function pumpio(array $webfinger, string $addr): array
1654 // The array is reversed to take into account the order of preference for same-rel links
1655 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1656 foreach (array_reverse($webfinger['links']) as $link) {
1657 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1658 && (($link['type'] ?? '') == 'text/html')
1659 && ($link['href'] != '')
1661 $data['url'] = $link['href'];
1662 } elseif (($link['rel'] == 'activity-inbox') && ($link['href'] != '')) {
1663 $data['notify'] = $link['href'];
1664 } elseif (($link['rel'] == 'activity-outbox') && ($link['href'] != '')) {
1665 $data['poll'] = $link['href'];
1666 } elseif (($link['rel'] == 'dialback') && ($link['href'] != '')) {
1667 $data['dialback'] = $link['href'];
1670 if (isset($data['poll']) && isset($data['notify'])
1671 && isset($data['dialback'])
1672 && isset($data['url'])
1674 // by now we use these fields only for the network type detection
1675 // So we unset all data that isn't used at the moment
1676 unset($data['dialback']);
1678 $data['network'] = Protocol::PUMPIO;
1683 $profile_data = self::pumpioProfileData($data['url']);
1685 if (!$profile_data) {
1689 $data = array_merge($data, $profile_data);
1691 if (($addr != '') && ($data['name'] != '')) {
1692 $name = trim(str_replace($addr, '', $data['name']));
1694 $data['name'] = $name;
1702 * Checks HTML page for RSS feed link
1704 * @param string $url Page link
1705 * @param string $body Page body string
1707 * @return string|false Feed link or false if body was invalid HTML document
1709 public static function getFeedLink(string $url, string $body)
1715 $doc = new DOMDocument();
1716 if (!@$doc->loadHTML($body)) {
1720 $xpath = new DOMXPath($doc);
1722 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1723 $feedUrl = $feedUrl ?: $xpath->evaluate('string(/html/head/link[@type="application/atom+xml" and @rel="alternate"]/@href)');
1725 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1731 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1733 * Loosely based on RFC 1808
1735 * @see https://tools.ietf.org/html/rfc1808
1737 * @param string $href The potential relative href found in the HTML document
1738 * @param string $base The HTML document URL
1739 * @param DOMXPath $xpath The HTML document XPath
1741 * @return string Absolute URL
1743 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath): string
1745 if (filter_var($href, FILTER_VALIDATE_URL)) {
1749 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1751 $baseParts = parse_url($base);
1752 if (empty($baseParts['host'])) {
1756 // Naked domain case (scheme://basehost)
1757 $path = $baseParts['path'] ?? '/';
1759 // Remove the filename part of the path if it exists (/base/path/file)
1760 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1762 $hrefParts = parse_url($href);
1764 if (!empty($hrefParts['path'])) {
1765 // Root path case (/path) including relative scheme case (//host/path)
1766 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1767 $path = $hrefParts['path'];
1769 $path = $path . '/' . $hrefParts['path'];
1771 // Resolve arbitrary relative path
1772 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1773 $parts = array_filter(explode('/', $path), 'strlen');
1775 foreach ($parts as $part) {
1776 if ('.' == $part) continue;
1777 if ('..' == $part) {
1778 array_pop($absolutes);
1780 $absolutes[] = $part;
1784 $path = '/' . implode('/', $absolutes);
1788 // Relative scheme case (//host/path)
1789 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1790 $baseParts['path'] = $path;
1791 unset($baseParts['query']);
1792 unset($baseParts['fragment']);
1794 return Network::unparseURL($baseParts);
1798 * Check for feed contact
1800 * @param string $url Profile link
1801 * @param boolean $probe Do a probe if the page contains a feed link
1803 * @return array feed data
1804 * @throws HTTPException\InternalServerErrorException
1806 private static function feed(string $url, bool $probe = true): array
1808 $curlResult = DI::httpClient()->get($url, HttpClientAccept::FEED_XML);
1809 if ($curlResult->isTimeout()) {
1810 self::$isTimeout = true;
1813 $feed = $curlResult->getBody();
1814 $feed_data = Feed::import($feed);
1821 $feed_url = self::getFeedLink($url, $feed);
1827 return self::feed($feed_url, false);
1830 if (!empty($feed_data['header']['author-name'])) {
1831 $data['name'] = $feed_data['header']['author-name'];
1834 if (!empty($feed_data['header']['author-nick'])) {
1835 $data['nick'] = $feed_data['header']['author-nick'];
1838 if (!empty($feed_data['header']['author-avatar'])) {
1839 $data['photo'] = $feed_data['header']['author-avatar'];
1842 if (!empty($feed_data['header']['author-id'])) {
1843 $data['alias'] = $feed_data['header']['author-id'];
1846 $data['url'] = $url;
1847 $data['poll'] = $url;
1849 $data['network'] = Protocol::FEED;
1855 * Check for mail contact
1857 * @param string $uri Profile link
1858 * @param integer $uid User ID
1860 * @return array mail data
1861 * @throws \Exception
1863 private static function mail(string $uri, int $uid): array
1865 if (!Network::isEmailDomainValid($uri)) {
1873 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1875 $condition = ["`uid` = ? AND `server` != ''", $uid];
1876 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1877 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1879 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1883 $mailbox = Email::constructMailboxName($mailacct);
1885 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1886 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1891 $msgs = Email::poll($mbox, $uri);
1892 Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
1894 if (!count($msgs)) {
1898 $phost = substr($uri, strpos($uri, '@') + 1);
1902 'network' => Protocol::MAIL,
1903 'name' => substr($uri, 0, strpos($uri, '@')),
1904 'photo' => Network::lookupAvatarByEmail($uri),
1905 'url' => 'mailto:' . $uri,
1906 'notify' => 'smtp ' . Strings::getRandomHex(),
1907 'poll' => 'email ' . Strings::getRandomHex(),
1910 $data['nick'] = $data['name'];
1912 $x = Email::messageMeta($mbox, $msgs[0]);
1914 if (stristr($x[0]->from, $uri)) {
1915 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1916 } elseif (stristr($x[0]->to, $uri)) {
1917 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1921 foreach ($adr as $feadr) {
1922 if ((strcasecmp($feadr->mailbox, $data['name']) == 0)
1923 &&(strcasecmp($feadr->host, $phost) == 0)
1924 && (strlen($feadr->personal))
1926 $personal = imap_mime_header_decode($feadr->personal);
1928 foreach ($personal as $perspart) {
1929 if ($perspart->charset != 'default') {
1930 $data['name'] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1932 $data['name'] .= $perspart->text;
1939 if (!empty($mbox)) {
1947 * Mix two paths together to possibly fix missing parts
1949 * @param string $avatar Path to the avatar
1950 * @param string $base Another path that is hopefully complete
1952 * @return string fixed avatar path
1953 * @throws \Exception
1955 public static function fixAvatar(string $avatar, string $base): string
1957 $base_parts = parse_url($base);
1959 // Remove all parts that could create a problem
1960 unset($base_parts['path']);
1961 unset($base_parts['query']);
1962 unset($base_parts['fragment']);
1964 $avatar_parts = parse_url($avatar);
1967 $parts = array_merge($base_parts, $avatar_parts);
1969 // And put them together again
1970 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1971 $host = isset($parts['host']) ? $parts['host'] : '';
1972 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1973 $path = isset($parts['path']) ? $parts['path'] : '';
1974 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1975 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1977 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1979 Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
1985 * Fetch the last date that the contact had posted something (publically)
1987 * @param array $data probing result
1989 * @return string last activity
1991 public static function getLastUpdate(array $data): string
1993 $uid = User::getIdForURL($data['url']);
1995 $contact = Contact::selectFirst(['url', 'last-item'], ['self' => true, 'uid' => $uid]);
1996 if (!empty($contact['last-item'])) {
1997 return $contact['last-item'];
2001 if ($lastUpdate = self::updateFromNoScrape($data)) {
2005 if (!empty($data['outbox'])) {
2006 return self::updateFromOutbox($data['outbox'], $data);
2007 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
2008 return self::updateFromOutbox($data['poll'], $data);
2009 } elseif (!empty($data['poll'])) {
2010 return self::updateFromFeed($data);
2017 * Fetch the last activity date from the "noscrape" endpoint
2019 * @param array $data Probing result
2021 * @return string last activity or true if update was successful or the server was unreachable
2023 private static function updateFromNoScrape(array $data): string
2025 if (empty($data['baseurl'])) {
2029 // Check the 'noscrape' endpoint when it is a Friendica server
2030 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
2031 Strings::normaliseLink($data['baseurl'])]);
2032 if (!DBA::isResult($gserver)) {
2036 $curlResult = DI::httpClient()->get($gserver['noscrape'] . '/' . $data['nick'], HttpClientAccept::JSON);
2038 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
2039 $noscrape = json_decode($curlResult->getBody(), true);
2040 if (!empty($noscrape) && !empty($noscrape['updated'])) {
2041 return DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2049 * Fetch the last activity date from an ActivityPub Outbox
2051 * @param string $feed
2052 * @param array $data Probing result
2054 * @return string last activity
2055 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2057 private static function updateFromOutbox(string $feed, array $data): string
2059 $outbox = ActivityPub::fetchContent($feed);
2060 if (empty($outbox)) {
2064 if (!empty($outbox['orderedItems'])) {
2065 $items = $outbox['orderedItems'];
2066 } elseif (!empty($outbox['first']['orderedItems'])) {
2067 $items = $outbox['first']['orderedItems'];
2068 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2069 return self::updateFromOutbox($outbox['first']['href'], $data);
2070 } elseif (!empty($outbox['first'])) {
2071 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2072 return self::updateFromOutbox($outbox['first'], $data);
2074 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2082 foreach ($items as $activity) {
2083 if (!empty($activity['published'])) {
2084 $published = DateTimeFormat::utc($activity['published']);
2085 } elseif (!empty($activity['object']['published'])) {
2086 $published = DateTimeFormat::utc($activity['object']['published']);
2091 if ($last_updated < $published) {
2092 $last_updated = $published;
2096 if (!empty($last_updated)) {
2097 return $last_updated;
2104 * Fetch the last activity date from an XML feed
2106 * @param array $data Probing result
2107 * @return string last activity
2109 private static function updateFromFeed(array $data): string
2111 // Search for the newest entry in the feed
2112 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::ATOM_XML);
2113 if (!$curlResult->isSuccess() || !$curlResult->getBody()) {
2117 $doc = new DOMDocument();
2118 @$doc->loadXML($curlResult->getBody());
2120 $xpath = new DOMXPath($doc);
2121 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2123 $entries = $xpath->query('/atom:feed/atom:entry');
2127 foreach ($entries as $entry) {
2128 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2129 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
2130 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2131 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2133 if (empty($published) || empty($updated)) {
2134 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2138 if ($last_updated < $published) {
2139 $last_updated = $published;
2142 if ($last_updated < $updated) {
2143 $last_updated = $updated;
2147 if (!empty($last_updated)) {
2148 return $last_updated;
2155 * Probe data from local profiles without network traffic
2157 * @param string $url
2159 * @return array probed data
2160 * @throws HTTPException\InternalServerErrorException
2161 * @throws HTTPException\NotFoundException
2163 private static function localProbe(string $url): array
2166 $uid = User::getIdForURL($url);
2168 throw new HTTPException\NotFoundException('User not found.');
2171 $owner = User::getOwnerDataById($uid);
2172 $approfile = ActivityPub\Transmitter::getProfile($uid);
2174 if (empty($owner['gsid'])) {
2175 $owner['gsid'] = GServer::getID($approfile['generator']['url']);
2179 'name' => $owner['name'], 'nick' => $owner['nick'], 'guid' => $approfile['diaspora:guid'] ?? '',
2180 'url' => $owner['url'], 'addr' => $owner['addr'], 'alias' => $owner['alias'],
2181 'photo' => User::getAvatarUrl($owner),
2182 'header' => $owner['header'] ? Contact::getHeaderUrlForId($owner['id'], $owner['updated']) : '',
2183 'account-type' => $owner['contact-type'], 'community' => ($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY),
2184 'keywords' => $owner['keywords'], 'location' => $owner['location'], 'about' => $owner['about'],
2185 'xmpp' => $owner['xmpp'], 'matrix' => $owner['matrix'],
2186 'hide' => !$owner['net-publish'], 'batch' => '', 'notify' => $owner['notify'],
2187 'poll' => $owner['poll'], 'request' => $owner['request'], 'confirm' => $owner['confirm'],
2188 'subscribe' => $approfile['generator']['url'] . '/contact/follow?url={uri}', 'poco' => $owner['poco'],
2189 'following' => $approfile['following'], 'followers' => $approfile['followers'],
2190 'inbox' => $approfile['inbox'], 'outbox' => $approfile['outbox'],
2191 'sharedinbox' => $approfile['endpoints']['sharedInbox'], 'network' => Protocol::DFRN,
2192 'pubkey' => $owner['upubkey'], 'baseurl' => $approfile['generator']['url'], 'gsid' => $owner['gsid'],
2193 'manually-approve' => in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])
2195 } catch (Exception $e) {
2196 // Default values for non existing targets
2198 'name' => $url, 'nick' => $url, 'url' => $url, 'network' => Protocol::PHANTOM,
2199 'photo' => DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO
2203 return self::rearrangeData($data);