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\Util\Crypto;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\Network;
46 use Friendica\Util\Strings;
47 use Friendica\Util\XML;
48 use GuzzleHttp\Psr7\Uri;
51 * This class contain functions for probing URL
55 const WEBFINGER = '/.well-known/webfinger?resource={uri}';
57 private static $baseurl;
58 private static $istimeout;
61 * Checks if the provided network can be probed
63 * @param string $network
66 public static function isProbable(string $network): bool
68 return (in_array($network, array_merge(Protocol::FEDERATED, [Protocol::ZOT, Protocol::PHANTOM])));
72 * Remove stuff from an URI that doesn't belong there
74 * @param string $rawUri
75 * @return string Cleaned URI
77 public static function cleanURI(string $rawUri): string
79 // At first remove leading and trailing junk
80 $rawUri = trim($rawUri, "@#?: \t\n\r\0\x0B");
82 $rawUri = Network::convertToIdn($rawUri);
84 $uri = new Uri($rawUri);
85 if (!$uri->getScheme()) {
86 return $uri->__toString();
89 // Remove the URL fragment, since these shouldn't be part of any profile URL
90 $uri = $uri->withFragment('');
92 return $uri->__toString();
96 * Rearrange the array so that it always has the same order
98 * @param array $data Unordered data
99 * @return array Ordered data
101 private static function rearrangeData(array $data): array
103 $fields = ['name', 'nick', 'guid', 'url', 'addr', 'alias', 'photo', 'header',
104 'account-type', 'community', 'keywords', 'location', 'about', 'xmpp', 'matrix',
105 'hide', 'batch', 'notify', 'poll', 'request', 'confirm', 'subscribe', 'poco',
106 'following', 'followers', 'inbox', 'outbox', 'sharedinbox',
107 'priority', 'network', 'pubkey', 'manually-approve', 'baseurl', 'gsid'];
109 $numeric_fields = ['gsid', 'hide', 'account-type', 'manually-approve'];
112 foreach ($fields as $field) {
113 if (isset($data[$field])) {
114 if (in_array($field, $numeric_fields)) {
115 $newdata[$field] = (int)$data[$field];
117 $newdata[$field] = $data[$field];
119 } elseif (!in_array($field, $numeric_fields)) {
120 $newdata[$field] = '';
122 $newdata[$field] = null;
126 // We don't use the "priority" field anymore and replace it with a dummy.
127 $newdata['priority'] = 0;
133 * Check if the hostname belongs to the own server
135 * @param string $host The hostname that is to be checked
136 * @return bool Does the testes hostname belongs to the own server?
138 private static function ownHost(string $host): bool
140 $own_host = DI::baseUrl()->getHostname();
142 $parts = parse_url($host);
144 if (!isset($parts['scheme'])) {
145 $parts = parse_url('http://'.$host);
148 if (!isset($parts['host'])) {
151 return $parts['host'] == $own_host;
155 * Probes for webfinger path via "host-meta"
157 * We have to check if the servers in the future still will offer this.
158 * It seems as if it was dropped from the standard.
160 * @param string $host The host part of an url
161 * @return array with template and type of the webfinger template for JSON or XML
162 * @throws HTTPException\InternalServerErrorException
164 private static function hostMeta(string $host): array
166 // Reset the static variable
169 // Handles the case when the hostname contains the scheme
170 if (!parse_url($host, PHP_URL_SCHEME)) {
171 $ssl_url = 'https://' . $host . '/.well-known/host-meta';
172 $url = 'http://' . $host . '/.well-known/host-meta';
174 $ssl_url = $host . '/.well-known/host-meta';
178 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
180 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
183 $curlResult = DI::httpClient()->get($ssl_url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
184 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
185 if ($curlResult->isSuccess()) {
186 $xml = $curlResult->getBody();
187 $xrd = XML::parseString($xml, true);
189 $host_url = 'https://' . $host;
193 } elseif ($curlResult->isTimeout()) {
194 Logger::info('Probing timeout', ['url' => $ssl_url]);
195 self::$istimeout = true;
199 if (!is_object($xrd) && !empty($url)) {
200 $curlResult = DI::httpClient()->get($url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
201 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
202 if ($curlResult->isTimeout()) {
203 Logger::info('Probing timeout', ['url' => $url]);
204 self::$istimeout = true;
206 } elseif ($connection_error && $ssl_connection_error) {
207 self::$istimeout = true;
211 $xml = $curlResult->getBody();
212 $xrd = XML::parseString($xml, true);
213 $host_url = 'http://'.$host;
215 if (!is_object($xrd)) {
216 Logger::info('No xrd object found', ['host' => $host]);
220 $links = XML::elementToArray($xrd);
221 if (!isset($links['xrd']['link'])) {
222 Logger::info('No xrd data found', ['host' => $host]);
228 foreach ($links['xrd']['link'] as $value => $link) {
229 if (!empty($link['@attributes'])) {
230 $attributes = $link['@attributes'];
231 } elseif ($value == '@attributes') {
237 if (!empty($attributes['rel']) && $attributes['rel'] == 'lrdd' && !empty($attributes['template'])) {
238 $type = (empty($attributes['type']) ? '' : $attributes['type']);
240 $lrdd[$type] = $attributes['template'];
244 if (Network::isUrlBlocked($host_url)) {
245 Logger::info('Domain is blocked', ['url' => $host]);
249 self::$baseurl = $host_url;
251 Logger::info('Probing successful', ['host' => $host]);
257 * Check an URI for LRDD data
259 * @param string $uri Address that should be probed
260 * @return array uri data
261 * @throws HTTPException\InternalServerErrorException
263 public static function lrdd(string $uri): array
265 $data = self::getWebfingerArray($uri);
269 $webfinger = $data['webfinger'];
271 if (empty($webfinger['links'])) {
272 Logger::info('No webfinger links found', ['uri' => $uri]);
278 foreach ($webfinger['links'] as $link) {
279 $data[] = ['@attributes' => $link];
282 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
283 foreach ($webfinger['aliases'] as $alias) {
297 * Fetch information (protocol endpoints and user information) about a given uri
299 * @param string $uri Address that should be probed
300 * @param string $network Test for this specific network
301 * @param integer $uid User ID for the probe (only used for mails)
302 * @param boolean $cache Use cached values?
304 * @return array uri data
305 * @throws HTTPException\InternalServerErrorException
306 * @throws \ImagickException
308 public static function uri($uri, $network = '', $uid = -1)
310 // Local profiles aren't probed via network
311 if (empty($network) && Contact::isLocal($uri)) {
312 $data = self::localProbe($uri);
322 if (empty($network) || ($network == Protocol::ACTIVITYPUB)) {
323 $ap_profile = ActivityPub::probeProfile($uri);
328 self::$istimeout = false;
330 if ($network != Protocol::ACTIVITYPUB) {
331 $data = self::detect($uri, $network, $uid, $ap_profile);
332 if (!is_array($data)) {
335 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
337 } elseif (!empty($ap_profile)) {
338 $ap_profile['batch'] = '';
339 $data = array_merge($ap_profile, $data);
345 if (!isset($data['url'])) {
349 if (empty($data['photo'])) {
350 $data['photo'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
353 if (empty($data['name'])) {
354 if (!empty($data['nick'])) {
355 $data['name'] = $data['nick'];
358 if (empty($data['name'])) {
359 $data['name'] = $data['url'];
363 if (empty($data['nick'])) {
364 $data['nick'] = strtolower($data['name']);
366 if (strpos($data['nick'], ' ')) {
367 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
371 if (!empty($data['baseurl']) && empty($data['gsid'])) {
372 $data['gsid'] = GServer::getID($data['baseurl']);
375 if (empty($data['network'])) {
376 $data['network'] = Protocol::PHANTOM;
379 // Ensure that local connections always are DFRN
380 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
381 $data['network'] = Protocol::DFRN;
384 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
385 $data['hide'] = self::getHideStatus($data['url']);
388 return self::rearrangeData($data);
393 * Fetches the "hide" status from the profile
395 * @param string $url URL of the profile
396 * @return boolean "hide" status
398 private static function getHideStatus(string $url): bool
400 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::CONTENT_LENGTH => 1000000]);
401 if (!$curlResult->isSuccess()) {
405 // If it isn't a HTML file then exit
406 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
410 $body = $curlResult->getBody();
415 $doc = new DOMDocument();
416 @$doc->loadHTML($body);
418 $xpath = new DOMXPath($doc);
420 $list = $xpath->query('//meta[@name]');
421 foreach ($list as $node) {
423 if ($node->attributes->length) {
424 foreach ($node->attributes as $attribute) {
425 $meta_tag[$attribute->name] = $attribute->value;
429 if (empty($meta_tag['content'])) {
433 $content = strtolower(trim($meta_tag['content']));
435 switch (strtolower(trim($meta_tag['name']))) {
436 case 'dfrn-global-visibility':
437 if ($content == 'false') {
442 if (strpos($content, 'noindex') !== false) {
453 * Fetch the "subscribe" and add it to the result
455 * @param array $result Result array
456 * @param array $webfinger Webfinger data
457 * @return array result Altered/unaltered result array
459 private static function getSubscribeLink(array $result, array $webfinger): array
461 if (empty($webfinger['links'])) {
465 foreach ($webfinger['links'] as $link) {
466 if (!empty($link['template']) && ($link['rel'] === ActivityNamespace::OSTATUSSUB)) {
467 $result['subscribe'] = $link['template'];
475 * Get webfinger data from a given URI
477 * @param string $uri URI
478 * @return array Webfinger data
479 * @throws HTTPException\InternalServerErrorException
481 private static function getWebfingerArray(string $uri): array
483 $parts = parse_url($uri);
485 if (!empty($parts['scheme']) && !empty($parts['host'])) {
486 $host = $parts['host'];
487 if (!empty($parts['port'])) {
488 $host .= ':' . $parts['port'];
491 $baseurl = $parts['scheme'] . '://' . $host;
496 $path_parts = explode('/', trim($parts['path'] ?? '', '/'));
497 if (!empty($path_parts)) {
498 $nick = ltrim(end($path_parts), '@');
499 $addr = $nick . '@' . $host;
502 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
503 if (empty($webfinger)) {
504 $lrdd = self::hostMeta($host);
507 if (empty($webfinger) && empty($lrdd)) {
508 while (empty($lrdd) && empty($webfinger) && (sizeof($path_parts) > 1)) {
509 $host .= '/' . array_shift($path_parts);
510 $baseurl = $parts['scheme'] . '://' . $host;
513 $addr = $nick . '@' . $host;
516 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
517 if (empty($webfinger)) {
518 $lrdd = self::hostMeta($host);
522 if (empty($lrdd) && empty($webfinger)) {
526 } elseif (strstr($uri, '@')) {
527 // Remove "acct:" from the URI
528 $uri = str_replace('acct:', '', $uri);
530 $host = substr($uri, strpos($uri, '@') + 1);
531 $nick = substr($uri, 0, strpos($uri, '@'));
534 $webfinger = self::getWebfinger('https://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
535 if (self::$istimeout) {
539 if (empty($webfinger)) {
540 $webfinger = self::getWebfinger('http://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
541 if (self::$istimeout) {
545 $baseurl = 'https://' . $host;
548 if (empty($webfinger)) {
549 $lrdd = self::hostMeta($host);
550 if (self::$istimeout) {
553 $baseurl = self::$baseurl;
555 $baseurl = 'http://' . $host;
558 Logger::info('URI was not detectable', ['uri' => $uri]);
562 if (empty($webfinger)) {
563 foreach ($lrdd as $type => $template) {
568 $webfinger = self::getWebfinger($template, $type, $uri, $addr);
572 if (empty($webfinger)) {
576 if ($webfinger['detected'] == $addr) {
577 $webfinger['nick'] = $nick;
578 $webfinger['addr'] = $addr;
581 $webfinger['baseurl'] = $baseurl;
587 * Perform network request for webfinger data
589 * @param string $template
590 * @param string $type
592 * @param string $addr
593 * @return array webfinger results
595 private static function getWebfinger(string $template, string $type, string $uri, string $addr): array
597 if (Network::isUrlBlocked($template)) {
598 Logger::info('Domain is blocked', ['url' => $template]);
602 // First try the address because this is the primary purpose of webfinger
605 $path = str_replace('{uri}', urlencode('acct:' . $addr), $template);
606 $webfinger = self::webfinger($path, $type);
607 if (self::$istimeout) {
613 if (empty($webfinger) && $uri != $addr) {
615 $path = str_replace('{uri}', urlencode($uri), $template);
616 $webfinger = self::webfinger($path, $type);
617 if (self::$istimeout) {
622 if (empty($webfinger)) {
626 return ['webfinger' => $webfinger, 'detected' => $detected];
630 * Fetch information (protocol endpoints and user information) about a given uri
632 * This function is only called by the "uri" function that adds caching and rearranging of data.
634 * @param string $uri Address that should be probed
635 * @param string $network Test for this specific network
636 * @param integer $uid User ID for the probe (only used for mails)
637 * @param array $ap_profile Previously probed AP profile
638 * @return array URI data
639 * @throws HTTPException\InternalServerErrorException
641 private static function detect(string $uri, string $network, int $uid, array $ap_profile): array
645 'network' => $network,
650 Hook::callAll('probe_detect', $hookData);
652 if (isset($hookData['result'])) {
653 return is_array($hookData['result']) ? $hookData['result'] : [];
656 $parts = parse_url($uri);
657 if (empty($parts['scheme']) && empty($parts['host']) && !strstr($parts['path'], '@')) {
658 Logger::info('URI was not detectable', ['uri' => $uri]);
662 // If the URI starts with "mailto:" then jump directly to the mail detection
663 if (strpos($uri, 'mailto:') !== false) {
664 $uri = str_replace('mailto:', '', $uri);
665 return self::mail($uri, $uid);
668 if ($network == Protocol::MAIL) {
669 return self::mail($uri, $uid);
672 Logger::info('Probing start', ['uri' => $uri]);
674 if (!empty($ap_profile['addr']) && ($ap_profile['addr'] != $uri)) {
675 $data = self::getWebfingerArray($ap_profile['addr']);
679 $data = self::getWebfingerArray($uri);
683 if (!empty($parts['scheme'])) {
684 return self::feed($uri);
685 } elseif (!empty($uid)) {
686 return self::mail($uri, $uid);
692 $webfinger = $data['webfinger'];
693 $nick = $data['nick'] ?? '';
694 $addr = $data['addr'] ?? '';
695 $baseurl = $data['baseurl'] ?? '';
699 if (in_array($network, ['', Protocol::DFRN])) {
700 $result = self::dfrn($webfinger);
702 if ((!$result && ($network == '')) || ($network == Protocol::DIASPORA)) {
703 $result = self::diaspora($webfinger);
705 if ((!$result && ($network == '')) || ($network == Protocol::OSTATUS)) {
706 $result = self::ostatus($webfinger);
708 if (in_array($network, ['', Protocol::ZOT])) {
709 $result = self::zot($webfinger, $result, $baseurl);
711 if ((!$result && ($network == '')) || ($network == Protocol::PUMPIO)) {
712 $result = self::pumpio($webfinger, $addr);
714 if (empty($result['network']) && empty($ap_profile['network']) || ($network == Protocol::FEED)) {
715 $result = self::feed($uri);
717 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
718 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
719 if ((empty($result['nick']) || (strstr($result['nick'], ' '))) && ($nick != '')) {
720 $result['nick'] = $nick;
723 if (empty($result['addr']) && ($addr != '')) {
724 $result['addr'] = $addr;
728 $result = self::getSubscribeLink($result, $webfinger);
730 if (empty($result['network'])) {
731 $result['network'] = Protocol::PHANTOM;
734 if (empty($result['baseurl']) && !empty($baseurl)) {
735 $result['baseurl'] = $baseurl;
738 if (empty($result['url'])) {
739 $result['url'] = $uri;
742 Logger::info('Probing done', ['uri' => $uri, 'network' => $result['network']]);
748 * Check for Zot contact
750 * @param array $webfinger Webfinger data
751 * @param array $data previously probed data
752 * @param string $baseUrl Base URL
753 * @return array Zot data
754 * @throws HTTPException\InternalServerErrorException
756 private static function zot(array $webfinger, array $data, string $baseurl): array
758 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
759 foreach ($webfinger['aliases'] as $alias) {
760 if (substr($alias, 0, 5) == 'acct:') {
761 $data['addr'] = substr($alias, 5);
766 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
767 $data['addr'] = substr($webfinger['subject'], 5);
771 foreach ($webfinger['links'] as $link) {
772 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
773 $zot_url = $link['href'];
777 if (empty($zot_url) && !empty($data['addr']) && !empty($baseurl)) {
778 $condition = ['nurl' => Strings::normaliseLink($baseurl), 'platform' => ['hubzilla']];
779 if (!DBA::exists('gserver', $condition)) {
782 $zot_url = $baseurl . '/.well-known/zot-info?address=' . $data['addr'];
785 if (empty($zot_url)) {
789 $data = self::pollZot($zot_url, $data);
791 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
792 foreach ($webfinger['aliases'] as $alias) {
793 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
794 $data['alias'] = $alias;
802 public static function pollZot(string $url, array $data): array
804 $curlResult = DI::httpClient()->get($url, HttpClientAccept::JSON);
805 if ($curlResult->isTimeout()) {
808 $content = $curlResult->getBody();
813 $json = json_decode($content, true);
814 if (!is_array($json)) {
818 if (empty($data['network'])) {
819 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
820 $data['network'] = Protocol::ZOT;
821 } elseif (!isset($json['protocols'])) {
822 $data['network'] = Protocol::ZOT;
826 if (!empty($json['guid']) && empty($data['guid'])) {
827 $data['guid'] = $json['guid'];
829 if (!empty($json['key']) && empty($data['pubkey'])) {
830 $data['pubkey'] = $json['key'];
832 if (!empty($json['name'])) {
833 $data['name'] = $json['name'];
835 if (!empty($json['photo'])) {
836 $data['photo'] = $json['photo'];
837 if (!empty($json['photo_updated'])) {
838 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
841 if (!empty($json['address'])) {
842 $data['addr'] = $json['address'];
844 if (!empty($json['url'])) {
845 $data['url'] = $json['url'];
847 if (!empty($json['connections_url'])) {
848 $data['poco'] = $json['connections_url'];
850 if (isset($json['searchable'])) {
851 $data['hide'] = !$json['searchable'];
853 if (!empty($json['public_forum'])) {
854 $data['community'] = $json['public_forum'];
855 $data['account-type'] = User::PAGE_FLAGS_COMMUNITY;
858 if (!empty($json['profile'])) {
859 $profile = $json['profile'];
860 if (!empty($profile['description'])) {
861 $data['about'] = $profile['description'];
863 if (!empty($profile['keywords'])) {
864 $keywords = implode(', ', $profile['keywords']);
865 if (!empty($keywords)) {
866 $data['keywords'] = $keywords;
871 if (!empty($profile['region'])) {
872 $loc['region'] = $profile['region'];
874 if (!empty($profile['country'])) {
875 $loc['country-name'] = $profile['country'];
877 $location = Profile::formatLocation($loc);
878 if (!empty($location)) {
879 $data['location'] = $location;
887 * Perform a webfinger request.
889 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
891 * @param string $url Address that should be probed
892 * @param string $type type
893 * @return array webfinger data
894 * @throws HTTPException\InternalServerErrorException
896 public static function webfinger(string $url, string $type): array
898 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
900 $curlResult = DI::httpClient()->get($url, $type, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
901 if ($curlResult->isTimeout()) {
902 self::$istimeout = true;
905 $data = $curlResult->getBody();
907 $webfinger = json_decode($data, true);
908 if (!empty($webfinger)) {
909 if (!isset($webfinger['links'])) {
910 Logger::info('No json webfinger links', ['url' => $url]);
916 // If it is not JSON, maybe it is XML
917 $xrd = XML::parseString($data, true);
918 if (!is_object($xrd)) {
919 Logger::info('No webfinger data retrievable', ['url' => $url]);
923 $xrd_arr = XML::elementToArray($xrd);
924 if (!isset($xrd_arr['xrd']['link'])) {
925 Logger::info('No XML webfinger links', ['url' => $url]);
931 if (!empty($xrd_arr['xrd']['subject'])) {
932 $webfinger['subject'] = $xrd_arr['xrd']['subject'];
935 if (!empty($xrd_arr['xrd']['alias'])) {
936 $webfinger['aliases'] = $xrd_arr['xrd']['alias'];
939 $webfinger['links'] = [];
941 foreach ($xrd_arr['xrd']['link'] as $value => $data) {
942 if (!empty($data['@attributes'])) {
943 $attributes = $data['@attributes'];
944 } elseif ($value == '@attributes') {
950 $webfinger['links'][] = $attributes;
956 * Poll the Friendica specific noscrape page.
958 * "noscrape" is a faster alternative to fetch the data from the hcard.
959 * This functionality was originally created for the directory.
961 * @param string $noscrape_url Link to the noscrape page
962 * @param array $data The already fetched data
963 * @return array noscrape data
964 * @throws HTTPException\InternalServerErrorException
966 private static function pollNoscrape(string $noscrape_url, array $data): array
968 $curlResult = DI::httpClient()->get($noscrape_url, HttpClientAccept::JSON);
969 if ($curlResult->isTimeout()) {
970 self::$istimeout = true;
973 $content = $curlResult->getBody();
975 Logger::info('Empty body', ['url' => $noscrape_url]);
979 $json = json_decode($content, true);
980 if (!is_array($json)) {
981 Logger::info('No json data', ['url' => $noscrape_url]);
985 if (!empty($json['fn'])) {
986 $data['name'] = $json['fn'];
989 if (!empty($json['addr'])) {
990 $data['addr'] = $json['addr'];
993 if (!empty($json['nick'])) {
994 $data['nick'] = $json['nick'];
997 if (!empty($json['guid'])) {
998 $data['guid'] = $json['guid'];
1001 if (!empty($json['comm'])) {
1002 $data['community'] = $json['comm'];
1005 if (!empty($json['tags'])) {
1006 $keywords = implode(', ', $json['tags']);
1007 if ($keywords != '') {
1008 $data['keywords'] = $keywords;
1012 $location = Profile::formatLocation($json);
1014 $data['location'] = $location;
1017 if (!empty($json['about'])) {
1018 $data['about'] = $json['about'];
1021 if (!empty($json['xmpp'])) {
1022 $data['xmpp'] = $json['xmpp'];
1025 if (!empty($json['matrix'])) {
1026 $data['matrix'] = $json['matrix'];
1029 if (!empty($json['key'])) {
1030 $data['pubkey'] = $json['key'];
1033 if (!empty($json['photo'])) {
1034 $data['photo'] = $json['photo'];
1037 if (!empty($json['dfrn-request'])) {
1038 $data['request'] = $json['dfrn-request'];
1041 if (!empty($json['dfrn-confirm'])) {
1042 $data['confirm'] = $json['dfrn-confirm'];
1045 if (!empty($json['dfrn-notify'])) {
1046 $data['notify'] = $json['dfrn-notify'];
1049 if (!empty($json['dfrn-poll'])) {
1050 $data['poll'] = $json['dfrn-poll'];
1053 if (isset($json['hide'])) {
1054 $data['hide'] = (bool)$json['hide'];
1056 $data['hide'] = false;
1063 * Check for valid DFRN data
1065 * @param array $data DFRN data
1067 * @return int Number of errors
1069 public static function validDfrn($data)
1072 if (!isset($data['key'])) {
1075 if (!isset($data['dfrn-request'])) {
1078 if (!isset($data['dfrn-confirm'])) {
1081 if (!isset($data['dfrn-notify'])) {
1084 if (!isset($data['dfrn-poll'])) {
1091 * Fetch data from a DFRN profile page and via "noscrape"
1093 * @param string $profile_link Link to the profile page
1094 * @return array profile data
1095 * @throws HTTPException\InternalServerErrorException
1096 * @throws \ImagickException
1098 public static function profile(string $profile_link): array
1102 Logger::info('Check profile', ['link' => $profile_link]);
1104 // Fetch data via noscrape - this is faster
1105 $noscrape_url = str_replace(['/hcard/', '/profile/'], '/noscrape/', $profile_link);
1106 $data = self::pollNoscrape($noscrape_url, $data);
1108 if (!isset($data['notify'])
1109 || !isset($data['confirm'])
1110 || !isset($data['request'])
1111 || !isset($data['poll'])
1112 || !isset($data['name'])
1113 || !isset($data['photo'])
1115 $data = self::pollHcard($profile_link, $data, true);
1120 if (empty($data['addr']) || empty($data['nick'])) {
1121 $probe_data = self::uri($profile_link);
1122 $data['addr'] = ($data['addr'] ?? '') ?: $probe_data['addr'];
1123 $data['nick'] = ($data['nick'] ?? '') ?: $probe_data['nick'];
1126 $prof_data['addr'] = $data['addr'];
1127 $prof_data['nick'] = $data['nick'];
1128 $prof_data['dfrn-request'] = $data['request'] ?? null;
1129 $prof_data['dfrn-confirm'] = $data['confirm'] ?? null;
1130 $prof_data['dfrn-notify'] = $data['notify'] ?? null;
1131 $prof_data['dfrn-poll'] = $data['poll'] ?? null;
1132 $prof_data['photo'] = $data['photo'] ?? null;
1133 $prof_data['fn'] = $data['name'] ?? null;
1134 $prof_data['key'] = $data['pubkey'] ?? null;
1136 Logger::debug('Result', ['link' => $profile_link, 'data' => $prof_data]);
1142 * Check for DFRN contact
1144 * @param array $webfinger Webfinger data
1145 * @return array DFRN data
1146 * @throws HTTPException\InternalServerErrorException
1148 private static function dfrn(array $webfinger): array
1152 // The array is reversed to take into account the order of preference for same-rel links
1153 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1154 foreach (array_reverse($webfinger['links']) as $link) {
1155 if (($link['rel'] == ActivityNamespace::DFRN) && !empty($link['href'])) {
1156 $data['network'] = Protocol::DFRN;
1157 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1158 $data['poll'] = $link['href'];
1159 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1160 $data['url'] = $link['href'];
1161 } elseif (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1162 $hcard_url = $link['href'];
1163 } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1164 $data['poco'] = $link['href'];
1165 } elseif (($link['rel'] == 'http://webfinger.net/rel/avatar') && !empty($link['href'])) {
1166 $data['photo'] = $link['href'];
1167 } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1168 $data['baseurl'] = trim($link['href'], '/');
1169 } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1170 $data['guid'] = $link['href'];
1171 } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1172 $data['pubkey'] = base64_decode($link['href']);
1174 if (strstr($data['pubkey'], 'RSA ')) {
1175 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1180 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1181 foreach ($webfinger['aliases'] as $alias) {
1182 if (empty($data['url']) && !strstr($alias, '@')) {
1183 $data['url'] = $alias;
1184 } elseif (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
1185 $data['alias'] = $alias;
1186 } elseif (substr($alias, 0, 5) == 'acct:') {
1187 $data['addr'] = substr($alias, 5);
1192 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1193 $data['addr'] = substr($webfinger['subject'], 5);
1196 if (!isset($data['network']) || ($hcard_url == '')) {
1200 // Fetch data via noscrape - this is faster
1201 $noscrape_url = str_replace('/hcard/', '/noscrape/', $hcard_url);
1202 $data = self::pollNoscrape($noscrape_url, $data);
1204 if (isset($data['notify'])
1205 && isset($data['confirm'])
1206 && isset($data['request'])
1207 && isset($data['poll'])
1208 && isset($data['name'])
1209 && isset($data['photo'])
1214 $data = self::pollHcard($hcard_url, $data, true);
1220 * Poll the hcard page (Diaspora and Friendica specific)
1222 * @param string $hcard_url Link to the hcard page
1223 * @param array $data The already fetched data
1224 * @param boolean $dfrn Poll DFRN specific data
1225 * @return array hcard data
1226 * @throws HTTPException\InternalServerErrorException
1228 private static function pollHcard(string $hcard_url, array $data, bool $dfrn = false): array
1230 $curlResult = DI::httpClient()->get($hcard_url, HttpClientAccept::HTML);
1231 if ($curlResult->isTimeout()) {
1232 self::$istimeout = true;
1235 $content = $curlResult->getBody();
1236 if (empty($content)) {
1240 $doc = new DOMDocument();
1241 if (!@$doc->loadHTML($content)) {
1245 $xpath = new DomXPath($doc);
1247 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1248 if (!is_object($vcards)) {
1252 if (!isset($data['baseurl'])) {
1253 $data['baseurl'] = '';
1256 if ($vcards->length > 0) {
1257 $vcard = $vcards->item(0);
1259 // We have to discard the guid from the hcard in favour of the guid from lrdd
1260 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1261 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1262 if (($search->length > 0) && empty($data['guid'])) {
1263 $data['guid'] = $search->item(0)->nodeValue;
1266 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1267 if ($search->length > 0) {
1268 $data['nick'] = $search->item(0)->nodeValue;
1271 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1272 if ($search->length > 0) {
1273 $data['name'] = $search->item(0)->nodeValue;
1276 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1277 if ($search->length > 0) {
1278 $data['searchable'] = $search->item(0)->nodeValue;
1281 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1282 if ($search->length > 0) {
1283 $data['pubkey'] = $search->item(0)->nodeValue;
1284 if (strstr($data['pubkey'], 'RSA ')) {
1285 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1289 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1290 if ($search->length > 0) {
1291 $data['baseurl'] = trim($search->item(0)->nodeValue, '/');
1296 if (!empty($vcard)) {
1297 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1298 foreach ($photos as $photo) {
1300 foreach ($photo->attributes as $attribute) {
1301 $attr[$attribute->name] = trim($attribute->value);
1304 if (isset($attr['src']) && isset($attr['width'])) {
1305 $avatar[$attr['width']] = $attr['src'];
1308 // We don't have a width. So we just take everything that we got.
1309 // This is a Hubzilla workaround which doesn't send a width.
1310 if ((sizeof($avatar) == 0) && !empty($attr['src'])) {
1311 $avatar[] = $attr['src'];
1316 if (sizeof($avatar)) {
1318 $data['photo'] = self::fixAvatar(array_pop($avatar), $data['baseurl']);
1322 // Poll DFRN specific data
1323 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1324 if ($search->length > 0) {
1325 foreach ($search as $link) {
1326 //$data['request'] = $search->item(0)->nodeValue;
1328 foreach ($link->attributes as $attribute) {
1329 $attr[$attribute->name] = trim($attribute->value);
1332 $data[substr($attr['rel'], 5)] = $attr['href'];
1336 // Older Friendica versions had used the "uid" field differently than newer versions
1337 if (!empty($data['nick']) && !empty($data['guid']) && ($data['nick'] == $data['guid'])) {
1338 unset($data['guid']);
1347 * Check for Diaspora contact
1349 * @param array $webfinger Webfinger data
1350 * @return array Diaspora data
1351 * @throws HTTPException\InternalServerErrorException
1353 private static function diaspora(array $webfinger): array
1358 // The array is reversed to take into account the order of preference for same-rel links
1359 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1360 foreach (array_reverse($webfinger['links']) as $link) {
1361 if (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1362 $hcard_url = $link['href'];
1363 } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1364 $data['baseurl'] = trim($link['href'], '/');
1365 } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1366 $data['guid'] = $link['href'];
1367 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1368 $data['url'] = $link['href'];
1369 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && empty($link['type']) && !empty($link['href'])) {
1370 $profile_url = $link['href'];
1371 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1372 $data['poll'] = $link['href'];
1373 } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1374 $data['poco'] = $link['href'];
1375 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1376 $data['notify'] = $link['href'];
1377 } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1378 $data['pubkey'] = base64_decode($link['href']);
1380 if (strstr($data['pubkey'], 'RSA ')) {
1381 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1386 if (empty($data['url']) && !empty($profile_url)) {
1387 $data['url'] = $profile_url;
1390 if (empty($data['url']) || empty($hcard_url)) {
1394 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1395 foreach ($webfinger['aliases'] as $alias) {
1396 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data['url']) && ! strstr($alias, '@')) {
1397 $data['alias'] = $alias;
1398 } elseif (substr($alias, 0, 5) == 'acct:') {
1399 $data['addr'] = substr($alias, 5);
1404 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1405 $data['addr'] = substr($webfinger['subject'], 5);
1408 // Fetch further information from the hcard
1409 $data = self::pollHcard($hcard_url, $data);
1415 if (!empty($data['url'])
1416 && !empty($data['guid'])
1417 && !empty($data['baseurl'])
1418 && !empty($data['pubkey'])
1419 && !empty($hcard_url)
1421 $data['network'] = Protocol::DIASPORA;
1422 $data['manually-approve'] = false;
1424 // The Diaspora handle must always be lowercase
1425 if (!empty($data['addr'])) {
1426 $data['addr'] = strtolower($data['addr']);
1429 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1430 $data['notify'] = $data['baseurl'] . '/receive/users/' . $data['guid'];
1431 $data['batch'] = $data['baseurl'] . '/receive/public';
1440 * Check for OStatus contact
1442 * @param array $webfinger Webfinger data
1443 * @param bool $short Short detection mode
1444 * @return array|bool OStatus data or "false" on error or "true" on short mode
1445 * @throws HTTPException\InternalServerErrorException
1447 private static function ostatus(array $webfinger, bool $short = false)
1451 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1452 foreach ($webfinger['aliases'] as $alias) {
1453 if (strstr($alias, '@') && !strstr(Strings::normaliseLink($alias), 'http://')) {
1454 $data['addr'] = str_replace('acct:', '', $alias);
1459 if (!empty($webfinger['subject']) && strstr($webfinger['subject'], '@')
1460 && !strstr(Strings::normaliseLink($webfinger['subject']), 'http://')
1462 $data['addr'] = str_replace('acct:', '', $webfinger['subject']);
1465 if (!empty($webfinger['links'])) {
1466 // The array is reversed to take into account the order of preference for same-rel links
1467 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1468 foreach (array_reverse($webfinger['links']) as $link) {
1469 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1470 && (($link['type'] ?? '') == 'text/html')
1471 && ($link['href'] != '')
1473 $data['url'] = $data['alias'] = $link['href'];
1474 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1475 $data['notify'] = $link['href'];
1476 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1477 $data['poll'] = $link['href'];
1478 } elseif (($link['rel'] == 'magic-public-key') && !empty($link['href'])) {
1479 $pubkey = $link['href'];
1481 if (substr($pubkey, 0, 5) === 'data:') {
1482 if (strstr($pubkey, ',')) {
1483 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1485 $pubkey = substr($pubkey, 5);
1487 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1488 $curlResult = DI::httpClient()->get($pubkey, HttpClientAccept::MAGIC_KEY);
1489 if ($curlResult->isTimeout()) {
1490 self::$istimeout = true;
1491 return $short ? false : [];
1493 Logger::debug('Fetched public key', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $pubkey]);
1494 $pubkey = $curlResult->getBody();
1497 $key = explode('.', $pubkey);
1499 if (sizeof($key) >= 3) {
1500 $m = Strings::base64UrlDecode($key[1]);
1501 $e = Strings::base64UrlDecode($key[2]);
1502 $data['pubkey'] = Crypto::meToPem($m, $e);
1508 if (isset($data['notify']) && isset($data['pubkey'])
1509 && isset($data['poll'])
1510 && isset($data['url'])
1512 $data['network'] = Protocol::OSTATUS;
1513 $data['manually-approve'] = false;
1515 return $short ? false : [];
1522 // Fetch all additional data from the feed
1523 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::FEED_XML);
1524 if ($curlResult->isTimeout()) {
1525 self::$istimeout = true;
1528 $feed = $curlResult->getBody();
1529 $feed_data = Feed::import($feed);
1534 if (!empty($feed_data['header']['author-name'])) {
1535 $data['name'] = $feed_data['header']['author-name'];
1537 if (!empty($feed_data['header']['author-nick'])) {
1538 $data['nick'] = $feed_data['header']['author-nick'];
1540 if (!empty($feed_data['header']['author-avatar'])) {
1541 $data['photo'] = self::fixAvatar($feed_data['header']['author-avatar'], $data['url']);
1543 if (!empty($feed_data['header']['author-id'])) {
1544 $data['alias'] = $feed_data['header']['author-id'];
1546 if (!empty($feed_data['header']['author-location'])) {
1547 $data['location'] = $feed_data['header']['author-location'];
1549 if (!empty($feed_data['header']['author-about'])) {
1550 $data['about'] = $feed_data['header']['author-about'];
1552 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1553 // So we take the value that we just fetched, although the other one worked as well
1554 if (!empty($feed_data['header']['author-link'])) {
1555 $data['url'] = $feed_data['header']['author-link'];
1558 if ($data['url'] == $data['alias']) {
1559 $data['alias'] = '';
1562 /// @todo Fetch location and "about" from the feed as well
1567 * Fetch data from a pump.io profile page
1569 * @param string $profile_link Link to the profile page
1570 * @return array Profile data
1572 private static function pumpioProfileData(string $profile_link): array
1574 $curlResult = DI::httpClient()->get($profile_link, HttpClientAccept::HTML);
1575 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
1579 $doc = new DOMDocument();
1580 if (!@$doc->loadHTML($curlResult->getBody())) {
1584 $xpath = new DomXPath($doc);
1587 $data['name'] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1589 if ($data['name'] == '') {
1590 // This is ugly - but pump.io doesn't seem to know a better way for it
1591 $data['name'] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1592 $pos = strpos($data['name'], chr(10));
1594 $data['name'] = trim(substr($data['name'], 0, $pos));
1598 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1600 if ($data['location'] == '') {
1601 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1604 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1606 if ($data['about'] == '') {
1607 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1610 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1612 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1615 foreach ($avatar->attributes as $attribute) {
1616 if ($attribute->name == 'src') {
1617 $data['photo'] = trim($attribute->value);
1626 * Check for pump.io contact
1628 * @param array $webfinger Webfinger data
1629 * @param string $addr
1630 * @return array pump.io data
1632 private static function pumpio(array $webfinger, string $addr): array
1635 // The array is reversed to take into account the order of preference for same-rel links
1636 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1637 foreach (array_reverse($webfinger['links']) as $link) {
1638 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1639 && (($link['type'] ?? '') == 'text/html')
1640 && ($link['href'] != '')
1642 $data['url'] = $link['href'];
1643 } elseif (($link['rel'] == 'activity-inbox') && ($link['href'] != '')) {
1644 $data['notify'] = $link['href'];
1645 } elseif (($link['rel'] == 'activity-outbox') && ($link['href'] != '')) {
1646 $data['poll'] = $link['href'];
1647 } elseif (($link['rel'] == 'dialback') && ($link['href'] != '')) {
1648 $data['dialback'] = $link['href'];
1651 if (isset($data['poll']) && isset($data['notify'])
1652 && isset($data['dialback'])
1653 && isset($data['url'])
1655 // by now we use these fields only for the network type detection
1656 // So we unset all data that isn't used at the moment
1657 unset($data['dialback']);
1659 $data['network'] = Protocol::PUMPIO;
1664 $profile_data = self::pumpioProfileData($data['url']);
1666 if (!$profile_data) {
1670 $data = array_merge($data, $profile_data);
1672 if (($addr != '') && ($data['name'] != '')) {
1673 $name = trim(str_replace($addr, '', $data['name']));
1675 $data['name'] = $name;
1683 * Checks HTML page for RSS feed link
1685 * @param string $url Page link
1686 * @param string $body Page body string
1687 * @return string|false Feed link or false if body was invalid HTML document
1689 public static function getFeedLink(string $url, string $body)
1695 $doc = new DOMDocument();
1696 if (!@$doc->loadHTML($body)) {
1700 $xpath = new DOMXPath($doc);
1702 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1704 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1710 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1712 * Loosely based on RFC 1808
1714 * @see https://tools.ietf.org/html/rfc1808
1716 * @param string $href The potential relative href found in the HTML document
1717 * @param string $base The HTML document URL
1718 * @param DOMXPath $xpath The HTML document XPath
1719 * @return string Absolute URL
1721 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath): string
1723 if (filter_var($href, FILTER_VALIDATE_URL)) {
1727 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1729 $baseParts = parse_url($base);
1730 if (empty($baseParts['host'])) {
1734 // Naked domain case (scheme://basehost)
1735 $path = $baseParts['path'] ?? '/';
1737 // Remove the filename part of the path if it exists (/base/path/file)
1738 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1740 $hrefParts = parse_url($href);
1742 if (!empty($hrefParts['path'])) {
1743 // Root path case (/path) including relative scheme case (//host/path)
1744 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1745 $path = $hrefParts['path'];
1747 $path = $path . '/' . $hrefParts['path'];
1749 // Resolve arbitrary relative path
1750 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1751 $parts = array_filter(explode('/', $path), 'strlen');
1753 foreach ($parts as $part) {
1754 if ('.' == $part) continue;
1755 if ('..' == $part) {
1756 array_pop($absolutes);
1758 $absolutes[] = $part;
1762 $path = '/' . implode('/', $absolutes);
1766 // Relative scheme case (//host/path)
1767 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1768 $baseParts['path'] = $path;
1769 unset($baseParts['query']);
1770 unset($baseParts['fragment']);
1772 return Network::unparseURL($baseParts);
1776 * Check for feed contact
1778 * @param string $url Profile link
1779 * @param boolean $probe Do a probe if the page contains a feed link
1780 * @return array feed data
1781 * @throws HTTPException\InternalServerErrorException
1783 private static function feed(string $url, bool $probe = true): array
1785 $curlResult = DI::httpClient()->get($url, HttpClientAccept::FEED_XML);
1786 if ($curlResult->isTimeout()) {
1787 self::$istimeout = true;
1790 $feed = $curlResult->getBody();
1791 $feed_data = Feed::import($feed);
1798 $feed_url = self::getFeedLink($url, $feed);
1804 return self::feed($feed_url, false);
1807 if (!empty($feed_data['header']['author-name'])) {
1808 $data['name'] = $feed_data['header']['author-name'];
1811 if (!empty($feed_data['header']['author-nick'])) {
1812 $data['nick'] = $feed_data['header']['author-nick'];
1815 if (!empty($feed_data['header']['author-avatar'])) {
1816 $data['photo'] = $feed_data['header']['author-avatar'];
1819 if (!empty($feed_data['header']['author-id'])) {
1820 $data['alias'] = $feed_data['header']['author-id'];
1823 $data['url'] = $url;
1824 $data['poll'] = $url;
1826 $data['network'] = Protocol::FEED;
1832 * Check for mail contact
1834 * @param string $uri Profile link
1835 * @param integer $uid User ID
1836 * @return array mail data
1837 * @throws \Exception
1839 private static function mail(string $uri, int $uid): array
1841 if (!Network::isEmailDomainValid($uri)) {
1849 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1851 $condition = ["`uid` = ? AND `server` != ''", $uid];
1852 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1853 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1855 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1859 $mailbox = Email::constructMailboxName($mailacct);
1861 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1862 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1867 $msgs = Email::poll($mbox, $uri);
1868 Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
1870 if (!count($msgs)) {
1874 $phost = substr($uri, strpos($uri, '@') + 1);
1877 $data['addr'] = $uri;
1878 $data['network'] = Protocol::MAIL;
1879 $data['name'] = substr($uri, 0, strpos($uri, '@'));
1880 $data['nick'] = $data['name'];
1881 $data['photo'] = Network::lookupAvatarByEmail($uri);
1882 $data['url'] = 'mailto:'.$uri;
1883 $data['notify'] = 'smtp ' . Strings::getRandomHex();
1884 $data['poll'] = 'email ' . Strings::getRandomHex();
1886 $x = Email::messageMeta($mbox, $msgs[0]);
1887 if (stristr($x[0]->from, $uri)) {
1888 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1889 } elseif (stristr($x[0]->to, $uri)) {
1890 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1893 foreach ($adr as $feadr) {
1894 if ((strcasecmp($feadr->mailbox, $data['name']) == 0)
1895 &&(strcasecmp($feadr->host, $phost) == 0)
1896 && (strlen($feadr->personal))
1898 $personal = imap_mime_header_decode($feadr->personal);
1900 foreach ($personal as $perspart) {
1901 if ($perspart->charset != 'default') {
1902 $data['name'] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1904 $data['name'] .= $perspart->text;
1910 if (!empty($mbox)) {
1917 * Mix two paths together to possibly fix missing parts
1919 * @param string $avatar Path to the avatar
1920 * @param string $base Another path that is hopefully complete
1921 * @return string fixed avatar path
1922 * @throws \Exception
1924 public static function fixAvatar(string $avatar, string $base): string
1926 $base_parts = parse_url($base);
1928 // Remove all parts that could create a problem
1929 unset($base_parts['path']);
1930 unset($base_parts['query']);
1931 unset($base_parts['fragment']);
1933 $avatar_parts = parse_url($avatar);
1936 $parts = array_merge($base_parts, $avatar_parts);
1938 // And put them together again
1939 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1940 $host = isset($parts['host']) ? $parts['host'] : '';
1941 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1942 $path = isset($parts['path']) ? $parts['path'] : '';
1943 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1944 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1946 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1948 Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
1954 * Fetch the last date that the contact had posted something (publically)
1956 * @param array $data probing result
1957 * @return string last activity
1959 public static function getLastUpdate(array $data): string
1961 $uid = User::getIdForURL($data['url']);
1963 $contact = Contact::selectFirst(['url', 'last-item'], ['self' => true, 'uid' => $uid]);
1964 if (!empty($contact['last-item'])) {
1965 return $contact['last-item'];
1969 if ($lastUpdate = self::updateFromNoScrape($data)) {
1973 if (!empty($data['outbox'])) {
1974 return self::updateFromOutbox($data['outbox'], $data);
1975 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
1976 return self::updateFromOutbox($data['poll'], $data);
1977 } elseif (!empty($data['poll'])) {
1978 return self::updateFromFeed($data);
1985 * Fetch the last activity date from the "noscrape" endpoint
1987 * @param array $data Probing result
1988 * @return string last activity or true if update was successful or the server was unreachable
1990 private static function updateFromNoScrape(array $data): string
1992 if (empty($data['baseurl'])) {
1996 // Check the 'noscrape' endpoint when it is a Friendica server
1997 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
1998 Strings::normaliseLink($data['baseurl'])]);
1999 if (!DBA::isResult($gserver)) {
2003 $curlResult = DI::httpClient()->get($gserver['noscrape'] . '/' . $data['nick'], HttpClientAccept::JSON);
2005 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
2006 $noscrape = json_decode($curlResult->getBody(), true);
2007 if (!empty($noscrape) && !empty($noscrape['updated'])) {
2008 return DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2016 * Fetch the last activity date from an ActivityPub Outbox
2018 * @param string $feed
2019 * @param array $data Probing result
2020 * @return string last activity
2021 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2023 private static function updateFromOutbox(string $feed, array $data): string
2025 $outbox = ActivityPub::fetchContent($feed);
2026 if (empty($outbox)) {
2030 if (!empty($outbox['orderedItems'])) {
2031 $items = $outbox['orderedItems'];
2032 } elseif (!empty($outbox['first']['orderedItems'])) {
2033 $items = $outbox['first']['orderedItems'];
2034 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2035 return self::updateFromOutbox($outbox['first']['href'], $data);
2036 } elseif (!empty($outbox['first'])) {
2037 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2038 return self::updateFromOutbox($outbox['first'], $data);
2040 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2048 foreach ($items as $activity) {
2049 if (!empty($activity['published'])) {
2050 $published = DateTimeFormat::utc($activity['published']);
2051 } elseif (!empty($activity['object']['published'])) {
2052 $published = DateTimeFormat::utc($activity['object']['published']);
2057 if ($last_updated < $published) {
2058 $last_updated = $published;
2062 if (!empty($last_updated)) {
2063 return $last_updated;
2070 * Fetch the last activity date from an XML feed
2072 * @param array $data Probing result
2073 * @return string last activity
2075 private static function updateFromFeed(array $data): string
2077 // Search for the newest entry in the feed
2078 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::ATOM_XML);
2079 if (!$curlResult->isSuccess() || !$curlResult->getBody()) {
2083 $doc = new DOMDocument();
2084 @$doc->loadXML($curlResult->getBody());
2086 $xpath = new DOMXPath($doc);
2087 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2089 $entries = $xpath->query('/atom:feed/atom:entry');
2093 foreach ($entries as $entry) {
2094 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2095 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
2096 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2097 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2099 if (empty($published) || empty($updated)) {
2100 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2104 if ($last_updated < $published) {
2105 $last_updated = $published;
2108 if ($last_updated < $updated) {
2109 $last_updated = $updated;
2113 if (!empty($last_updated)) {
2114 return $last_updated;
2121 * Probe data from local profiles without network traffic
2123 * @param string $url
2124 * @return array probed data
2125 * @throws HTTPException\InternalServerErrorException
2126 * @throws HTTPException\NotFoundException
2128 private static function localProbe(string $url): array
2131 $uid = User::getIdForURL($url);
2133 throw new HTTPException\NotFoundException('User not found.');
2136 $owner = User::getOwnerDataById($uid);
2137 $approfile = ActivityPub\Transmitter::getProfile($uid);
2139 if (empty($owner['gsid'])) {
2140 $owner['gsid'] = GServer::getID($approfile['generator']['url']);
2144 'name' => $owner['name'], 'nick' => $owner['nick'], 'guid' => $approfile['diaspora:guid'] ?? '',
2145 'url' => $owner['url'], 'addr' => $owner['addr'], 'alias' => $owner['alias'],
2146 'photo' => User::getAvatarUrl($owner),
2147 'header' => $owner['header'] ? Contact::getHeaderUrlForId($owner['id'], $owner['updated']) : '',
2148 'account-type' => $owner['contact-type'], 'community' => ($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY),
2149 'keywords' => $owner['keywords'], 'location' => $owner['location'], 'about' => $owner['about'],
2150 'xmpp' => $owner['xmpp'], 'matrix' => $owner['matrix'],
2151 'hide' => !$owner['net-publish'], 'batch' => '', 'notify' => $owner['notify'],
2152 'poll' => $owner['poll'], 'request' => $owner['request'], 'confirm' => $owner['confirm'],
2153 'subscribe' => $approfile['generator']['url'] . '/follow?url={uri}', 'poco' => $owner['poco'],
2154 'following' => $approfile['following'], 'followers' => $approfile['followers'],
2155 'inbox' => $approfile['inbox'], 'outbox' => $approfile['outbox'],
2156 'sharedinbox' => $approfile['endpoints']['sharedInbox'], 'network' => Protocol::DFRN,
2157 'pubkey' => $owner['upubkey'], 'baseurl' => $approfile['generator']['url'], 'gsid' => $owner['gsid'],
2158 'manually-approve' => in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])
2160 } catch (Exception $e) {
2161 // Default values for non existing targets
2163 'name' => $url, 'nick' => $url, 'url' => $url, 'network' => Protocol::PHANTOM,
2164 'photo' => DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO
2168 return self::rearrangeData($data);