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\Session;
31 use Friendica\Core\System;
32 use Friendica\Database\DBA;
34 use Friendica\Model\Contact;
35 use Friendica\Model\GServer;
36 use Friendica\Model\Profile;
37 use Friendica\Model\User;
38 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
39 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
40 use Friendica\Protocol\ActivityNamespace;
41 use Friendica\Protocol\ActivityPub;
42 use Friendica\Protocol\Email;
43 use Friendica\Protocol\Feed;
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 WEBFINGER = '/.well-known/webfinger?resource={uri}';
58 private static $baseurl;
59 private static $istimeout;
62 * Checks if the provided network can be probed
64 * @param string $network
67 public static function isProbable(string $network): bool
69 return (in_array($network, array_merge(Protocol::FEDERATED, [Protocol::ZOT, Protocol::PHANTOM])));
73 * Remove stuff from an URI that doesn't belong there
75 * @param string $rawUri
76 * @return string Cleaned URI
78 public static function cleanURI(string $rawUri): string
80 // At first remove leading and trailing junk
81 $rawUri = trim($rawUri, "@#?: \t\n\r\0\x0B");
83 $rawUri = Network::convertToIdn($rawUri);
85 $uri = new Uri($rawUri);
86 if (!$uri->getScheme()) {
87 return $uri->__toString();
90 // Remove the URL fragment, since these shouldn't be part of any profile URL
91 $uri = $uri->withFragment('');
93 return $uri->__toString();
97 * Rearrange the array so that it always has the same order
99 * @param array $data Unordered data
100 * @return array Ordered data
102 private static function rearrangeData(array $data): array
104 $fields = ['name', 'nick', 'guid', 'url', 'addr', 'alias', 'photo', 'header',
105 'account-type', 'community', 'keywords', 'location', 'about', 'xmpp', 'matrix',
106 'hide', 'batch', 'notify', 'poll', 'request', 'confirm', 'subscribe', 'poco',
107 'following', 'followers', 'inbox', 'outbox', 'sharedinbox',
108 'priority', 'network', 'pubkey', 'manually-approve', 'baseurl', 'gsid'];
110 $numeric_fields = ['gsid', 'hide', 'account-type', 'manually-approve'];
113 foreach ($fields as $field) {
114 if (isset($data[$field])) {
115 if (in_array($field, $numeric_fields)) {
116 $newdata[$field] = (int)$data[$field];
118 $newdata[$field] = $data[$field];
120 } elseif (!in_array($field, $numeric_fields)) {
121 $newdata[$field] = '';
123 $newdata[$field] = null;
127 // We don't use the "priority" field anymore and replace it with a dummy.
128 $newdata['priority'] = 0;
134 * Check if the hostname belongs to the own server
136 * @param string $host The hostname that is to be checked
137 * @return bool Does the testes hostname belongs to the own server?
139 private static function ownHost(string $host): bool
141 $own_host = DI::baseUrl()->getHostname();
143 $parts = parse_url($host);
145 if (!isset($parts['scheme'])) {
146 $parts = parse_url('http://'.$host);
149 if (!isset($parts['host'])) {
152 return $parts['host'] == $own_host;
156 * Probes for webfinger path via "host-meta"
158 * We have to check if the servers in the future still will offer this.
159 * It seems as if it was dropped from the standard.
161 * @param string $host The host part of an url
162 * @return array with template and type of the webfinger template for JSON or XML
163 * @throws HTTPException\InternalServerErrorException
165 private static function hostMeta(string $host): array
167 // Reset the static variable
170 // Handles the case when the hostname contains the scheme
171 if (!parse_url($host, PHP_URL_SCHEME)) {
172 $ssl_url = 'https://' . $host . '/.well-known/host-meta';
173 $url = 'http://' . $host . '/.well-known/host-meta';
175 $ssl_url = $host . '/.well-known/host-meta';
179 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
181 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
184 $curlResult = DI::httpClient()->get($ssl_url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
185 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
186 if ($curlResult->isSuccess()) {
187 $xml = $curlResult->getBody();
188 $xrd = XML::parseString($xml, true);
190 $host_url = 'https://' . $host;
194 } elseif ($curlResult->isTimeout()) {
195 Logger::info('Probing timeout', ['url' => $ssl_url]);
196 self::$istimeout = true;
200 if (!is_object($xrd) && !empty($url)) {
201 $curlResult = DI::httpClient()->get($url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
202 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
203 if ($curlResult->isTimeout()) {
204 Logger::info('Probing timeout', ['url' => $url]);
205 self::$istimeout = true;
207 } elseif ($connection_error && $ssl_connection_error) {
208 self::$istimeout = true;
212 $xml = $curlResult->getBody();
213 $xrd = XML::parseString($xml, true);
214 $host_url = 'http://'.$host;
216 if (!is_object($xrd)) {
217 Logger::info('No xrd object found', ['host' => $host]);
221 $links = XML::elementToArray($xrd);
222 if (!isset($links['xrd']['link'])) {
223 Logger::info('No xrd data found', ['host' => $host]);
229 foreach ($links['xrd']['link'] as $value => $link) {
230 if (!empty($link['@attributes'])) {
231 $attributes = $link['@attributes'];
232 } elseif ($value == '@attributes') {
238 if (!empty($attributes['rel']) && $attributes['rel'] == 'lrdd' && !empty($attributes['template'])) {
239 $type = (empty($attributes['type']) ? '' : $attributes['type']);
241 $lrdd[$type] = $attributes['template'];
245 if (Network::isUrlBlocked($host_url)) {
246 Logger::info('Domain is blocked', ['url' => $host]);
250 self::$baseurl = $host_url;
252 Logger::info('Probing successful', ['host' => $host]);
258 * Check an URI for LRDD data
260 * @param string $uri Address that should be probed
261 * @return array uri data
262 * @throws HTTPException\InternalServerErrorException
264 public static function lrdd(string $uri): array
266 $data = self::getWebfingerArray($uri);
270 $webfinger = $data['webfinger'];
272 if (empty($webfinger['links'])) {
273 Logger::info('No webfinger links found', ['uri' => $uri]);
279 foreach ($webfinger['links'] as $link) {
280 $data[] = ['@attributes' => $link];
283 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
284 foreach ($webfinger['aliases'] as $alias) {
298 * Fetch information (protocol endpoints and user information) about a given uri
300 * @param string $uri Address that should be probed
301 * @param string $network Test for this specific network
302 * @param integer $uid User ID for the probe (only used for mails)
303 * @param boolean $cache Use cached values?
305 * @return array uri data
306 * @throws HTTPException\InternalServerErrorException
307 * @throws \ImagickException
309 public static function uri($uri, $network = '', $uid = -1)
311 // Local profiles aren't probed via network
312 if (empty($network) && Contact::isLocal($uri)) {
313 $data = self::localProbe($uri);
320 $uid = Session::getLocalUser();
323 if (empty($network) || ($network == Protocol::ACTIVITYPUB)) {
324 $ap_profile = ActivityPub::probeProfile($uri);
329 self::$istimeout = false;
331 if ($network != Protocol::ACTIVITYPUB) {
332 $data = self::detect($uri, $network, $uid, $ap_profile);
333 if (!is_array($data)) {
336 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
338 } elseif (!empty($ap_profile)) {
339 $ap_profile['batch'] = '';
340 $data = array_merge($ap_profile, $data);
346 if (!isset($data['url'])) {
350 if (empty($data['photo'])) {
351 $data['photo'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
354 if (empty($data['name'])) {
355 if (!empty($data['nick'])) {
356 $data['name'] = $data['nick'];
359 if (empty($data['name'])) {
360 $data['name'] = $data['url'];
364 if (empty($data['nick'])) {
365 $data['nick'] = strtolower($data['name']);
367 if (strpos($data['nick'], ' ')) {
368 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
372 if (!empty($data['baseurl']) && empty($data['gsid'])) {
373 $data['gsid'] = GServer::getID($data['baseurl']);
376 if (empty($data['network'])) {
377 $data['network'] = Protocol::PHANTOM;
380 // Ensure that local connections always are DFRN
381 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
382 $data['network'] = Protocol::DFRN;
385 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
386 $data['hide'] = self::getHideStatus($data['url']);
389 return self::rearrangeData($data);
394 * Fetches the "hide" status from the profile
396 * @param string $url URL of the profile
397 * @return boolean "hide" status
399 private static function getHideStatus(string $url): bool
401 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::CONTENT_LENGTH => 1000000]);
402 if (!$curlResult->isSuccess()) {
406 // If it isn't a HTML file then exit
407 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
411 $body = $curlResult->getBody();
416 $doc = new DOMDocument();
417 @$doc->loadHTML($body);
419 $xpath = new DOMXPath($doc);
421 $list = $xpath->query('//meta[@name]');
422 foreach ($list as $node) {
424 if ($node->attributes->length) {
425 foreach ($node->attributes as $attribute) {
426 $meta_tag[$attribute->name] = $attribute->value;
430 if (empty($meta_tag['content'])) {
434 $content = strtolower(trim($meta_tag['content']));
436 switch (strtolower(trim($meta_tag['name']))) {
437 case 'dfrn-global-visibility':
438 if ($content == 'false') {
443 if (strpos($content, 'noindex') !== false) {
454 * Fetch the "subscribe" and add it to the result
456 * @param array $result Result array
457 * @param array $webfinger Webfinger data
458 * @return array result Altered/unaltered result array
460 private static function getSubscribeLink(array $result, array $webfinger): array
462 if (empty($webfinger['links'])) {
466 foreach ($webfinger['links'] as $link) {
467 if (!empty($link['template']) && ($link['rel'] === ActivityNamespace::OSTATUSSUB)) {
468 $result['subscribe'] = $link['template'];
476 * Get webfinger data from a given URI
478 * @param string $uri URI
479 * @return array Webfinger data
480 * @throws HTTPException\InternalServerErrorException
482 private static function getWebfingerArray(string $uri): array
484 $parts = parse_url($uri);
486 if (!empty($parts['scheme']) && !empty($parts['host'])) {
487 $host = $parts['host'];
488 if (!empty($parts['port'])) {
489 $host .= ':' . $parts['port'];
492 $baseurl = $parts['scheme'] . '://' . $host;
497 $path_parts = explode('/', trim($parts['path'] ?? '', '/'));
498 if (!empty($path_parts)) {
499 $nick = ltrim(end($path_parts), '@');
500 $addr = $nick . '@' . $host;
503 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
504 if (empty($webfinger)) {
505 $lrdd = self::hostMeta($host);
508 if (empty($webfinger) && empty($lrdd)) {
509 while (empty($lrdd) && empty($webfinger) && (sizeof($path_parts) > 1)) {
510 $host .= '/' . array_shift($path_parts);
511 $baseurl = $parts['scheme'] . '://' . $host;
514 $addr = $nick . '@' . $host;
517 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
518 if (empty($webfinger)) {
519 $lrdd = self::hostMeta($host);
523 if (empty($lrdd) && empty($webfinger)) {
527 } elseif (strstr($uri, '@')) {
528 // Remove "acct:" from the URI
529 $uri = str_replace('acct:', '', $uri);
531 $host = substr($uri, strpos($uri, '@') + 1);
532 $nick = substr($uri, 0, strpos($uri, '@'));
535 $webfinger = self::getWebfinger('https://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
536 if (self::$istimeout) {
540 if (empty($webfinger)) {
541 $webfinger = self::getWebfinger('http://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
542 if (self::$istimeout) {
546 $baseurl = 'https://' . $host;
549 if (empty($webfinger)) {
550 $lrdd = self::hostMeta($host);
551 if (self::$istimeout) {
554 $baseurl = self::$baseurl;
556 $baseurl = 'http://' . $host;
559 Logger::info('URI was not detectable', ['uri' => $uri]);
563 if (empty($webfinger)) {
564 foreach ($lrdd as $type => $template) {
569 $webfinger = self::getWebfinger($template, $type, $uri, $addr);
573 if (empty($webfinger)) {
577 if ($webfinger['detected'] == $addr) {
578 $webfinger['nick'] = $nick;
579 $webfinger['addr'] = $addr;
582 $webfinger['baseurl'] = $baseurl;
588 * Perform network request for webfinger data
590 * @param string $template
591 * @param string $type
593 * @param string $addr
594 * @return array webfinger results
596 private static function getWebfinger(string $template, string $type, string $uri, string $addr): array
598 if (Network::isUrlBlocked($template)) {
599 Logger::info('Domain is blocked', ['url' => $template]);
603 // First try the address because this is the primary purpose of webfinger
606 $path = str_replace('{uri}', urlencode('acct:' . $addr), $template);
607 $webfinger = self::webfinger($path, $type);
608 if (self::$istimeout) {
614 if (empty($webfinger) && $uri != $addr) {
616 $path = str_replace('{uri}', urlencode($uri), $template);
617 $webfinger = self::webfinger($path, $type);
618 if (self::$istimeout) {
623 if (empty($webfinger)) {
627 return ['webfinger' => $webfinger, 'detected' => $detected];
631 * Fetch information (protocol endpoints and user information) about a given uri
633 * This function is only called by the "uri" function that adds caching and rearranging of data.
635 * @param string $uri Address that should be probed
636 * @param string $network Test for this specific network
637 * @param integer $uid User ID for the probe (only used for mails)
638 * @param array $ap_profile Previously probed AP profile
639 * @return array URI data
640 * @throws HTTPException\InternalServerErrorException
642 private static function detect(string $uri, string $network, int $uid, array $ap_profile): array
646 'network' => $network,
651 Hook::callAll('probe_detect', $hookData);
653 if (isset($hookData['result'])) {
654 return is_array($hookData['result']) ? $hookData['result'] : [];
657 $parts = parse_url($uri);
658 if (empty($parts['scheme']) && empty($parts['host']) && !strstr($parts['path'], '@')) {
659 Logger::info('URI was not detectable', ['uri' => $uri]);
663 // If the URI starts with "mailto:" then jump directly to the mail detection
664 if (strpos($uri, 'mailto:') !== false) {
665 $uri = str_replace('mailto:', '', $uri);
666 return self::mail($uri, $uid);
669 if ($network == Protocol::MAIL) {
670 return self::mail($uri, $uid);
673 Logger::info('Probing start', ['uri' => $uri]);
675 if (!empty($ap_profile['addr']) && ($ap_profile['addr'] != $uri)) {
676 $data = self::getWebfingerArray($ap_profile['addr']);
680 $data = self::getWebfingerArray($uri);
684 if (!empty($parts['scheme'])) {
685 return self::feed($uri);
686 } elseif (!empty($uid)) {
687 return self::mail($uri, $uid);
693 $webfinger = $data['webfinger'];
694 $nick = $data['nick'] ?? '';
695 $addr = $data['addr'] ?? '';
696 $baseurl = $data['baseurl'] ?? '';
700 if (in_array($network, ['', Protocol::DFRN])) {
701 $result = self::dfrn($webfinger);
703 if ((!$result && ($network == '')) || ($network == Protocol::DIASPORA)) {
704 $result = self::diaspora($webfinger);
706 if ((!$result && ($network == '')) || ($network == Protocol::OSTATUS)) {
707 $result = self::ostatus($webfinger);
709 if (in_array($network, ['', Protocol::ZOT])) {
710 $result = self::zot($webfinger, $result, $baseurl);
712 if ((!$result && ($network == '')) || ($network == Protocol::PUMPIO)) {
713 $result = self::pumpio($webfinger, $addr);
715 if (empty($result['network']) && empty($ap_profile['network']) || ($network == Protocol::FEED)) {
716 $result = self::feed($uri);
718 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
719 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
720 if ((empty($result['nick']) || (strstr($result['nick'], ' '))) && ($nick != '')) {
721 $result['nick'] = $nick;
724 if (empty($result['addr']) && ($addr != '')) {
725 $result['addr'] = $addr;
729 $result = self::getSubscribeLink($result, $webfinger);
731 if (empty($result['network'])) {
732 $result['network'] = Protocol::PHANTOM;
735 if (empty($result['baseurl']) && !empty($baseurl)) {
736 $result['baseurl'] = $baseurl;
739 if (empty($result['url'])) {
740 $result['url'] = $uri;
743 Logger::info('Probing done', ['uri' => $uri, 'network' => $result['network']]);
749 * Check for Zot contact
751 * @param array $webfinger Webfinger data
752 * @param array $data previously probed data
753 * @param string $baseUrl Base URL
754 * @return array Zot data
755 * @throws HTTPException\InternalServerErrorException
757 private static function zot(array $webfinger, array $data, string $baseurl): array
759 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
760 foreach ($webfinger['aliases'] as $alias) {
761 if (substr($alias, 0, 5) == 'acct:') {
762 $data['addr'] = substr($alias, 5);
767 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
768 $data['addr'] = substr($webfinger['subject'], 5);
772 foreach ($webfinger['links'] as $link) {
773 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
774 $zot_url = $link['href'];
778 if (empty($zot_url) && !empty($data['addr']) && !empty($baseurl)) {
779 $condition = ['nurl' => Strings::normaliseLink($baseurl), 'platform' => ['hubzilla']];
780 if (!DBA::exists('gserver', $condition)) {
783 $zot_url = $baseurl . '/.well-known/zot-info?address=' . $data['addr'];
786 if (empty($zot_url)) {
790 $data = self::pollZot($zot_url, $data);
792 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
793 foreach ($webfinger['aliases'] as $alias) {
794 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
795 $data['alias'] = $alias;
803 public static function pollZot(string $url, array $data): array
805 $curlResult = DI::httpClient()->get($url, HttpClientAccept::JSON);
806 if ($curlResult->isTimeout()) {
809 $content = $curlResult->getBody();
814 $json = json_decode($content, true);
815 if (!is_array($json)) {
819 if (empty($data['network'])) {
820 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
821 $data['network'] = Protocol::ZOT;
822 } elseif (!isset($json['protocols'])) {
823 $data['network'] = Protocol::ZOT;
827 if (!empty($json['guid']) && empty($data['guid'])) {
828 $data['guid'] = $json['guid'];
830 if (!empty($json['key']) && empty($data['pubkey'])) {
831 $data['pubkey'] = $json['key'];
833 if (!empty($json['name'])) {
834 $data['name'] = $json['name'];
836 if (!empty($json['photo'])) {
837 $data['photo'] = $json['photo'];
838 if (!empty($json['photo_updated'])) {
839 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
842 if (!empty($json['address'])) {
843 $data['addr'] = $json['address'];
845 if (!empty($json['url'])) {
846 $data['url'] = $json['url'];
848 if (!empty($json['connections_url'])) {
849 $data['poco'] = $json['connections_url'];
851 if (isset($json['searchable'])) {
852 $data['hide'] = !$json['searchable'];
854 if (!empty($json['public_forum'])) {
855 $data['community'] = $json['public_forum'];
856 $data['account-type'] = User::PAGE_FLAGS_COMMUNITY;
859 if (!empty($json['profile'])) {
860 $profile = $json['profile'];
861 if (!empty($profile['description'])) {
862 $data['about'] = $profile['description'];
864 if (!empty($profile['keywords'])) {
865 $keywords = implode(', ', $profile['keywords']);
866 if (!empty($keywords)) {
867 $data['keywords'] = $keywords;
872 if (!empty($profile['region'])) {
873 $loc['region'] = $profile['region'];
875 if (!empty($profile['country'])) {
876 $loc['country-name'] = $profile['country'];
878 $location = Profile::formatLocation($loc);
879 if (!empty($location)) {
880 $data['location'] = $location;
888 * Perform a webfinger request.
890 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
892 * @param string $url Address that should be probed
893 * @param string $type type
894 * @return array webfinger data
895 * @throws HTTPException\InternalServerErrorException
897 public static function webfinger(string $url, string $type): array
899 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
901 $curlResult = DI::httpClient()->get($url, $type, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
902 if ($curlResult->isTimeout()) {
903 self::$istimeout = true;
906 $data = $curlResult->getBody();
908 $webfinger = json_decode($data, true);
909 if (!empty($webfinger)) {
910 if (!isset($webfinger['links'])) {
911 Logger::info('No json webfinger links', ['url' => $url]);
917 // If it is not JSON, maybe it is XML
918 $xrd = XML::parseString($data, true);
919 if (!is_object($xrd)) {
920 Logger::info('No webfinger data retrievable', ['url' => $url]);
924 $xrd_arr = XML::elementToArray($xrd);
925 if (!isset($xrd_arr['xrd']['link'])) {
926 Logger::info('No XML webfinger links', ['url' => $url]);
932 if (!empty($xrd_arr['xrd']['subject'])) {
933 $webfinger['subject'] = $xrd_arr['xrd']['subject'];
936 if (!empty($xrd_arr['xrd']['alias'])) {
937 $webfinger['aliases'] = $xrd_arr['xrd']['alias'];
940 $webfinger['links'] = [];
942 foreach ($xrd_arr['xrd']['link'] as $value => $data) {
943 if (!empty($data['@attributes'])) {
944 $attributes = $data['@attributes'];
945 } elseif ($value == '@attributes') {
951 $webfinger['links'][] = $attributes;
957 * Poll the Friendica specific noscrape page.
959 * "noscrape" is a faster alternative to fetch the data from the hcard.
960 * This functionality was originally created for the directory.
962 * @param string $noscrape_url Link to the noscrape page
963 * @param array $data The already fetched data
964 * @return array noscrape data
965 * @throws HTTPException\InternalServerErrorException
967 private static function pollNoscrape(string $noscrape_url, array $data): array
969 $curlResult = DI::httpClient()->get($noscrape_url, HttpClientAccept::JSON);
970 if ($curlResult->isTimeout()) {
971 self::$istimeout = true;
974 $content = $curlResult->getBody();
976 Logger::info('Empty body', ['url' => $noscrape_url]);
980 $json = json_decode($content, true);
981 if (!is_array($json)) {
982 Logger::info('No json data', ['url' => $noscrape_url]);
986 if (!empty($json['fn'])) {
987 $data['name'] = $json['fn'];
990 if (!empty($json['addr'])) {
991 $data['addr'] = $json['addr'];
994 if (!empty($json['nick'])) {
995 $data['nick'] = $json['nick'];
998 if (!empty($json['guid'])) {
999 $data['guid'] = $json['guid'];
1002 if (!empty($json['comm'])) {
1003 $data['community'] = $json['comm'];
1006 if (!empty($json['tags'])) {
1007 $keywords = implode(', ', $json['tags']);
1008 if ($keywords != '') {
1009 $data['keywords'] = $keywords;
1013 $location = Profile::formatLocation($json);
1015 $data['location'] = $location;
1018 if (!empty($json['about'])) {
1019 $data['about'] = $json['about'];
1022 if (!empty($json['xmpp'])) {
1023 $data['xmpp'] = $json['xmpp'];
1026 if (!empty($json['matrix'])) {
1027 $data['matrix'] = $json['matrix'];
1030 if (!empty($json['key'])) {
1031 $data['pubkey'] = $json['key'];
1034 if (!empty($json['photo'])) {
1035 $data['photo'] = $json['photo'];
1038 if (!empty($json['dfrn-request'])) {
1039 $data['request'] = $json['dfrn-request'];
1042 if (!empty($json['dfrn-confirm'])) {
1043 $data['confirm'] = $json['dfrn-confirm'];
1046 if (!empty($json['dfrn-notify'])) {
1047 $data['notify'] = $json['dfrn-notify'];
1050 if (!empty($json['dfrn-poll'])) {
1051 $data['poll'] = $json['dfrn-poll'];
1054 if (isset($json['hide'])) {
1055 $data['hide'] = (bool)$json['hide'];
1057 $data['hide'] = false;
1064 * Check for valid DFRN data
1066 * @param array $data DFRN data
1068 * @return int Number of errors
1070 public static function validDfrn($data)
1073 if (!isset($data['key'])) {
1076 if (!isset($data['dfrn-request'])) {
1079 if (!isset($data['dfrn-confirm'])) {
1082 if (!isset($data['dfrn-notify'])) {
1085 if (!isset($data['dfrn-poll'])) {
1092 * Fetch data from a DFRN profile page and via "noscrape"
1094 * @param string $profile_link Link to the profile page
1095 * @return array profile data
1096 * @throws HTTPException\InternalServerErrorException
1097 * @throws \ImagickException
1099 public static function profile(string $profile_link): array
1103 Logger::info('Check profile', ['link' => $profile_link]);
1105 // Fetch data via noscrape - this is faster
1106 $noscrape_url = str_replace(['/hcard/', '/profile/'], '/noscrape/', $profile_link);
1107 $data = self::pollNoscrape($noscrape_url, $data);
1109 if (!isset($data['notify'])
1110 || !isset($data['confirm'])
1111 || !isset($data['request'])
1112 || !isset($data['poll'])
1113 || !isset($data['name'])
1114 || !isset($data['photo'])
1116 $data = self::pollHcard($profile_link, $data, true);
1121 if (empty($data['addr']) || empty($data['nick'])) {
1122 $probe_data = self::uri($profile_link);
1123 $data['addr'] = ($data['addr'] ?? '') ?: $probe_data['addr'];
1124 $data['nick'] = ($data['nick'] ?? '') ?: $probe_data['nick'];
1127 $prof_data['addr'] = $data['addr'];
1128 $prof_data['nick'] = $data['nick'];
1129 $prof_data['dfrn-request'] = $data['request'] ?? null;
1130 $prof_data['dfrn-confirm'] = $data['confirm'] ?? null;
1131 $prof_data['dfrn-notify'] = $data['notify'] ?? null;
1132 $prof_data['dfrn-poll'] = $data['poll'] ?? null;
1133 $prof_data['photo'] = $data['photo'] ?? null;
1134 $prof_data['fn'] = $data['name'] ?? null;
1135 $prof_data['key'] = $data['pubkey'] ?? null;
1137 Logger::debug('Result', ['link' => $profile_link, 'data' => $prof_data]);
1143 * Check for DFRN contact
1145 * @param array $webfinger Webfinger data
1146 * @return array DFRN data
1147 * @throws HTTPException\InternalServerErrorException
1149 private static function dfrn(array $webfinger): array
1153 // The array is reversed to take into account the order of preference for same-rel links
1154 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1155 foreach (array_reverse($webfinger['links']) as $link) {
1156 if (($link['rel'] == ActivityNamespace::DFRN) && !empty($link['href'])) {
1157 $data['network'] = Protocol::DFRN;
1158 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1159 $data['poll'] = $link['href'];
1160 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1161 $data['url'] = $link['href'];
1162 } elseif (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1163 $hcard_url = $link['href'];
1164 } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1165 $data['poco'] = $link['href'];
1166 } elseif (($link['rel'] == 'http://webfinger.net/rel/avatar') && !empty($link['href'])) {
1167 $data['photo'] = $link['href'];
1168 } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1169 $data['baseurl'] = trim($link['href'], '/');
1170 } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1171 $data['guid'] = $link['href'];
1172 } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1173 $data['pubkey'] = base64_decode($link['href']);
1175 if (strstr($data['pubkey'], 'RSA ')) {
1176 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1181 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1182 foreach ($webfinger['aliases'] as $alias) {
1183 if (empty($data['url']) && !strstr($alias, '@')) {
1184 $data['url'] = $alias;
1185 } elseif (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
1186 $data['alias'] = $alias;
1187 } elseif (substr($alias, 0, 5) == 'acct:') {
1188 $data['addr'] = substr($alias, 5);
1193 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1194 $data['addr'] = substr($webfinger['subject'], 5);
1197 if (!isset($data['network']) || ($hcard_url == '')) {
1201 // Fetch data via noscrape - this is faster
1202 $noscrape_url = str_replace('/hcard/', '/noscrape/', $hcard_url);
1203 $data = self::pollNoscrape($noscrape_url, $data);
1205 if (isset($data['notify'])
1206 && isset($data['confirm'])
1207 && isset($data['request'])
1208 && isset($data['poll'])
1209 && isset($data['name'])
1210 && isset($data['photo'])
1215 $data = self::pollHcard($hcard_url, $data, true);
1221 * Poll the hcard page (Diaspora and Friendica specific)
1223 * @param string $hcard_url Link to the hcard page
1224 * @param array $data The already fetched data
1225 * @param boolean $dfrn Poll DFRN specific data
1226 * @return array hcard data
1227 * @throws HTTPException\InternalServerErrorException
1229 private static function pollHcard(string $hcard_url, array $data, bool $dfrn = false): array
1231 $curlResult = DI::httpClient()->get($hcard_url, HttpClientAccept::HTML);
1232 if ($curlResult->isTimeout()) {
1233 self::$istimeout = true;
1236 $content = $curlResult->getBody();
1237 if (empty($content)) {
1241 $doc = new DOMDocument();
1242 if (!@$doc->loadHTML($content)) {
1246 $xpath = new DomXPath($doc);
1248 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1249 if (!is_object($vcards)) {
1253 if (!isset($data['baseurl'])) {
1254 $data['baseurl'] = '';
1257 if ($vcards->length > 0) {
1258 $vcard = $vcards->item(0);
1260 // We have to discard the guid from the hcard in favour of the guid from lrdd
1261 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1262 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1263 if (($search->length > 0) && empty($data['guid'])) {
1264 $data['guid'] = $search->item(0)->nodeValue;
1267 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1268 if ($search->length > 0) {
1269 $data['nick'] = $search->item(0)->nodeValue;
1272 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1273 if ($search->length > 0) {
1274 $data['name'] = $search->item(0)->nodeValue;
1277 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1278 if ($search->length > 0) {
1279 $data['searchable'] = $search->item(0)->nodeValue;
1282 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1283 if ($search->length > 0) {
1284 $data['pubkey'] = $search->item(0)->nodeValue;
1285 if (strstr($data['pubkey'], 'RSA ')) {
1286 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1290 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1291 if ($search->length > 0) {
1292 $data['baseurl'] = trim($search->item(0)->nodeValue, '/');
1297 if (!empty($vcard)) {
1298 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1299 foreach ($photos as $photo) {
1301 foreach ($photo->attributes as $attribute) {
1302 $attr[$attribute->name] = trim($attribute->value);
1305 if (isset($attr['src']) && isset($attr['width'])) {
1306 $avatar[$attr['width']] = $attr['src'];
1309 // We don't have a width. So we just take everything that we got.
1310 // This is a Hubzilla workaround which doesn't send a width.
1311 if ((sizeof($avatar) == 0) && !empty($attr['src'])) {
1312 $avatar[] = $attr['src'];
1317 if (sizeof($avatar)) {
1319 $data['photo'] = self::fixAvatar(array_pop($avatar), $data['baseurl']);
1323 // Poll DFRN specific data
1324 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1325 if ($search->length > 0) {
1326 foreach ($search as $link) {
1327 //$data['request'] = $search->item(0)->nodeValue;
1329 foreach ($link->attributes as $attribute) {
1330 $attr[$attribute->name] = trim($attribute->value);
1333 $data[substr($attr['rel'], 5)] = $attr['href'];
1337 // Older Friendica versions had used the "uid" field differently than newer versions
1338 if (!empty($data['nick']) && !empty($data['guid']) && ($data['nick'] == $data['guid'])) {
1339 unset($data['guid']);
1348 * Check for Diaspora contact
1350 * @param array $webfinger Webfinger data
1351 * @return array Diaspora data
1352 * @throws HTTPException\InternalServerErrorException
1354 private static function diaspora(array $webfinger): array
1359 // The array is reversed to take into account the order of preference for same-rel links
1360 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1361 foreach (array_reverse($webfinger['links']) as $link) {
1362 if (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1363 $hcard_url = $link['href'];
1364 } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1365 $data['baseurl'] = trim($link['href'], '/');
1366 } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1367 $data['guid'] = $link['href'];
1368 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1369 $data['url'] = $link['href'];
1370 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && empty($link['type']) && !empty($link['href'])) {
1371 $profile_url = $link['href'];
1372 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1373 $data['poll'] = $link['href'];
1374 } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1375 $data['poco'] = $link['href'];
1376 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1377 $data['notify'] = $link['href'];
1378 } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1379 $data['pubkey'] = base64_decode($link['href']);
1381 if (strstr($data['pubkey'], 'RSA ')) {
1382 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1387 if (empty($data['url']) && !empty($profile_url)) {
1388 $data['url'] = $profile_url;
1391 if (empty($data['url']) || empty($hcard_url)) {
1395 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1396 foreach ($webfinger['aliases'] as $alias) {
1397 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data['url']) && ! strstr($alias, '@')) {
1398 $data['alias'] = $alias;
1399 } elseif (substr($alias, 0, 5) == 'acct:') {
1400 $data['addr'] = substr($alias, 5);
1405 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1406 $data['addr'] = substr($webfinger['subject'], 5);
1409 // Fetch further information from the hcard
1410 $data = self::pollHcard($hcard_url, $data);
1416 if (!empty($data['url'])
1417 && !empty($data['guid'])
1418 && !empty($data['baseurl'])
1419 && !empty($data['pubkey'])
1420 && !empty($hcard_url)
1422 $data['network'] = Protocol::DIASPORA;
1423 $data['manually-approve'] = false;
1425 // The Diaspora handle must always be lowercase
1426 if (!empty($data['addr'])) {
1427 $data['addr'] = strtolower($data['addr']);
1430 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1431 $data['notify'] = $data['baseurl'] . '/receive/users/' . $data['guid'];
1432 $data['batch'] = $data['baseurl'] . '/receive/public';
1441 * Check for OStatus contact
1443 * @param array $webfinger Webfinger data
1444 * @param bool $short Short detection mode
1445 * @return array|bool OStatus data or "false" on error or "true" on short mode
1446 * @throws HTTPException\InternalServerErrorException
1448 private static function ostatus(array $webfinger, bool $short = false)
1452 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1453 foreach ($webfinger['aliases'] as $alias) {
1454 if (strstr($alias, '@') && !strstr(Strings::normaliseLink($alias), 'http://')) {
1455 $data['addr'] = str_replace('acct:', '', $alias);
1460 if (!empty($webfinger['subject']) && strstr($webfinger['subject'], '@')
1461 && !strstr(Strings::normaliseLink($webfinger['subject']), 'http://')
1463 $data['addr'] = str_replace('acct:', '', $webfinger['subject']);
1466 if (!empty($webfinger['links'])) {
1467 // The array is reversed to take into account the order of preference for same-rel links
1468 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1469 foreach (array_reverse($webfinger['links']) as $link) {
1470 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1471 && (($link['type'] ?? '') == 'text/html')
1472 && ($link['href'] != '')
1474 $data['url'] = $data['alias'] = $link['href'];
1475 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1476 $data['notify'] = $link['href'];
1477 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1478 $data['poll'] = $link['href'];
1479 } elseif (($link['rel'] == 'magic-public-key') && !empty($link['href'])) {
1480 $pubkey = $link['href'];
1482 if (substr($pubkey, 0, 5) === 'data:') {
1483 if (strstr($pubkey, ',')) {
1484 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1486 $pubkey = substr($pubkey, 5);
1488 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1489 $curlResult = DI::httpClient()->get($pubkey, HttpClientAccept::MAGIC_KEY);
1490 if ($curlResult->isTimeout()) {
1491 self::$istimeout = true;
1492 return $short ? false : [];
1494 Logger::debug('Fetched public key', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $pubkey]);
1495 $pubkey = $curlResult->getBody();
1498 $key = explode('.', $pubkey);
1500 if (sizeof($key) >= 3) {
1501 $m = Strings::base64UrlDecode($key[1]);
1502 $e = Strings::base64UrlDecode($key[2]);
1503 $data['pubkey'] = Crypto::meToPem($m, $e);
1509 if (isset($data['notify']) && isset($data['pubkey'])
1510 && isset($data['poll'])
1511 && isset($data['url'])
1513 $data['network'] = Protocol::OSTATUS;
1514 $data['manually-approve'] = false;
1516 return $short ? false : [];
1523 // Fetch all additional data from the feed
1524 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::FEED_XML);
1525 if ($curlResult->isTimeout()) {
1526 self::$istimeout = true;
1529 $feed = $curlResult->getBody();
1530 $feed_data = Feed::import($feed);
1535 if (!empty($feed_data['header']['author-name'])) {
1536 $data['name'] = $feed_data['header']['author-name'];
1538 if (!empty($feed_data['header']['author-nick'])) {
1539 $data['nick'] = $feed_data['header']['author-nick'];
1541 if (!empty($feed_data['header']['author-avatar'])) {
1542 $data['photo'] = self::fixAvatar($feed_data['header']['author-avatar'], $data['url']);
1544 if (!empty($feed_data['header']['author-id'])) {
1545 $data['alias'] = $feed_data['header']['author-id'];
1547 if (!empty($feed_data['header']['author-location'])) {
1548 $data['location'] = $feed_data['header']['author-location'];
1550 if (!empty($feed_data['header']['author-about'])) {
1551 $data['about'] = $feed_data['header']['author-about'];
1553 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1554 // So we take the value that we just fetched, although the other one worked as well
1555 if (!empty($feed_data['header']['author-link'])) {
1556 $data['url'] = $feed_data['header']['author-link'];
1559 if ($data['url'] == $data['alias']) {
1560 $data['alias'] = '';
1563 /// @todo Fetch location and "about" from the feed as well
1568 * Fetch data from a pump.io profile page
1570 * @param string $profile_link Link to the profile page
1571 * @return array Profile data
1573 private static function pumpioProfileData(string $profile_link): array
1575 $curlResult = DI::httpClient()->get($profile_link, HttpClientAccept::HTML);
1576 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
1580 $doc = new DOMDocument();
1581 if (!@$doc->loadHTML($curlResult->getBody())) {
1585 $xpath = new DomXPath($doc);
1588 $data['name'] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1590 if ($data['name'] == '') {
1591 // This is ugly - but pump.io doesn't seem to know a better way for it
1592 $data['name'] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1593 $pos = strpos($data['name'], chr(10));
1595 $data['name'] = trim(substr($data['name'], 0, $pos));
1599 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1601 if ($data['location'] == '') {
1602 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1605 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1607 if ($data['about'] == '') {
1608 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1611 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1613 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1616 foreach ($avatar->attributes as $attribute) {
1617 if ($attribute->name == 'src') {
1618 $data['photo'] = trim($attribute->value);
1627 * Check for pump.io contact
1629 * @param array $webfinger Webfinger data
1630 * @param string $addr
1631 * @return array pump.io data
1633 private static function pumpio(array $webfinger, string $addr): array
1636 // The array is reversed to take into account the order of preference for same-rel links
1637 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1638 foreach (array_reverse($webfinger['links']) as $link) {
1639 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1640 && (($link['type'] ?? '') == 'text/html')
1641 && ($link['href'] != '')
1643 $data['url'] = $link['href'];
1644 } elseif (($link['rel'] == 'activity-inbox') && ($link['href'] != '')) {
1645 $data['notify'] = $link['href'];
1646 } elseif (($link['rel'] == 'activity-outbox') && ($link['href'] != '')) {
1647 $data['poll'] = $link['href'];
1648 } elseif (($link['rel'] == 'dialback') && ($link['href'] != '')) {
1649 $data['dialback'] = $link['href'];
1652 if (isset($data['poll']) && isset($data['notify'])
1653 && isset($data['dialback'])
1654 && isset($data['url'])
1656 // by now we use these fields only for the network type detection
1657 // So we unset all data that isn't used at the moment
1658 unset($data['dialback']);
1660 $data['network'] = Protocol::PUMPIO;
1665 $profile_data = self::pumpioProfileData($data['url']);
1667 if (!$profile_data) {
1671 $data = array_merge($data, $profile_data);
1673 if (($addr != '') && ($data['name'] != '')) {
1674 $name = trim(str_replace($addr, '', $data['name']));
1676 $data['name'] = $name;
1684 * Checks HTML page for RSS feed link
1686 * @param string $url Page link
1687 * @param string $body Page body string
1688 * @return string|false Feed link or false if body was invalid HTML document
1690 public static function getFeedLink(string $url, string $body)
1696 $doc = new DOMDocument();
1697 if (!@$doc->loadHTML($body)) {
1701 $xpath = new DOMXPath($doc);
1703 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1705 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1711 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1713 * Loosely based on RFC 1808
1715 * @see https://tools.ietf.org/html/rfc1808
1717 * @param string $href The potential relative href found in the HTML document
1718 * @param string $base The HTML document URL
1719 * @param DOMXPath $xpath The HTML document XPath
1720 * @return string Absolute URL
1722 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath): string
1724 if (filter_var($href, FILTER_VALIDATE_URL)) {
1728 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1730 $baseParts = parse_url($base);
1731 if (empty($baseParts['host'])) {
1735 // Naked domain case (scheme://basehost)
1736 $path = $baseParts['path'] ?? '/';
1738 // Remove the filename part of the path if it exists (/base/path/file)
1739 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1741 $hrefParts = parse_url($href);
1743 if (!empty($hrefParts['path'])) {
1744 // Root path case (/path) including relative scheme case (//host/path)
1745 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1746 $path = $hrefParts['path'];
1748 $path = $path . '/' . $hrefParts['path'];
1750 // Resolve arbitrary relative path
1751 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1752 $parts = array_filter(explode('/', $path), 'strlen');
1754 foreach ($parts as $part) {
1755 if ('.' == $part) continue;
1756 if ('..' == $part) {
1757 array_pop($absolutes);
1759 $absolutes[] = $part;
1763 $path = '/' . implode('/', $absolutes);
1767 // Relative scheme case (//host/path)
1768 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1769 $baseParts['path'] = $path;
1770 unset($baseParts['query']);
1771 unset($baseParts['fragment']);
1773 return Network::unparseURL($baseParts);
1777 * Check for feed contact
1779 * @param string $url Profile link
1780 * @param boolean $probe Do a probe if the page contains a feed link
1781 * @return array feed data
1782 * @throws HTTPException\InternalServerErrorException
1784 private static function feed(string $url, bool $probe = true): array
1786 $curlResult = DI::httpClient()->get($url, HttpClientAccept::FEED_XML);
1787 if ($curlResult->isTimeout()) {
1788 self::$istimeout = true;
1791 $feed = $curlResult->getBody();
1792 $feed_data = Feed::import($feed);
1799 $feed_url = self::getFeedLink($url, $feed);
1805 return self::feed($feed_url, false);
1808 if (!empty($feed_data['header']['author-name'])) {
1809 $data['name'] = $feed_data['header']['author-name'];
1812 if (!empty($feed_data['header']['author-nick'])) {
1813 $data['nick'] = $feed_data['header']['author-nick'];
1816 if (!empty($feed_data['header']['author-avatar'])) {
1817 $data['photo'] = $feed_data['header']['author-avatar'];
1820 if (!empty($feed_data['header']['author-id'])) {
1821 $data['alias'] = $feed_data['header']['author-id'];
1824 $data['url'] = $url;
1825 $data['poll'] = $url;
1827 $data['network'] = Protocol::FEED;
1833 * Check for mail contact
1835 * @param string $uri Profile link
1836 * @param integer $uid User ID
1837 * @return array mail data
1838 * @throws \Exception
1840 private static function mail(string $uri, int $uid): array
1842 if (!Network::isEmailDomainValid($uri)) {
1850 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1852 $condition = ["`uid` = ? AND `server` != ''", $uid];
1853 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1854 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1856 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1860 $mailbox = Email::constructMailboxName($mailacct);
1862 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1863 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1868 $msgs = Email::poll($mbox, $uri);
1869 Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
1871 if (!count($msgs)) {
1875 $phost = substr($uri, strpos($uri, '@') + 1);
1878 $data['addr'] = $uri;
1879 $data['network'] = Protocol::MAIL;
1880 $data['name'] = substr($uri, 0, strpos($uri, '@'));
1881 $data['nick'] = $data['name'];
1882 $data['photo'] = Network::lookupAvatarByEmail($uri);
1883 $data['url'] = 'mailto:'.$uri;
1884 $data['notify'] = 'smtp ' . Strings::getRandomHex();
1885 $data['poll'] = 'email ' . Strings::getRandomHex();
1887 $x = Email::messageMeta($mbox, $msgs[0]);
1888 if (stristr($x[0]->from, $uri)) {
1889 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1890 } elseif (stristr($x[0]->to, $uri)) {
1891 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1894 foreach ($adr as $feadr) {
1895 if ((strcasecmp($feadr->mailbox, $data['name']) == 0)
1896 &&(strcasecmp($feadr->host, $phost) == 0)
1897 && (strlen($feadr->personal))
1899 $personal = imap_mime_header_decode($feadr->personal);
1901 foreach ($personal as $perspart) {
1902 if ($perspart->charset != 'default') {
1903 $data['name'] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1905 $data['name'] .= $perspart->text;
1911 if (!empty($mbox)) {
1918 * Mix two paths together to possibly fix missing parts
1920 * @param string $avatar Path to the avatar
1921 * @param string $base Another path that is hopefully complete
1922 * @return string fixed avatar path
1923 * @throws \Exception
1925 public static function fixAvatar(string $avatar, string $base): string
1927 $base_parts = parse_url($base);
1929 // Remove all parts that could create a problem
1930 unset($base_parts['path']);
1931 unset($base_parts['query']);
1932 unset($base_parts['fragment']);
1934 $avatar_parts = parse_url($avatar);
1937 $parts = array_merge($base_parts, $avatar_parts);
1939 // And put them together again
1940 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1941 $host = isset($parts['host']) ? $parts['host'] : '';
1942 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1943 $path = isset($parts['path']) ? $parts['path'] : '';
1944 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1945 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1947 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1949 Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
1955 * Fetch the last date that the contact had posted something (publically)
1957 * @param array $data probing result
1958 * @return string last activity
1960 public static function getLastUpdate(array $data): string
1962 $uid = User::getIdForURL($data['url']);
1964 $contact = Contact::selectFirst(['url', 'last-item'], ['self' => true, 'uid' => $uid]);
1965 if (!empty($contact['last-item'])) {
1966 return $contact['last-item'];
1970 if ($lastUpdate = self::updateFromNoScrape($data)) {
1974 if (!empty($data['outbox'])) {
1975 return self::updateFromOutbox($data['outbox'], $data);
1976 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
1977 return self::updateFromOutbox($data['poll'], $data);
1978 } elseif (!empty($data['poll'])) {
1979 return self::updateFromFeed($data);
1986 * Fetch the last activity date from the "noscrape" endpoint
1988 * @param array $data Probing result
1989 * @return string last activity or true if update was successful or the server was unreachable
1991 private static function updateFromNoScrape(array $data): string
1993 if (empty($data['baseurl'])) {
1997 // Check the 'noscrape' endpoint when it is a Friendica server
1998 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
1999 Strings::normaliseLink($data['baseurl'])]);
2000 if (!DBA::isResult($gserver)) {
2004 $curlResult = DI::httpClient()->get($gserver['noscrape'] . '/' . $data['nick'], HttpClientAccept::JSON);
2006 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
2007 $noscrape = json_decode($curlResult->getBody(), true);
2008 if (!empty($noscrape) && !empty($noscrape['updated'])) {
2009 return DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2017 * Fetch the last activity date from an ActivityPub Outbox
2019 * @param string $feed
2020 * @param array $data Probing result
2021 * @return string last activity
2022 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2024 private static function updateFromOutbox(string $feed, array $data): string
2026 $outbox = ActivityPub::fetchContent($feed);
2027 if (empty($outbox)) {
2031 if (!empty($outbox['orderedItems'])) {
2032 $items = $outbox['orderedItems'];
2033 } elseif (!empty($outbox['first']['orderedItems'])) {
2034 $items = $outbox['first']['orderedItems'];
2035 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2036 return self::updateFromOutbox($outbox['first']['href'], $data);
2037 } elseif (!empty($outbox['first'])) {
2038 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2039 return self::updateFromOutbox($outbox['first'], $data);
2041 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2049 foreach ($items as $activity) {
2050 if (!empty($activity['published'])) {
2051 $published = DateTimeFormat::utc($activity['published']);
2052 } elseif (!empty($activity['object']['published'])) {
2053 $published = DateTimeFormat::utc($activity['object']['published']);
2058 if ($last_updated < $published) {
2059 $last_updated = $published;
2063 if (!empty($last_updated)) {
2064 return $last_updated;
2071 * Fetch the last activity date from an XML feed
2073 * @param array $data Probing result
2074 * @return string last activity
2076 private static function updateFromFeed(array $data): string
2078 // Search for the newest entry in the feed
2079 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::ATOM_XML);
2080 if (!$curlResult->isSuccess() || !$curlResult->getBody()) {
2084 $doc = new DOMDocument();
2085 @$doc->loadXML($curlResult->getBody());
2087 $xpath = new DOMXPath($doc);
2088 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2090 $entries = $xpath->query('/atom:feed/atom:entry');
2094 foreach ($entries as $entry) {
2095 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2096 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
2097 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2098 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2100 if (empty($published) || empty($updated)) {
2101 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2105 if ($last_updated < $published) {
2106 $last_updated = $published;
2109 if ($last_updated < $updated) {
2110 $last_updated = $updated;
2114 if (!empty($last_updated)) {
2115 return $last_updated;
2122 * Probe data from local profiles without network traffic
2124 * @param string $url
2125 * @return array probed data
2126 * @throws HTTPException\InternalServerErrorException
2127 * @throws HTTPException\NotFoundException
2129 private static function localProbe(string $url): array
2132 $uid = User::getIdForURL($url);
2134 throw new HTTPException\NotFoundException('User not found.');
2137 $owner = User::getOwnerDataById($uid);
2138 $approfile = ActivityPub\Transmitter::getProfile($uid);
2140 if (empty($owner['gsid'])) {
2141 $owner['gsid'] = GServer::getID($approfile['generator']['url']);
2145 'name' => $owner['name'], 'nick' => $owner['nick'], 'guid' => $approfile['diaspora:guid'] ?? '',
2146 'url' => $owner['url'], 'addr' => $owner['addr'], 'alias' => $owner['alias'],
2147 'photo' => User::getAvatarUrl($owner),
2148 'header' => $owner['header'] ? Contact::getHeaderUrlForId($owner['id'], $owner['updated']) : '',
2149 'account-type' => $owner['contact-type'], 'community' => ($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY),
2150 'keywords' => $owner['keywords'], 'location' => $owner['location'], 'about' => $owner['about'],
2151 'xmpp' => $owner['xmpp'], 'matrix' => $owner['matrix'],
2152 'hide' => !$owner['net-publish'], 'batch' => '', 'notify' => $owner['notify'],
2153 'poll' => $owner['poll'], 'request' => $owner['request'], 'confirm' => $owner['confirm'],
2154 'subscribe' => $approfile['generator']['url'] . '/follow?url={uri}', 'poco' => $owner['poco'],
2155 'following' => $approfile['following'], 'followers' => $approfile['followers'],
2156 'inbox' => $approfile['inbox'], 'outbox' => $approfile['outbox'],
2157 'sharedinbox' => $approfile['endpoints']['sharedInbox'], 'network' => Protocol::DFRN,
2158 'pubkey' => $owner['upubkey'], 'baseurl' => $approfile['generator']['url'], 'gsid' => $owner['gsid'],
2159 'manually-approve' => in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])
2161 } catch (Exception $e) {
2162 // Default values for non existing targets
2164 'name' => $url, 'nick' => $url, 'url' => $url, 'network' => Protocol::PHANTOM,
2165 'photo' => DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO
2169 return self::rearrangeData($data);