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 * Remove stuff from an URI that doesn't belong there
63 * @param string $rawUri
64 * @return string Cleaned URI
66 public static function cleanURI(string $rawUri): string
68 // At first remove leading and trailing junk
69 $rawUri = trim($rawUri, "@#?:/ \t\n\r\0\x0B");
71 $rawUri = Network::convertToIdn($rawUri);
73 $uri = new Uri($rawUri);
74 if (!$uri->getScheme()) {
75 return $uri->__toString();
78 // Remove the URL fragment, since these shouldn't be part of any profile URL
79 $uri = $uri->withFragment('');
81 return $uri->__toString();
85 * Rearrange the array so that it always has the same order
87 * @param array $data Unordered data
88 * @return array Ordered data
90 private static function rearrangeData(array $data): array
92 $fields = ['name', 'nick', 'guid', 'url', 'addr', 'alias', 'photo', 'header',
93 'account-type', 'community', 'keywords', 'location', 'about', 'xmpp', 'matrix',
94 'hide', 'batch', 'notify', 'poll', 'request', 'confirm', 'subscribe', 'poco',
95 'following', 'followers', 'inbox', 'outbox', 'sharedinbox',
96 'priority', 'network', 'pubkey', 'manually-approve', 'baseurl', 'gsid'];
98 $numeric_fields = ['gsid', 'hide', 'account-type', 'manually-approve'];
101 foreach ($fields as $field) {
102 if (isset($data[$field])) {
103 if (in_array($field, $numeric_fields)) {
104 $newdata[$field] = (int)$data[$field];
106 $newdata[$field] = $data[$field];
108 } elseif (!in_array($field, $numeric_fields)) {
109 $newdata[$field] = '';
111 $newdata[$field] = null;
115 // We don't use the "priority" field anymore and replace it with a dummy.
116 $newdata['priority'] = 0;
122 * Check if the hostname belongs to the own server
124 * @param string $host The hostname that is to be checked
125 * @return bool Does the testes hostname belongs to the own server?
127 private static function ownHost(string $host): bool
129 $own_host = DI::baseUrl()->getHostname();
131 $parts = parse_url($host);
133 if (!isset($parts['scheme'])) {
134 $parts = parse_url('http://'.$host);
137 if (!isset($parts['host'])) {
140 return $parts['host'] == $own_host;
144 * Probes for webfinger path via 'host-meta'
146 * We have to check if the servers in the future still will offer this.
147 * It seems as if it was dropped from the standard.
149 * @param string $host The host part of an url
150 * @return array with template and type of the webfinger template for JSON or XML
151 * @throws HTTPException\InternalServerErrorException
153 private static function hostMeta(string $host): array
155 // Reset the static variable
158 // Handles the case when the hostname contains the scheme
159 if (!parse_url($host, PHP_URL_SCHEME)) {
160 $ssl_url = 'https://' . $host . '/.well-known/host-meta';
161 $url = 'http://' . $host . '/.well-known/host-meta';
163 $ssl_url = $host . '/.well-known/host-meta';
167 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
169 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
172 $curlResult = DI::httpClient()->get($ssl_url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
173 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
174 if ($curlResult->isSuccess()) {
175 $xml = $curlResult->getBody();
176 $xrd = XML::parseString($xml, true);
178 $host_url = 'https://' . $host;
182 } elseif ($curlResult->isTimeout()) {
183 Logger::info('Probing timeout', ['url' => $ssl_url]);
184 self::$istimeout = true;
188 if (!is_object($xrd) && !empty($url)) {
189 $curlResult = DI::httpClient()->get($url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
190 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
191 if ($curlResult->isTimeout()) {
192 Logger::info('Probing timeout', ['url' => $url]);
193 self::$istimeout = true;
195 } elseif ($connection_error && $ssl_connection_error) {
196 self::$istimeout = true;
200 $xml = $curlResult->getBody();
201 $xrd = XML::parseString($xml, true);
202 $host_url = 'http://'.$host;
204 if (!is_object($xrd)) {
205 Logger::info('No xrd object found', ['host' => $host]);
209 $links = XML::elementToArray($xrd);
210 if (!isset($links['xrd']['link'])) {
211 Logger::info('No xrd data found', ['host' => $host]);
217 foreach ($links['xrd']['link'] as $value => $link) {
218 if (!empty($link['@attributes'])) {
219 $attributes = $link['@attributes'];
220 } elseif ($value == '@attributes') {
226 if (!empty($attributes['rel']) && $attributes['rel'] == 'lrdd' && !empty($attributes['template'])) {
227 $type = (empty($attributes['type']) ? '' : $attributes['type']);
229 $lrdd[$type] = $attributes['template'];
233 if (Network::isUrlBlocked($host_url)) {
234 Logger::info('Domain is blocked', ['url' => $host]);
238 self::$baseurl = $host_url;
240 Logger::info('Probing successful', ['host' => $host]);
246 * Check an URI for LRDD data
248 * @param string $uri Address that should be probed
249 * @return array uri data
250 * @throws HTTPException\InternalServerErrorException
252 public static function lrdd(string $uri): array
254 $data = self::getWebfingerArray($uri);
258 $webfinger = $data['webfinger'];
260 if (empty($webfinger['links'])) {
261 Logger::info('No webfinger links found', ['uri' => $uri]);
267 foreach ($webfinger['links'] as $link) {
268 $data[] = ['@attributes' => $link];
271 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
272 foreach ($webfinger['aliases'] as $alias) {
286 * Fetch information (protocol endpoints and user information) about a given uri
288 * @param string $uri Address that should be probed
289 * @param string $network Test for this specific network
290 * @param integer $uid User ID for the probe (only used for mails)
291 * @param boolean $cache Use cached values?
293 * @return array uri data
294 * @throws HTTPException\InternalServerErrorException
295 * @throws \ImagickException
297 public static function uri($uri, $network = '', $uid = -1)
299 // Local profiles aren't probed via network
300 if (empty($network) && Contact::isLocal($uri)) {
301 $data = self::localProbe($uri);
311 if (empty($network) || ($network == Protocol::ACTIVITYPUB)) {
312 $ap_profile = ActivityPub::probeProfile($uri);
317 self::$istimeout = false;
319 if ($network != Protocol::ACTIVITYPUB) {
320 $data = self::detect($uri, $network, $uid, $ap_profile);
321 if (!is_array($data)) {
324 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
326 } elseif (!empty($ap_profile)) {
327 $ap_profile['batch'] = '';
328 $data = array_merge($ap_profile, $data);
334 if (!isset($data['url'])) {
338 if (empty($data['photo'])) {
339 $data['photo'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
342 if (empty($data['name'])) {
343 if (!empty($data['nick'])) {
344 $data['name'] = $data['nick'];
347 if (empty($data['name'])) {
348 $data['name'] = $data['url'];
352 if (empty($data['nick'])) {
353 $data['nick'] = strtolower($data['name']);
355 if (strpos($data['nick'], ' ')) {
356 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
360 if (!empty($data['baseurl']) && empty($data['gsid'])) {
361 $data['gsid'] = GServer::getID($data['baseurl']);
364 if (empty($data['network'])) {
365 $data['network'] = Protocol::PHANTOM;
368 // Ensure that local connections always are DFRN
369 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
370 $data['network'] = Protocol::DFRN;
373 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
374 $data['hide'] = self::getHideStatus($data['url']);
377 return self::rearrangeData($data);
382 * Fetches the "hide" status from the profile
384 * @param string $url URL of the profile
385 * @return boolean "hide" status
387 private static function getHideStatus(string $url): bool
389 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::CONTENT_LENGTH => 1000000]);
390 if (!$curlResult->isSuccess()) {
394 // If it isn't a HTML file then exit
395 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
399 $body = $curlResult->getBody();
404 $doc = new DOMDocument();
405 @$doc->loadHTML($body);
407 $xpath = new DOMXPath($doc);
409 $list = $xpath->query('//meta[@name]');
410 foreach ($list as $node) {
412 if ($node->attributes->length) {
413 foreach ($node->attributes as $attribute) {
414 $meta_tag[$attribute->name] = $attribute->value;
418 if (empty($meta_tag['content'])) {
422 $content = strtolower(trim($meta_tag['content']));
424 switch (strtolower(trim($meta_tag['name']))) {
425 case 'dfrn-global-visibility':
426 if ($content == 'false') {
431 if (strpos($content, 'noindex') !== false) {
442 * Fetch the "subscribe" and add it to the result
444 * @param array $result Result array
445 * @param array $webfinger Webfinger data
446 * @return array result Altered/unaltered result array
448 private static function getSubscribeLink(array $result, array $webfinger): array
450 if (empty($webfinger['links'])) {
454 foreach ($webfinger['links'] as $link) {
455 if (!empty($link['template']) && ($link['rel'] === ActivityNamespace::OSTATUSSUB)) {
456 $result['subscribe'] = $link['template'];
464 * Get webfinger data from a given URI
466 * @param string $uri URI
467 * @return array Webfinger data
468 * @throws HTTPException\InternalServerErrorException
470 private static function getWebfingerArray(string $uri): array
472 $parts = parse_url($uri);
474 if (!empty($parts['scheme']) && !empty($parts['host'])) {
475 $host = $parts['host'];
476 if (!empty($parts['port'])) {
477 $host .= ':' . $parts['port'];
480 $baseurl = $parts['scheme'] . '://' . $host;
485 $path_parts = explode('/', trim($parts['path'] ?? '', '/'));
486 if (!empty($path_parts)) {
487 $nick = ltrim(end($path_parts), '@');
488 $addr = $nick . '@' . $host;
491 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
492 if (empty($webfinger)) {
493 $lrdd = self::hostMeta($host);
496 if (empty($webfinger) && empty($lrdd)) {
497 while (empty($lrdd) && empty($webfinger) && (sizeof($path_parts) > 1)) {
498 $host .= '/' . array_shift($path_parts);
499 $baseurl = $parts['scheme'] . '://' . $host;
502 $addr = $nick . '@' . $host;
505 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
506 if (empty($webfinger)) {
507 $lrdd = self::hostMeta($host);
511 if (empty($lrdd) && empty($webfinger)) {
515 } elseif (strstr($uri, '@')) {
516 // Remove "acct:" from the URI
517 $uri = str_replace('acct:', '', $uri);
519 $host = substr($uri, strpos($uri, '@') + 1);
520 $nick = substr($uri, 0, strpos($uri, '@'));
523 $webfinger = self::getWebfinger('https://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
524 if (self::$istimeout) {
528 if (empty($webfinger)) {
529 $webfinger = self::getWebfinger('http://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
530 if (self::$istimeout) {
534 $baseurl = 'https://' . $host;
537 if (empty($webfinger)) {
538 $lrdd = self::hostMeta($host);
539 if (self::$istimeout) {
542 $baseurl = self::$baseurl;
544 $baseurl = 'http://' . $host;
547 Logger::info('URI was not detectable', ['uri' => $uri]);
551 if (empty($webfinger)) {
552 foreach ($lrdd as $type => $template) {
557 $webfinger = self::getWebfinger($template, $type, $uri, $addr);
561 if (empty($webfinger)) {
565 if ($webfinger['detected'] == $addr) {
566 $webfinger['nick'] = $nick;
567 $webfinger['addr'] = $addr;
570 $webfinger['baseurl'] = $baseurl;
576 * Perform network request for webfinger data
578 * @param string $template
579 * @param string $type
581 * @param string $addr
582 * @return array webfinger results
584 private static function getWebfinger(string $template, string $type, string $uri, string $addr): array
586 if (Network::isUrlBlocked($template)) {
587 Logger::info('Domain is blocked', ['url' => $template]);
591 // First try the address because this is the primary purpose of webfinger
594 $path = str_replace('{uri}', urlencode('acct:' . $addr), $template);
595 $webfinger = self::webfinger($path, $type);
596 if (self::$istimeout) {
602 if (empty($webfinger) && $uri != $addr) {
604 $path = str_replace('{uri}', urlencode($uri), $template);
605 $webfinger = self::webfinger($path, $type);
606 if (self::$istimeout) {
611 if (empty($webfinger)) {
615 return ['webfinger' => $webfinger, 'detected' => $detected];
619 * Fetch information (protocol endpoints and user information) about a given uri
621 * This function is only called by the "uri" function that adds caching and rearranging of data.
623 * @param string $uri Address that should be probed
624 * @param string $network Test for this specific network
625 * @param integer $uid User ID for the probe (only used for mails)
626 * @param array $ap_profile Previously probed AP profile
627 * @return array URI data
628 * @throws HTTPException\InternalServerErrorException
630 private static function detect(string $uri, string $network, int $uid, array $ap_profile): array
634 'network' => $network,
639 Hook::callAll('probe_detect', $hookData);
641 if (isset($hookData['result'])) {
642 return is_array($hookData['result']) ? $hookData['result'] : [];
645 $parts = parse_url($uri);
646 if (empty($parts['scheme']) && empty($parts['host']) && !strstr($parts['path'], '@')) {
647 Logger::info('URI was not detectable', ['uri' => $uri]);
651 // If the URI starts with "mailto:" then jump directly to the mail detection
652 if (strpos($uri, 'mailto:') !== false) {
653 $uri = str_replace('mailto:', '', $uri);
654 return self::mail($uri, $uid);
657 if ($network == Protocol::MAIL) {
658 return self::mail($uri, $uid);
661 Logger::info('Probing start', ['uri' => $uri]);
663 if (!empty($ap_profile['addr']) && ($ap_profile['addr'] != $uri)) {
664 $data = self::getWebfingerArray($ap_profile['addr']);
668 $data = self::getWebfingerArray($uri);
672 if (!empty($parts['scheme'])) {
673 return self::feed($uri);
674 } elseif (!empty($uid)) {
675 return self::mail($uri, $uid);
681 $webfinger = $data['webfinger'];
682 $nick = $data['nick'] ?? '';
683 $addr = $data['addr'] ?? '';
684 $baseurl = $data['baseurl'] ?? '';
688 if (in_array($network, ["", Protocol::DFRN])) {
689 $result = self::dfrn($webfinger);
691 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
692 $result = self::diaspora($webfinger);
694 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
695 $result = self::ostatus($webfinger);
697 if (in_array($network, ['', Protocol::ZOT])) {
698 $result = self::zot($webfinger, $result, $baseurl);
700 if ((!$result && ($network == '')) || ($network == Protocol::PUMPIO)) {
701 $result = self::pumpio($webfinger, $addr);
703 if (empty($result['network']) && empty($ap_profile['network']) || ($network == Protocol::FEED)) {
704 $result = self::feed($uri);
706 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
707 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
708 if ((empty($result['nick']) || (strstr($result['nick'], ' '))) && ($nick != '')) {
709 $result['nick'] = $nick;
712 if (empty($result['addr']) && ($addr != '')) {
713 $result['addr'] = $addr;
717 $result = self::getSubscribeLink($result, $webfinger);
719 if (empty($result['network'])) {
720 $result['network'] = Protocol::PHANTOM;
723 if (empty($result['baseurl']) && !empty($baseurl)) {
724 $result['baseurl'] = $baseurl;
727 if (empty($result['url'])) {
728 $result['url'] = $uri;
731 Logger::info('Probing done', ['uri' => $uri, 'network' => $result['network']]);
737 * Check for Zot contact
739 * @param array $webfinger Webfinger data
740 * @param array $data previously probed data
741 * @param string $baseUrl Base URL
742 * @return array Zot data
743 * @throws HTTPException\InternalServerErrorException
745 private static function zot(array $webfinger, array $data, string $baseurl): array
747 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
748 foreach ($webfinger['aliases'] as $alias) {
749 if (substr($alias, 0, 5) == 'acct:') {
750 $data['addr'] = substr($alias, 5);
755 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
756 $data['addr'] = substr($webfinger['subject'], 5);
760 foreach ($webfinger['links'] as $link) {
761 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
762 $zot_url = $link['href'];
766 if (empty($zot_url) && !empty($data['addr']) && !empty($baseurl)) {
767 $condition = ['nurl' => Strings::normaliseLink($baseurl), 'platform' => ['hubzilla']];
768 if (!DBA::exists('gserver', $condition)) {
771 $zot_url = $baseurl . '/.well-known/zot-info?address=' . $data['addr'];
774 if (empty($zot_url)) {
778 $data = self::pollZot($zot_url, $data);
780 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
781 foreach ($webfinger['aliases'] as $alias) {
782 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
783 $data['alias'] = $alias;
791 public static function pollZot($url, $data)
793 $curlResult = DI::httpClient()->get($url, HttpClientAccept::JSON);
794 if ($curlResult->isTimeout()) {
797 $content = $curlResult->getBody();
802 $json = json_decode($content, true);
803 if (!is_array($json)) {
807 if (empty($data['network'])) {
808 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
809 $data['network'] = Protocol::ZOT;
810 } elseif (!isset($json['protocols'])) {
811 $data['network'] = Protocol::ZOT;
815 if (!empty($json['guid']) && empty($data['guid'])) {
816 $data['guid'] = $json['guid'];
818 if (!empty($json['key']) && empty($data['pubkey'])) {
819 $data['pubkey'] = $json['key'];
821 if (!empty($json['name'])) {
822 $data['name'] = $json['name'];
824 if (!empty($json['photo'])) {
825 $data['photo'] = $json['photo'];
826 if (!empty($json['photo_updated'])) {
827 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
830 if (!empty($json['address'])) {
831 $data['addr'] = $json['address'];
833 if (!empty($json['url'])) {
834 $data['url'] = $json['url'];
836 if (!empty($json['connections_url'])) {
837 $data['poco'] = $json['connections_url'];
839 if (isset($json['searchable'])) {
840 $data['hide'] = !$json['searchable'];
842 if (!empty($json['public_forum'])) {
843 $data['community'] = $json['public_forum'];
844 $data['account-type'] = User::PAGE_FLAGS_COMMUNITY;
847 if (!empty($json['profile'])) {
848 $profile = $json['profile'];
849 if (!empty($profile['description'])) {
850 $data['about'] = $profile['description'];
852 if (!empty($profile['keywords'])) {
853 $keywords = implode(', ', $profile['keywords']);
854 if (!empty($keywords)) {
855 $data['keywords'] = $keywords;
860 if (!empty($profile['region'])) {
861 $loc['region'] = $profile['region'];
863 if (!empty($profile['country'])) {
864 $loc['country-name'] = $profile['country'];
866 $location = Profile::formatLocation($loc);
867 if (!empty($location)) {
868 $data['location'] = $location;
876 * Perform a webfinger request.
878 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
880 * @param string $url Address that should be probed
881 * @param string $type type
882 * @return array webfinger data
883 * @throws HTTPException\InternalServerErrorException
885 public static function webfinger(string $url, string $type): array
887 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
889 $curlResult = DI::httpClient()->get($url, $type, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
890 if ($curlResult->isTimeout()) {
891 self::$istimeout = true;
894 $data = $curlResult->getBody();
896 $webfinger = json_decode($data, true);
897 if (!empty($webfinger)) {
898 if (!isset($webfinger['links'])) {
899 Logger::info('No json webfinger links', ['url' => $url]);
905 // If it is not JSON, maybe it is XML
906 $xrd = XML::parseString($data, true);
907 if (!is_object($xrd)) {
908 Logger::info('No webfinger data retrievable', ['url' => $url]);
912 $xrd_arr = XML::elementToArray($xrd);
913 if (!isset($xrd_arr['xrd']['link'])) {
914 Logger::info('No XML webfinger links', ['url' => $url]);
920 if (!empty($xrd_arr['xrd']['subject'])) {
921 $webfinger['subject'] = $xrd_arr['xrd']['subject'];
924 if (!empty($xrd_arr['xrd']['alias'])) {
925 $webfinger['aliases'] = $xrd_arr['xrd']['alias'];
928 $webfinger['links'] = [];
930 foreach ($xrd_arr['xrd']['link'] as $value => $data) {
931 if (!empty($data['@attributes'])) {
932 $attributes = $data['@attributes'];
933 } elseif ($value == '@attributes') {
939 $webfinger['links'][] = $attributes;
945 * Poll the Friendica specific noscrape page.
947 * "noscrape" is a faster alternative to fetch the data from the hcard.
948 * This functionality was originally created for the directory.
950 * @param string $noscrape_url Link to the noscrape page
951 * @param array $data The already fetched data
952 * @return array noscrape data
953 * @throws HTTPException\InternalServerErrorException
955 private static function pollNoscrape(string $noscrape_url, array $data): array
957 $curlResult = DI::httpClient()->get($noscrape_url, HttpClientAccept::JSON);
958 if ($curlResult->isTimeout()) {
959 self::$istimeout = true;
962 $content = $curlResult->getBody();
964 Logger::info('Empty body', ['url' => $noscrape_url]);
968 $json = json_decode($content, true);
969 if (!is_array($json)) {
970 Logger::info('No json data', ['url' => $noscrape_url]);
974 if (!empty($json['fn'])) {
975 $data['name'] = $json['fn'];
978 if (!empty($json['addr'])) {
979 $data['addr'] = $json['addr'];
982 if (!empty($json['nick'])) {
983 $data['nick'] = $json['nick'];
986 if (!empty($json['guid'])) {
987 $data['guid'] = $json['guid'];
990 if (!empty($json['comm'])) {
991 $data['community'] = $json['comm'];
994 if (!empty($json['tags'])) {
995 $keywords = implode(', ', $json['tags']);
996 if ($keywords != '') {
997 $data['keywords'] = $keywords;
1001 $location = Profile::formatLocation($json);
1003 $data['location'] = $location;
1006 if (!empty($json['about'])) {
1007 $data['about'] = $json['about'];
1010 if (!empty($json['xmpp'])) {
1011 $data['xmpp'] = $json['xmpp'];
1014 if (!empty($json['matrix'])) {
1015 $data['matrix'] = $json['matrix'];
1018 if (!empty($json['key'])) {
1019 $data['pubkey'] = $json['key'];
1022 if (!empty($json['photo'])) {
1023 $data['photo'] = $json['photo'];
1026 if (!empty($json['dfrn-request'])) {
1027 $data['request'] = $json['dfrn-request'];
1030 if (!empty($json['dfrn-confirm'])) {
1031 $data['confirm'] = $json['dfrn-confirm'];
1034 if (!empty($json['dfrn-notify'])) {
1035 $data['notify'] = $json['dfrn-notify'];
1038 if (!empty($json['dfrn-poll'])) {
1039 $data['poll'] = $json['dfrn-poll'];
1042 if (isset($json['hide'])) {
1043 $data['hide'] = (bool)$json['hide'];
1045 $data['hide'] = false;
1052 * Check for valid DFRN data
1054 * @param array $data DFRN data
1056 * @return int Number of errors
1058 public static function validDfrn($data)
1061 if (!isset($data['key'])) {
1064 if (!isset($data['dfrn-request'])) {
1067 if (!isset($data['dfrn-confirm'])) {
1070 if (!isset($data['dfrn-notify'])) {
1073 if (!isset($data['dfrn-poll'])) {
1080 * Fetch data from a DFRN profile page and via "noscrape"
1082 * @param string $profile_link Link to the profile page
1083 * @return array profile data
1084 * @throws HTTPException\InternalServerErrorException
1085 * @throws \ImagickException
1087 public static function profile(string $profile_link): array
1091 Logger::info('Check profile', ['link' => $profile_link]);
1093 // Fetch data via noscrape - this is faster
1094 $noscrape_url = str_replace(['/hcard/', '/profile/'], '/noscrape/', $profile_link);
1095 $data = self::pollNoscrape($noscrape_url, $data);
1097 if (!isset($data['notify'])
1098 || !isset($data['confirm'])
1099 || !isset($data['request'])
1100 || !isset($data['poll'])
1101 || !isset($data['name'])
1102 || !isset($data['photo'])
1104 $data = self::pollHcard($profile_link, $data, true);
1109 if (empty($data['addr']) || empty($data['nick'])) {
1110 $probe_data = self::uri($profile_link);
1111 $data['addr'] = ($data['addr'] ?? '') ?: $probe_data['addr'];
1112 $data['nick'] = ($data['nick'] ?? '') ?: $probe_data['nick'];
1115 $prof_data['addr'] = $data['addr'];
1116 $prof_data['nick'] = $data['nick'];
1117 $prof_data['dfrn-request'] = $data['request'] ?? null;
1118 $prof_data['dfrn-confirm'] = $data['confirm'] ?? null;
1119 $prof_data['dfrn-notify'] = $data['notify'] ?? null;
1120 $prof_data['dfrn-poll'] = $data['poll'] ?? null;
1121 $prof_data['photo'] = $data['photo'] ?? null;
1122 $prof_data['fn'] = $data['name'] ?? null;
1123 $prof_data['key'] = $data['pubkey'] ?? null;
1125 Logger::debug('Result', ['link' => $profile_link, 'data' => $prof_data]);
1131 * Check for DFRN contact
1133 * @param array $webfinger Webfinger data
1134 * @return array DFRN data
1135 * @throws HTTPException\InternalServerErrorException
1137 private static function dfrn(array $webfinger): array
1141 // The array is reversed to take into account the order of preference for same-rel links
1142 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1143 foreach (array_reverse($webfinger['links']) as $link) {
1144 if (($link['rel'] == ActivityNamespace::DFRN) && !empty($link['href'])) {
1145 $data['network'] = Protocol::DFRN;
1146 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1147 $data['poll'] = $link['href'];
1148 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1149 $data['url'] = $link['href'];
1150 } elseif (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1151 $hcard_url = $link['href'];
1152 } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1153 $data['poco'] = $link['href'];
1154 } elseif (($link['rel'] == 'http://webfinger.net/rel/avatar') && !empty($link['href'])) {
1155 $data['photo'] = $link['href'];
1156 } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1157 $data['baseurl'] = trim($link['href'], '/');
1158 } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1159 $data['guid'] = $link['href'];
1160 } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1161 $data['pubkey'] = base64_decode($link['href']);
1163 //if (strstr($data['pubkey'], 'RSA ') || ($link['type'] == 'RSA'))
1164 if (strstr($data['pubkey'], 'RSA ')) {
1165 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1170 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1171 foreach ($webfinger['aliases'] as $alias) {
1172 if (empty($data['url']) && !strstr($alias, '@')) {
1173 $data['url'] = $alias;
1174 } elseif (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
1175 $data['alias'] = $alias;
1176 } elseif (substr($alias, 0, 5) == 'acct:') {
1177 $data['addr'] = substr($alias, 5);
1182 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1183 $data['addr'] = substr($webfinger['subject'], 5);
1186 if (!isset($data['network']) || ($hcard_url == '')) {
1190 // Fetch data via noscrape - this is faster
1191 $noscrape_url = str_replace('/hcard/', '/noscrape/', $hcard_url);
1192 $data = self::pollNoscrape($noscrape_url, $data);
1194 if (isset($data['notify'])
1195 && isset($data['confirm'])
1196 && isset($data['request'])
1197 && isset($data['poll'])
1198 && isset($data['name'])
1199 && isset($data['photo'])
1204 $data = self::pollHcard($hcard_url, $data, true);
1210 * Poll the hcard page (Diaspora and Friendica specific)
1212 * @param string $hcard_url Link to the hcard page
1213 * @param array $data The already fetched data
1214 * @param boolean $dfrn Poll DFRN specific data
1215 * @return array hcard data
1216 * @throws HTTPException\InternalServerErrorException
1218 private static function pollHcard(string $hcard_url, array $data, bool $dfrn = false): array
1220 $curlResult = DI::httpClient()->get($hcard_url, HttpClientAccept::HTML);
1221 if ($curlResult->isTimeout()) {
1222 self::$istimeout = true;
1225 $content = $curlResult->getBody();
1226 if (empty($content)) {
1230 $doc = new DOMDocument();
1231 if (!@$doc->loadHTML($content)) {
1235 $xpath = new DomXPath($doc);
1237 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1238 if (!is_object($vcards)) {
1242 if (!isset($data["baseurl"])) {
1243 $data["baseurl"] = "";
1246 if ($vcards->length > 0) {
1247 $vcard = $vcards->item(0);
1249 // We have to discard the guid from the hcard in favour of the guid from lrdd
1250 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1251 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1252 if (($search->length > 0) && empty($data["guid"])) {
1253 $data["guid"] = $search->item(0)->nodeValue;
1256 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1257 if ($search->length > 0) {
1258 $data["nick"] = $search->item(0)->nodeValue;
1261 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1262 if ($search->length > 0) {
1263 $data["name"] = $search->item(0)->nodeValue;
1266 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1267 if ($search->length > 0) {
1268 $data["searchable"] = $search->item(0)->nodeValue;
1271 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1272 if ($search->length > 0) {
1273 $data['pubkey'] = $search->item(0)->nodeValue;
1274 if (strstr($data['pubkey'], 'RSA ')) {
1275 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1279 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1280 if ($search->length > 0) {
1281 $data['baseurl'] = trim($search->item(0)->nodeValue, '/');
1286 if (!empty($vcard)) {
1287 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1288 foreach ($photos as $photo) {
1290 foreach ($photo->attributes as $attribute) {
1291 $attr[$attribute->name] = trim($attribute->value);
1294 if (isset($attr['src']) && isset($attr['width'])) {
1295 $avatar[$attr['width']] = $attr['src'];
1298 // We don't have a width. So we just take everything that we got.
1299 // This is a Hubzilla workaround which doesn't send a width.
1300 if ((sizeof($avatar) == 0) && !empty($attr['src'])) {
1301 $avatar[] = $attr['src'];
1306 if (sizeof($avatar)) {
1308 $data['photo'] = self::fixAvatar(array_pop($avatar), $data['baseurl']);
1312 // Poll DFRN specific data
1313 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1314 if ($search->length > 0) {
1315 foreach ($search as $link) {
1316 //$data['request'] = $search->item(0)->nodeValue;
1318 foreach ($link->attributes as $attribute) {
1319 $attr[$attribute->name] = trim($attribute->value);
1322 $data[substr($attr['rel'], 5)] = $attr['href'];
1326 // Older Friendica versions had used the 'uid' field differently than newer versions
1327 if (!empty($data['nick']) && !empty($data['guid']) && ($data['nick'] == $data['guid'])) {
1328 unset($data['guid']);
1337 * Check for Diaspora contact
1339 * @param array $webfinger Webfinger data
1340 * @return array Diaspora data
1341 * @throws HTTPException\InternalServerErrorException
1343 private static function diaspora(array $webfinger): array
1348 // The array is reversed to take into account the order of preference for same-rel links
1349 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1350 foreach (array_reverse($webfinger['links']) as $link) {
1351 if (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1352 $hcard_url = $link['href'];
1353 } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1354 $data['baseurl'] = trim($link['href'], '/');
1355 } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1356 $data['guid'] = $link['href'];
1357 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1358 $data['url'] = $link['href'];
1359 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && empty($link['type']) && !empty($link['href'])) {
1360 $profile_url = $link['href'];
1361 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1362 $data['poll'] = $link['href'];
1363 } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1364 $data['poco'] = $link['href'];
1365 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1366 $data['notify'] = $link['href'];
1367 } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1368 $data['pubkey'] = base64_decode($link['href']);
1370 //if (strstr($data['pubkey'], 'RSA ') || ($link['type'] == 'RSA'))
1371 if (strstr($data['pubkey'], 'RSA ')) {
1372 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1377 if (empty($data['url']) && !empty($profile_url)) {
1378 $data['url'] = $profile_url;
1381 if (empty($data['url']) || empty($hcard_url)) {
1385 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1386 foreach ($webfinger['aliases'] as $alias) {
1387 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data['url']) && ! strstr($alias, '@')) {
1388 $data['alias'] = $alias;
1389 } elseif (substr($alias, 0, 5) == 'acct:') {
1390 $data['addr'] = substr($alias, 5);
1395 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1396 $data['addr'] = substr($webfinger['subject'], 5);
1399 // Fetch further information from the hcard
1400 $data = self::pollHcard($hcard_url, $data);
1406 if (!empty($data['url'])
1407 && !empty($data['guid'])
1408 && !empty($data['baseurl'])
1409 && !empty($data['pubkey'])
1410 && !empty($hcard_url)
1412 $data['network'] = Protocol::DIASPORA;
1413 $data['manually-approve'] = false;
1415 // The Diaspora handle must always be lowercase
1416 if (!empty($data['addr'])) {
1417 $data['addr'] = strtolower($data['addr']);
1420 // We have to overwrite the detected value for 'notify' since Hubzilla doesn't send it
1421 $data['notify'] = $data['baseurl'] . '/receive/users/' . $data['guid'];
1422 $data['batch'] = $data['baseurl'] . '/receive/public';
1431 * Check for OStatus contact
1433 * @param array $webfinger Webfinger data
1434 * @param bool $short Short detection mode
1435 * @return array|bool OStatus data or "false" on error or "true" on short mode
1436 * @throws HTTPException\InternalServerErrorException
1438 private static function ostatus(array $webfinger, bool $short = false)
1442 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1443 foreach ($webfinger['aliases'] as $alias) {
1444 if (strstr($alias, '@') && !strstr(Strings::normaliseLink($alias), 'http://')) {
1445 $data['addr'] = str_replace('acct:', '', $alias);
1450 if (!empty($webfinger['subject']) && strstr($webfinger['subject'], '@')
1451 && !strstr(Strings::normaliseLink($webfinger['subject']), 'http://')
1453 $data['addr'] = str_replace('acct:', '', $webfinger['subject']);
1456 if (!empty($webfinger['links'])) {
1457 // The array is reversed to take into account the order of preference for same-rel links
1458 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1459 foreach (array_reverse($webfinger['links']) as $link) {
1460 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1461 && (($link['type'] ?? '') == 'text/html')
1462 && ($link['href'] != '')
1464 $data['url'] = $data['alias'] = $link['href'];
1465 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1466 $data['notify'] = $link['href'];
1467 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1468 $data['poll'] = $link['href'];
1469 } elseif (($link['rel'] == 'magic-public-key') && !empty($link['href'])) {
1470 $pubkey = $link['href'];
1472 if (substr($pubkey, 0, 5) === 'data:') {
1473 if (strstr($pubkey, ',')) {
1474 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1476 $pubkey = substr($pubkey, 5);
1478 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1479 $curlResult = DI::httpClient()->get($pubkey, HttpClientAccept::MAGIC_KEY);
1480 if ($curlResult->isTimeout()) {
1481 self::$istimeout = true;
1482 return $short ? false : [];
1484 Logger::debug('Fetched public key', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $pubkey]);
1485 $pubkey = $curlResult->getBody();
1488 $key = explode('.', $pubkey);
1490 if (sizeof($key) >= 3) {
1491 $m = Strings::base64UrlDecode($key[1]);
1492 $e = Strings::base64UrlDecode($key[2]);
1493 $data['pubkey'] = Crypto::meToPem($m, $e);
1499 if (isset($data['notify']) && isset($data['pubkey'])
1500 && isset($data['poll'])
1501 && isset($data['url'])
1503 $data['network'] = Protocol::OSTATUS;
1504 $data['manually-approve'] = false;
1506 return $short ? false : [];
1513 // Fetch all additional data from the feed
1514 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::FEED_XML);
1515 if ($curlResult->isTimeout()) {
1516 self::$istimeout = true;
1519 $feed = $curlResult->getBody();
1520 $feed_data = Feed::import($feed);
1525 if (!empty($feed_data['header']['author-name'])) {
1526 $data['name'] = $feed_data['header']['author-name'];
1528 if (!empty($feed_data['header']['author-nick'])) {
1529 $data['nick'] = $feed_data['header']['author-nick'];
1531 if (!empty($feed_data['header']['author-avatar'])) {
1532 $data['photo'] = self::fixAvatar($feed_data['header']['author-avatar'], $data['url']);
1534 if (!empty($feed_data['header']['author-id'])) {
1535 $data['alias'] = $feed_data['header']['author-id'];
1537 if (!empty($feed_data['header']['author-location'])) {
1538 $data['location'] = $feed_data['header']['author-location'];
1540 if (!empty($feed_data['header']['author-about'])) {
1541 $data['about'] = $feed_data['header']['author-about'];
1543 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1544 // So we take the value that we just fetched, although the other one worked as well
1545 if (!empty($feed_data['header']['author-link'])) {
1546 $data['url'] = $feed_data['header']['author-link'];
1549 if ($data['url'] == $data['alias']) {
1550 $data['alias'] = '';
1553 /// @todo Fetch location and "about" from the feed as well
1558 * Fetch data from a pump.io profile page
1560 * @param string $profile_link Link to the profile page
1561 * @return array Profile data
1563 private static function pumpioProfileData(string $profile_link): array
1565 $curlResult = DI::httpClient()->get($profile_link, HttpClientAccept::HTML);
1566 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
1570 $doc = new DOMDocument();
1571 if (!@$doc->loadHTML($curlResult->getBody())) {
1575 $xpath = new DomXPath($doc);
1578 $data['name'] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1580 if ($data['name'] == '') {
1581 // This is ugly - but pump.io doesn't seem to know a better way for it
1582 $data['name'] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1583 $pos = strpos($data['name'], chr(10));
1585 $data['name'] = trim(substr($data['name'], 0, $pos));
1589 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1591 if ($data['location'] == '') {
1592 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1595 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1597 if ($data['about'] == '') {
1598 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1601 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1603 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1606 foreach ($avatar->attributes as $attribute) {
1607 if ($attribute->name == 'src') {
1608 $data['photo'] = trim($attribute->value);
1617 * Check for pump.io contact
1619 * @param array $webfinger Webfinger data
1620 * @param string $addr
1621 * @return array pump.io data
1623 private static function pumpio(array $webfinger, string $addr): array
1626 // The array is reversed to take into account the order of preference for same-rel links
1627 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1628 foreach (array_reverse($webfinger['links']) as $link) {
1629 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1630 && (($link['type'] ?? '') == 'text/html')
1631 && ($link['href'] != '')
1633 $data['url'] = $link['href'];
1634 } elseif (($link['rel'] == 'activity-inbox') && ($link['href'] != '')) {
1635 $data['notify'] = $link['href'];
1636 } elseif (($link['rel'] == 'activity-outbox') && ($link['href'] != '')) {
1637 $data['poll'] = $link['href'];
1638 } elseif (($link['rel'] == 'dialback') && ($link['href'] != '')) {
1639 $data['dialback'] = $link['href'];
1642 if (isset($data['poll']) && isset($data['notify'])
1643 && isset($data['dialback'])
1644 && isset($data['url'])
1646 // by now we use these fields only for the network type detection
1647 // So we unset all data that isn't used at the moment
1648 unset($data['dialback']);
1650 $data['network'] = Protocol::PUMPIO;
1655 $profile_data = self::pumpioProfileData($data['url']);
1657 if (!$profile_data) {
1661 $data = array_merge($data, $profile_data);
1663 if (($addr != '') && ($data['name'] != '')) {
1664 $name = trim(str_replace($addr, '', $data['name']));
1666 $data['name'] = $name;
1674 * Checks HTML page for RSS feed link
1676 * @param string $url Page link
1677 * @param string $body Page body string
1678 * @return string|false Feed link or false if body was invalid HTML document
1680 public static function getFeedLink(string $url, string $body)
1686 $doc = new DOMDocument();
1687 if (!@$doc->loadHTML($body)) {
1691 $xpath = new DOMXPath($doc);
1693 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1695 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1701 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1703 * Loosely based on RFC 1808
1705 * @see https://tools.ietf.org/html/rfc1808
1707 * @param string $href The potential relative href found in the HTML document
1708 * @param string $base The HTML document URL
1709 * @param DOMXPath $xpath The HTML document XPath
1710 * @return string Absolute URL
1712 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath): string
1714 if (filter_var($href, FILTER_VALIDATE_URL)) {
1718 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1720 $baseParts = parse_url($base);
1721 if (empty($baseParts['host'])) {
1725 // Naked domain case (scheme://basehost)
1726 $path = $baseParts['path'] ?? '/';
1728 // Remove the filename part of the path if it exists (/base/path/file)
1729 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1731 $hrefParts = parse_url($href);
1733 if (!empty($hrefParts['path'])) {
1734 // Root path case (/path) including relative scheme case (//host/path)
1735 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1736 $path = $hrefParts['path'];
1738 $path = $path . '/' . $hrefParts['path'];
1740 // Resolve arbitrary relative path
1741 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1742 $parts = array_filter(explode('/', $path), 'strlen');
1743 $absolutes = array();
1744 foreach ($parts as $part) {
1745 if ('.' == $part) continue;
1746 if ('..' == $part) {
1747 array_pop($absolutes);
1749 $absolutes[] = $part;
1753 $path = '/' . implode('/', $absolutes);
1757 // Relative scheme case (//host/path)
1758 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1759 $baseParts['path'] = $path;
1760 unset($baseParts['query']);
1761 unset($baseParts['fragment']);
1763 return Network::unparseURL($baseParts);
1767 * Check for feed contact
1769 * @param string $url Profile link
1770 * @param boolean $probe Do a probe if the page contains a feed link
1772 * @return array feed data
1773 * @throws HTTPException\InternalServerErrorException
1775 private static function feed($url, $probe = true)
1777 $curlResult = DI::httpClient()->get($url, HttpClientAccept::FEED_XML);
1778 if ($curlResult->isTimeout()) {
1779 self::$istimeout = true;
1782 $feed = $curlResult->getBody();
1783 $feed_data = Feed::import($feed);
1790 $feed_url = self::getFeedLink($url, $feed);
1796 return self::feed($feed_url, false);
1799 if (!empty($feed_data['header']['author-name'])) {
1800 $data['name'] = $feed_data['header']['author-name'];
1803 if (!empty($feed_data['header']['author-nick'])) {
1804 $data['nick'] = $feed_data['header']['author-nick'];
1807 if (!empty($feed_data['header']['author-avatar'])) {
1808 $data['photo'] = $feed_data['header']['author-avatar'];
1811 if (!empty($feed_data['header']['author-id'])) {
1812 $data['alias'] = $feed_data['header']['author-id'];
1815 $data['url'] = $url;
1816 $data['poll'] = $url;
1818 $data['network'] = Protocol::FEED;
1824 * Check for mail contact
1826 * @param string $uri Profile link
1827 * @param integer $uid User ID
1828 * @return array mail data
1829 * @throws \Exception
1831 private static function mail(string $uri, int $uid): array
1833 if (!Network::isEmailDomainValid($uri)) {
1841 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1843 $condition = ["`uid` = ? AND `server` != ''", $uid];
1844 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1845 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1847 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1851 $mailbox = Email::constructMailboxName($mailacct);
1853 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1854 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1859 $msgs = Email::poll($mbox, $uri);
1860 Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
1862 if (!count($msgs)) {
1866 $phost = substr($uri, strpos($uri, '@') + 1);
1869 $data['addr'] = $uri;
1870 $data['network'] = Protocol::MAIL;
1871 $data['name'] = substr($uri, 0, strpos($uri, '@'));
1872 $data['nick'] = $data['name'];
1873 $data['photo'] = Network::lookupAvatarByEmail($uri);
1874 $data['url'] = 'mailto:'.$uri;
1875 $data['notify'] = 'smtp ' . Strings::getRandomHex();
1876 $data['poll'] = 'email ' . Strings::getRandomHex();
1878 $x = Email::messageMeta($mbox, $msgs[0]);
1879 if (stristr($x[0]->from, $uri)) {
1880 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1881 } elseif (stristr($x[0]->to, $uri)) {
1882 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1885 foreach ($adr as $feadr) {
1886 if ((strcasecmp($feadr->mailbox, $data['name']) == 0)
1887 &&(strcasecmp($feadr->host, $phost) == 0)
1888 && (strlen($feadr->personal))
1890 $personal = imap_mime_header_decode($feadr->personal);
1892 foreach ($personal as $perspart) {
1893 if ($perspart->charset != 'default') {
1894 $data['name'] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1896 $data['name'] .= $perspart->text;
1902 if (!empty($mbox)) {
1909 * Mix two paths together to possibly fix missing parts
1911 * @param string $avatar Path to the avatar
1912 * @param string $base Another path that is hopefully complete
1913 * @return string fixed avatar path
1914 * @throws \Exception
1916 public static function fixAvatar(string $avatar, string $base): string
1918 $base_parts = parse_url($base);
1920 // Remove all parts that could create a problem
1921 unset($base_parts['path']);
1922 unset($base_parts['query']);
1923 unset($base_parts['fragment']);
1925 $avatar_parts = parse_url($avatar);
1928 $parts = array_merge($base_parts, $avatar_parts);
1930 // And put them together again
1931 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1932 $host = isset($parts['host']) ? $parts['host'] : '';
1933 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1934 $path = isset($parts['path']) ? $parts['path'] : '';
1935 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1936 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1938 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1940 Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
1946 * Fetch the last date that the contact had posted something (publically)
1948 * @param array $data probing result
1949 * @return string last activity
1951 public static function getLastUpdate(array $data): string
1953 $uid = User::getIdForURL($data['url']);
1955 $contact = Contact::selectFirst(['url', 'last-item'], ['self' => true, 'uid' => $uid]);
1956 if (!empty($contact['last-item'])) {
1957 return $contact['last-item'];
1961 if ($lastUpdate = self::updateFromNoScrape($data)) {
1965 if (!empty($data['outbox'])) {
1966 return self::updateFromOutbox($data['outbox'], $data);
1967 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
1968 return self::updateFromOutbox($data['poll'], $data);
1969 } elseif (!empty($data['poll'])) {
1970 return self::updateFromFeed($data);
1977 * Fetch the last activity date from the "noscrape" endpoint
1979 * @param array $data Probing result
1980 * @return string last activity or bool 'true' if update was successful or the server was unreachable
1982 private static function updateFromNoScrape(array $data)
1984 if (empty($data['baseurl'])) {
1988 // Check the 'noscrape' endpoint when it is a Friendica server
1989 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
1990 Strings::normaliseLink($data['baseurl'])]);
1991 if (!DBA::isResult($gserver)) {
1995 $curlResult = DI::httpClient()->get($gserver['noscrape'] . '/' . $data['nick'], HttpClientAccept::JSON);
1997 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
1998 $noscrape = json_decode($curlResult->getBody(), true);
1999 if (!empty($noscrape) && !empty($noscrape['updated'])) {
2000 return DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2008 * Fetch the last activity date from an ActivityPub Outbox
2010 * @param string $feed
2011 * @param array $data Probing result
2012 * @return string last activity
2013 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2015 private static function updateFromOutbox(string $feed, array $data): string
2017 $outbox = ActivityPub::fetchContent($feed);
2018 if (empty($outbox)) {
2022 if (!empty($outbox['orderedItems'])) {
2023 $items = $outbox['orderedItems'];
2024 } elseif (!empty($outbox['first']['orderedItems'])) {
2025 $items = $outbox['first']['orderedItems'];
2026 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2027 return self::updateFromOutbox($outbox['first']['href'], $data);
2028 } elseif (!empty($outbox['first'])) {
2029 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2030 return self::updateFromOutbox($outbox['first'], $data);
2032 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2040 foreach ($items as $activity) {
2041 if (!empty($activity['published'])) {
2042 $published = DateTimeFormat::utc($activity['published']);
2043 } elseif (!empty($activity['object']['published'])) {
2044 $published = DateTimeFormat::utc($activity['object']['published']);
2049 if ($last_updated < $published) {
2050 $last_updated = $published;
2054 if (!empty($last_updated)) {
2055 return $last_updated;
2062 * Fetch the last activity date from an XML feed
2064 * @param array $data Probing result
2065 * @return string last activity
2067 private static function updateFromFeed(array $data): string
2069 // Search for the newest entry in the feed
2070 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::ATOM_XML);
2071 if (!$curlResult->isSuccess() || !$curlResult->getBody()) {
2075 $doc = new DOMDocument();
2076 @$doc->loadXML($curlResult->getBody());
2078 $xpath = new DOMXPath($doc);
2079 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2081 $entries = $xpath->query('/atom:feed/atom:entry');
2085 foreach ($entries as $entry) {
2086 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2087 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
2088 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2089 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2091 if (empty($published) || empty($updated)) {
2092 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2096 if ($last_updated < $published) {
2097 $last_updated = $published;
2100 if ($last_updated < $updated) {
2101 $last_updated = $updated;
2105 if (!empty($last_updated)) {
2106 return $last_updated;
2113 * Probe data from local profiles without network traffic
2115 * @param string $url
2116 * @return array probed data
2117 * @throws HTTPException\InternalServerErrorException
2118 * @throws HTTPException\NotFoundException
2120 private static function localProbe(string $url): array
2123 $uid = User::getIdForURL($url);
2125 throw new HTTPException\NotFoundException('User not found.');
2128 $owner = User::getOwnerDataById($uid);
2129 $approfile = ActivityPub\Transmitter::getProfile($uid);
2131 if (empty($owner['gsid'])) {
2132 $owner['gsid'] = GServer::getID($approfile['generator']['url']);
2136 'name' => $owner['name'], 'nick' => $owner['nick'], 'guid' => $approfile['diaspora:guid'] ?? '',
2137 'url' => $owner['url'], 'addr' => $owner['addr'], 'alias' => $owner['alias'],
2138 'photo' => User::getAvatarUrl($owner),
2139 'header' => $owner['header'] ? Contact::getHeaderUrlForId($owner['id'], $owner['updated']) : '',
2140 'account-type' => $owner['contact-type'], 'community' => ($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY),
2141 'keywords' => $owner['keywords'], 'location' => $owner['location'], 'about' => $owner['about'],
2142 'xmpp' => $owner['xmpp'], 'matrix' => $owner['matrix'],
2143 'hide' => !$owner['net-publish'], 'batch' => '', 'notify' => $owner['notify'],
2144 'poll' => $owner['poll'], 'request' => $owner['request'], 'confirm' => $owner['confirm'],
2145 'subscribe' => $approfile['generator']['url'] . '/follow?url={uri}', 'poco' => $owner['poco'],
2146 'following' => $approfile['following'], 'followers' => $approfile['followers'],
2147 'inbox' => $approfile['inbox'], 'outbox' => $approfile['outbox'],
2148 'sharedinbox' => $approfile['endpoints']['sharedInbox'], 'network' => Protocol::DFRN,
2149 'pubkey' => $owner['upubkey'], 'baseurl' => $approfile['generator']['url'], 'gsid' => $owner['gsid'],
2150 'manually-approve' => in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])
2152 } catch (Exception $e) {
2153 // Default values for non existing targets
2155 'name' => $url, 'nick' => $url, 'url' => $url, 'network' => Protocol::PHANTOM,
2156 'photo' => DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO
2160 return self::rearrangeData($data);