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(string $url, array $data): array
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 ')) {
1164 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1169 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1170 foreach ($webfinger['aliases'] as $alias) {
1171 if (empty($data['url']) && !strstr($alias, '@')) {
1172 $data['url'] = $alias;
1173 } elseif (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
1174 $data['alias'] = $alias;
1175 } elseif (substr($alias, 0, 5) == 'acct:') {
1176 $data['addr'] = substr($alias, 5);
1181 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1182 $data['addr'] = substr($webfinger['subject'], 5);
1185 if (!isset($data['network']) || ($hcard_url == '')) {
1189 // Fetch data via noscrape - this is faster
1190 $noscrape_url = str_replace('/hcard/', '/noscrape/', $hcard_url);
1191 $data = self::pollNoscrape($noscrape_url, $data);
1193 if (isset($data['notify'])
1194 && isset($data['confirm'])
1195 && isset($data['request'])
1196 && isset($data['poll'])
1197 && isset($data['name'])
1198 && isset($data['photo'])
1203 $data = self::pollHcard($hcard_url, $data, true);
1209 * Poll the hcard page (Diaspora and Friendica specific)
1211 * @param string $hcard_url Link to the hcard page
1212 * @param array $data The already fetched data
1213 * @param boolean $dfrn Poll DFRN specific data
1214 * @return array hcard data
1215 * @throws HTTPException\InternalServerErrorException
1217 private static function pollHcard(string $hcard_url, array $data, bool $dfrn = false): array
1219 $curlResult = DI::httpClient()->get($hcard_url, HttpClientAccept::HTML);
1220 if ($curlResult->isTimeout()) {
1221 self::$istimeout = true;
1224 $content = $curlResult->getBody();
1225 if (empty($content)) {
1229 $doc = new DOMDocument();
1230 if (!@$doc->loadHTML($content)) {
1234 $xpath = new DomXPath($doc);
1236 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1237 if (!is_object($vcards)) {
1241 if (!isset($data["baseurl"])) {
1242 $data["baseurl"] = "";
1245 if ($vcards->length > 0) {
1246 $vcard = $vcards->item(0);
1248 // We have to discard the guid from the hcard in favour of the guid from lrdd
1249 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1250 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1251 if (($search->length > 0) && empty($data["guid"])) {
1252 $data["guid"] = $search->item(0)->nodeValue;
1255 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1256 if ($search->length > 0) {
1257 $data["nick"] = $search->item(0)->nodeValue;
1260 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1261 if ($search->length > 0) {
1262 $data["name"] = $search->item(0)->nodeValue;
1265 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1266 if ($search->length > 0) {
1267 $data["searchable"] = $search->item(0)->nodeValue;
1270 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1271 if ($search->length > 0) {
1272 $data['pubkey'] = $search->item(0)->nodeValue;
1273 if (strstr($data['pubkey'], 'RSA ')) {
1274 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1278 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1279 if ($search->length > 0) {
1280 $data['baseurl'] = trim($search->item(0)->nodeValue, '/');
1285 if (!empty($vcard)) {
1286 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1287 foreach ($photos as $photo) {
1289 foreach ($photo->attributes as $attribute) {
1290 $attr[$attribute->name] = trim($attribute->value);
1293 if (isset($attr['src']) && isset($attr['width'])) {
1294 $avatar[$attr['width']] = $attr['src'];
1297 // We don't have a width. So we just take everything that we got.
1298 // This is a Hubzilla workaround which doesn't send a width.
1299 if ((sizeof($avatar) == 0) && !empty($attr['src'])) {
1300 $avatar[] = $attr['src'];
1305 if (sizeof($avatar)) {
1307 $data['photo'] = self::fixAvatar(array_pop($avatar), $data['baseurl']);
1311 // Poll DFRN specific data
1312 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1313 if ($search->length > 0) {
1314 foreach ($search as $link) {
1315 //$data['request'] = $search->item(0)->nodeValue;
1317 foreach ($link->attributes as $attribute) {
1318 $attr[$attribute->name] = trim($attribute->value);
1321 $data[substr($attr['rel'], 5)] = $attr['href'];
1325 // Older Friendica versions had used the "uid" field differently than newer versions
1326 if (!empty($data['nick']) && !empty($data['guid']) && ($data['nick'] == $data['guid'])) {
1327 unset($data['guid']);
1336 * Check for Diaspora contact
1338 * @param array $webfinger Webfinger data
1339 * @return array Diaspora data
1340 * @throws HTTPException\InternalServerErrorException
1342 private static function diaspora(array $webfinger): array
1347 // The array is reversed to take into account the order of preference for same-rel links
1348 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1349 foreach (array_reverse($webfinger['links']) as $link) {
1350 if (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1351 $hcard_url = $link['href'];
1352 } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1353 $data['baseurl'] = trim($link['href'], '/');
1354 } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1355 $data['guid'] = $link['href'];
1356 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1357 $data['url'] = $link['href'];
1358 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && empty($link['type']) && !empty($link['href'])) {
1359 $profile_url = $link['href'];
1360 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1361 $data['poll'] = $link['href'];
1362 } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1363 $data['poco'] = $link['href'];
1364 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1365 $data['notify'] = $link['href'];
1366 } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1367 $data['pubkey'] = base64_decode($link['href']);
1369 if (strstr($data['pubkey'], 'RSA ')) {
1370 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1375 if (empty($data['url']) && !empty($profile_url)) {
1376 $data['url'] = $profile_url;
1379 if (empty($data['url']) || empty($hcard_url)) {
1383 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1384 foreach ($webfinger['aliases'] as $alias) {
1385 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data['url']) && ! strstr($alias, '@')) {
1386 $data['alias'] = $alias;
1387 } elseif (substr($alias, 0, 5) == 'acct:') {
1388 $data['addr'] = substr($alias, 5);
1393 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1394 $data['addr'] = substr($webfinger['subject'], 5);
1397 // Fetch further information from the hcard
1398 $data = self::pollHcard($hcard_url, $data);
1404 if (!empty($data['url'])
1405 && !empty($data['guid'])
1406 && !empty($data['baseurl'])
1407 && !empty($data['pubkey'])
1408 && !empty($hcard_url)
1410 $data['network'] = Protocol::DIASPORA;
1411 $data['manually-approve'] = false;
1413 // The Diaspora handle must always be lowercase
1414 if (!empty($data['addr'])) {
1415 $data['addr'] = strtolower($data['addr']);
1418 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1419 $data['notify'] = $data['baseurl'] . '/receive/users/' . $data['guid'];
1420 $data['batch'] = $data['baseurl'] . '/receive/public';
1429 * Check for OStatus contact
1431 * @param array $webfinger Webfinger data
1432 * @param bool $short Short detection mode
1433 * @return array|bool OStatus data or "false" on error or "true" on short mode
1434 * @throws HTTPException\InternalServerErrorException
1436 private static function ostatus(array $webfinger, bool $short = false)
1440 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1441 foreach ($webfinger['aliases'] as $alias) {
1442 if (strstr($alias, '@') && !strstr(Strings::normaliseLink($alias), 'http://')) {
1443 $data['addr'] = str_replace('acct:', '', $alias);
1448 if (!empty($webfinger['subject']) && strstr($webfinger['subject'], '@')
1449 && !strstr(Strings::normaliseLink($webfinger['subject']), 'http://')
1451 $data['addr'] = str_replace('acct:', '', $webfinger['subject']);
1454 if (!empty($webfinger['links'])) {
1455 // The array is reversed to take into account the order of preference for same-rel links
1456 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1457 foreach (array_reverse($webfinger['links']) as $link) {
1458 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1459 && (($link['type'] ?? '') == 'text/html')
1460 && ($link['href'] != '')
1462 $data['url'] = $data['alias'] = $link['href'];
1463 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1464 $data['notify'] = $link['href'];
1465 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1466 $data['poll'] = $link['href'];
1467 } elseif (($link['rel'] == 'magic-public-key') && !empty($link['href'])) {
1468 $pubkey = $link['href'];
1470 if (substr($pubkey, 0, 5) === 'data:') {
1471 if (strstr($pubkey, ',')) {
1472 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1474 $pubkey = substr($pubkey, 5);
1476 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1477 $curlResult = DI::httpClient()->get($pubkey, HttpClientAccept::MAGIC_KEY);
1478 if ($curlResult->isTimeout()) {
1479 self::$istimeout = true;
1480 return $short ? false : [];
1482 Logger::debug('Fetched public key', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $pubkey]);
1483 $pubkey = $curlResult->getBody();
1486 $key = explode('.', $pubkey);
1488 if (sizeof($key) >= 3) {
1489 $m = Strings::base64UrlDecode($key[1]);
1490 $e = Strings::base64UrlDecode($key[2]);
1491 $data['pubkey'] = Crypto::meToPem($m, $e);
1497 if (isset($data['notify']) && isset($data['pubkey'])
1498 && isset($data['poll'])
1499 && isset($data['url'])
1501 $data['network'] = Protocol::OSTATUS;
1502 $data['manually-approve'] = false;
1504 return $short ? false : [];
1511 // Fetch all additional data from the feed
1512 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::FEED_XML);
1513 if ($curlResult->isTimeout()) {
1514 self::$istimeout = true;
1517 $feed = $curlResult->getBody();
1518 $feed_data = Feed::import($feed);
1523 if (!empty($feed_data['header']['author-name'])) {
1524 $data['name'] = $feed_data['header']['author-name'];
1526 if (!empty($feed_data['header']['author-nick'])) {
1527 $data['nick'] = $feed_data['header']['author-nick'];
1529 if (!empty($feed_data['header']['author-avatar'])) {
1530 $data['photo'] = self::fixAvatar($feed_data['header']['author-avatar'], $data['url']);
1532 if (!empty($feed_data['header']['author-id'])) {
1533 $data['alias'] = $feed_data['header']['author-id'];
1535 if (!empty($feed_data['header']['author-location'])) {
1536 $data['location'] = $feed_data['header']['author-location'];
1538 if (!empty($feed_data['header']['author-about'])) {
1539 $data['about'] = $feed_data['header']['author-about'];
1541 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1542 // So we take the value that we just fetched, although the other one worked as well
1543 if (!empty($feed_data['header']['author-link'])) {
1544 $data['url'] = $feed_data['header']['author-link'];
1547 if ($data['url'] == $data['alias']) {
1548 $data['alias'] = '';
1551 /// @todo Fetch location and "about" from the feed as well
1556 * Fetch data from a pump.io profile page
1558 * @param string $profile_link Link to the profile page
1559 * @return array Profile data
1561 private static function pumpioProfileData(string $profile_link): array
1563 $curlResult = DI::httpClient()->get($profile_link, HttpClientAccept::HTML);
1564 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
1568 $doc = new DOMDocument();
1569 if (!@$doc->loadHTML($curlResult->getBody())) {
1573 $xpath = new DomXPath($doc);
1576 $data['name'] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1578 if ($data['name'] == '') {
1579 // This is ugly - but pump.io doesn't seem to know a better way for it
1580 $data['name'] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1581 $pos = strpos($data['name'], chr(10));
1583 $data['name'] = trim(substr($data['name'], 0, $pos));
1587 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1589 if ($data['location'] == '') {
1590 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1593 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1595 if ($data['about'] == '') {
1596 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1599 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1601 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1604 foreach ($avatar->attributes as $attribute) {
1605 if ($attribute->name == 'src') {
1606 $data['photo'] = trim($attribute->value);
1615 * Check for pump.io contact
1617 * @param array $webfinger Webfinger data
1618 * @param string $addr
1619 * @return array pump.io data
1621 private static function pumpio(array $webfinger, string $addr): array
1624 // The array is reversed to take into account the order of preference for same-rel links
1625 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1626 foreach (array_reverse($webfinger['links']) as $link) {
1627 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1628 && (($link['type'] ?? '') == 'text/html')
1629 && ($link['href'] != '')
1631 $data['url'] = $link['href'];
1632 } elseif (($link['rel'] == 'activity-inbox') && ($link['href'] != '')) {
1633 $data['notify'] = $link['href'];
1634 } elseif (($link['rel'] == 'activity-outbox') && ($link['href'] != '')) {
1635 $data['poll'] = $link['href'];
1636 } elseif (($link['rel'] == 'dialback') && ($link['href'] != '')) {
1637 $data['dialback'] = $link['href'];
1640 if (isset($data['poll']) && isset($data['notify'])
1641 && isset($data['dialback'])
1642 && isset($data['url'])
1644 // by now we use these fields only for the network type detection
1645 // So we unset all data that isn't used at the moment
1646 unset($data['dialback']);
1648 $data['network'] = Protocol::PUMPIO;
1653 $profile_data = self::pumpioProfileData($data['url']);
1655 if (!$profile_data) {
1659 $data = array_merge($data, $profile_data);
1661 if (($addr != '') && ($data['name'] != '')) {
1662 $name = trim(str_replace($addr, '', $data['name']));
1664 $data['name'] = $name;
1672 * Checks HTML page for RSS feed link
1674 * @param string $url Page link
1675 * @param string $body Page body string
1676 * @return string|false Feed link or false if body was invalid HTML document
1678 public static function getFeedLink(string $url, string $body)
1684 $doc = new DOMDocument();
1685 if (!@$doc->loadHTML($body)) {
1689 $xpath = new DOMXPath($doc);
1691 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1693 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1699 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1701 * Loosely based on RFC 1808
1703 * @see https://tools.ietf.org/html/rfc1808
1705 * @param string $href The potential relative href found in the HTML document
1706 * @param string $base The HTML document URL
1707 * @param DOMXPath $xpath The HTML document XPath
1708 * @return string Absolute URL
1710 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath): string
1712 if (filter_var($href, FILTER_VALIDATE_URL)) {
1716 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1718 $baseParts = parse_url($base);
1719 if (empty($baseParts['host'])) {
1723 // Naked domain case (scheme://basehost)
1724 $path = $baseParts['path'] ?? '/';
1726 // Remove the filename part of the path if it exists (/base/path/file)
1727 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1729 $hrefParts = parse_url($href);
1731 if (!empty($hrefParts['path'])) {
1732 // Root path case (/path) including relative scheme case (//host/path)
1733 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1734 $path = $hrefParts['path'];
1736 $path = $path . '/' . $hrefParts['path'];
1738 // Resolve arbitrary relative path
1739 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1740 $parts = array_filter(explode('/', $path), 'strlen');
1741 $absolutes = array();
1742 foreach ($parts as $part) {
1743 if ('.' == $part) continue;
1744 if ('..' == $part) {
1745 array_pop($absolutes);
1747 $absolutes[] = $part;
1751 $path = '/' . implode('/', $absolutes);
1755 // Relative scheme case (//host/path)
1756 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1757 $baseParts['path'] = $path;
1758 unset($baseParts['query']);
1759 unset($baseParts['fragment']);
1761 return Network::unparseURL($baseParts);
1765 * Check for feed contact
1767 * @param string $url Profile link
1768 * @param boolean $probe Do a probe if the page contains a feed link
1770 * @return array feed data
1771 * @throws HTTPException\InternalServerErrorException
1773 private static function feed($url, $probe = true)
1775 $curlResult = DI::httpClient()->get($url, HttpClientAccept::FEED_XML);
1776 if ($curlResult->isTimeout()) {
1777 self::$istimeout = true;
1780 $feed = $curlResult->getBody();
1781 $feed_data = Feed::import($feed);
1788 $feed_url = self::getFeedLink($url, $feed);
1794 return self::feed($feed_url, false);
1797 if (!empty($feed_data['header']['author-name'])) {
1798 $data['name'] = $feed_data['header']['author-name'];
1801 if (!empty($feed_data['header']['author-nick'])) {
1802 $data['nick'] = $feed_data['header']['author-nick'];
1805 if (!empty($feed_data['header']['author-avatar'])) {
1806 $data['photo'] = $feed_data['header']['author-avatar'];
1809 if (!empty($feed_data['header']['author-id'])) {
1810 $data['alias'] = $feed_data['header']['author-id'];
1813 $data['url'] = $url;
1814 $data['poll'] = $url;
1816 $data['network'] = Protocol::FEED;
1822 * Check for mail contact
1824 * @param string $uri Profile link
1825 * @param integer $uid User ID
1826 * @return array mail data
1827 * @throws \Exception
1829 private static function mail(string $uri, int $uid): array
1831 if (!Network::isEmailDomainValid($uri)) {
1839 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1841 $condition = ["`uid` = ? AND `server` != ''", $uid];
1842 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1843 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1845 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1849 $mailbox = Email::constructMailboxName($mailacct);
1851 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1852 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1857 $msgs = Email::poll($mbox, $uri);
1858 Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
1860 if (!count($msgs)) {
1864 $phost = substr($uri, strpos($uri, '@') + 1);
1867 $data['addr'] = $uri;
1868 $data['network'] = Protocol::MAIL;
1869 $data['name'] = substr($uri, 0, strpos($uri, '@'));
1870 $data['nick'] = $data['name'];
1871 $data['photo'] = Network::lookupAvatarByEmail($uri);
1872 $data['url'] = 'mailto:'.$uri;
1873 $data['notify'] = 'smtp ' . Strings::getRandomHex();
1874 $data['poll'] = 'email ' . Strings::getRandomHex();
1876 $x = Email::messageMeta($mbox, $msgs[0]);
1877 if (stristr($x[0]->from, $uri)) {
1878 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1879 } elseif (stristr($x[0]->to, $uri)) {
1880 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1883 foreach ($adr as $feadr) {
1884 if ((strcasecmp($feadr->mailbox, $data['name']) == 0)
1885 &&(strcasecmp($feadr->host, $phost) == 0)
1886 && (strlen($feadr->personal))
1888 $personal = imap_mime_header_decode($feadr->personal);
1890 foreach ($personal as $perspart) {
1891 if ($perspart->charset != 'default') {
1892 $data['name'] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1894 $data['name'] .= $perspart->text;
1900 if (!empty($mbox)) {
1907 * Mix two paths together to possibly fix missing parts
1909 * @param string $avatar Path to the avatar
1910 * @param string $base Another path that is hopefully complete
1911 * @return string fixed avatar path
1912 * @throws \Exception
1914 public static function fixAvatar(string $avatar, string $base): string
1916 $base_parts = parse_url($base);
1918 // Remove all parts that could create a problem
1919 unset($base_parts['path']);
1920 unset($base_parts['query']);
1921 unset($base_parts['fragment']);
1923 $avatar_parts = parse_url($avatar);
1926 $parts = array_merge($base_parts, $avatar_parts);
1928 // And put them together again
1929 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1930 $host = isset($parts['host']) ? $parts['host'] : '';
1931 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1932 $path = isset($parts['path']) ? $parts['path'] : '';
1933 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1934 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1936 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1938 Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
1944 * Fetch the last date that the contact had posted something (publically)
1946 * @param array $data probing result
1947 * @return string last activity
1949 public static function getLastUpdate(array $data): string
1951 $uid = User::getIdForURL($data['url']);
1953 $contact = Contact::selectFirst(['url', 'last-item'], ['self' => true, 'uid' => $uid]);
1954 if (!empty($contact['last-item'])) {
1955 return $contact['last-item'];
1959 if ($lastUpdate = self::updateFromNoScrape($data)) {
1963 if (!empty($data['outbox'])) {
1964 return self::updateFromOutbox($data['outbox'], $data);
1965 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
1966 return self::updateFromOutbox($data['poll'], $data);
1967 } elseif (!empty($data['poll'])) {
1968 return self::updateFromFeed($data);
1975 * Fetch the last activity date from the "noscrape" endpoint
1977 * @param array $data Probing result
1978 * @return string last activity or true if update was successful or the server was unreachable
1980 private static function updateFromNoScrape(array $data)
1982 if (empty($data['baseurl'])) {
1986 // Check the 'noscrape' endpoint when it is a Friendica server
1987 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
1988 Strings::normaliseLink($data['baseurl'])]);
1989 if (!DBA::isResult($gserver)) {
1993 $curlResult = DI::httpClient()->get($gserver['noscrape'] . '/' . $data['nick'], HttpClientAccept::JSON);
1995 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
1996 $noscrape = json_decode($curlResult->getBody(), true);
1997 if (!empty($noscrape) && !empty($noscrape['updated'])) {
1998 return DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2006 * Fetch the last activity date from an ActivityPub Outbox
2008 * @param string $feed
2009 * @param array $data Probing result
2010 * @return string last activity
2011 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2013 private static function updateFromOutbox(string $feed, array $data): string
2015 $outbox = ActivityPub::fetchContent($feed);
2016 if (empty($outbox)) {
2020 if (!empty($outbox['orderedItems'])) {
2021 $items = $outbox['orderedItems'];
2022 } elseif (!empty($outbox['first']['orderedItems'])) {
2023 $items = $outbox['first']['orderedItems'];
2024 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2025 return self::updateFromOutbox($outbox['first']['href'], $data);
2026 } elseif (!empty($outbox['first'])) {
2027 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2028 return self::updateFromOutbox($outbox['first'], $data);
2030 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2038 foreach ($items as $activity) {
2039 if (!empty($activity['published'])) {
2040 $published = DateTimeFormat::utc($activity['published']);
2041 } elseif (!empty($activity['object']['published'])) {
2042 $published = DateTimeFormat::utc($activity['object']['published']);
2047 if ($last_updated < $published) {
2048 $last_updated = $published;
2052 if (!empty($last_updated)) {
2053 return $last_updated;
2060 * Fetch the last activity date from an XML feed
2062 * @param array $data Probing result
2063 * @return string last activity
2065 private static function updateFromFeed(array $data): string
2067 // Search for the newest entry in the feed
2068 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::ATOM_XML);
2069 if (!$curlResult->isSuccess() || !$curlResult->getBody()) {
2073 $doc = new DOMDocument();
2074 @$doc->loadXML($curlResult->getBody());
2076 $xpath = new DOMXPath($doc);
2077 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2079 $entries = $xpath->query('/atom:feed/atom:entry');
2083 foreach ($entries as $entry) {
2084 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2085 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
2086 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2087 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2089 if (empty($published) || empty($updated)) {
2090 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2094 if ($last_updated < $published) {
2095 $last_updated = $published;
2098 if ($last_updated < $updated) {
2099 $last_updated = $updated;
2103 if (!empty($last_updated)) {
2104 return $last_updated;
2111 * Probe data from local profiles without network traffic
2113 * @param string $url
2114 * @return array probed data
2115 * @throws HTTPException\InternalServerErrorException
2116 * @throws HTTPException\NotFoundException
2118 private static function localProbe(string $url): array
2121 $uid = User::getIdForURL($url);
2123 throw new HTTPException\NotFoundException('User not found.');
2126 $owner = User::getOwnerDataById($uid);
2127 $approfile = ActivityPub\Transmitter::getProfile($uid);
2129 if (empty($owner['gsid'])) {
2130 $owner['gsid'] = GServer::getID($approfile['generator']['url']);
2134 'name' => $owner['name'], 'nick' => $owner['nick'], 'guid' => $approfile['diaspora:guid'] ?? '',
2135 'url' => $owner['url'], 'addr' => $owner['addr'], 'alias' => $owner['alias'],
2136 'photo' => User::getAvatarUrl($owner),
2137 'header' => $owner['header'] ? Contact::getHeaderUrlForId($owner['id'], $owner['updated']) : '',
2138 'account-type' => $owner['contact-type'], 'community' => ($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY),
2139 'keywords' => $owner['keywords'], 'location' => $owner['location'], 'about' => $owner['about'],
2140 'xmpp' => $owner['xmpp'], 'matrix' => $owner['matrix'],
2141 'hide' => !$owner['net-publish'], 'batch' => '', 'notify' => $owner['notify'],
2142 'poll' => $owner['poll'], 'request' => $owner['request'], 'confirm' => $owner['confirm'],
2143 'subscribe' => $approfile['generator']['url'] . '/follow?url={uri}', 'poco' => $owner['poco'],
2144 'following' => $approfile['following'], 'followers' => $approfile['followers'],
2145 'inbox' => $approfile['inbox'], 'outbox' => $approfile['outbox'],
2146 'sharedinbox' => $approfile['endpoints']['sharedInbox'], 'network' => Protocol::DFRN,
2147 'pubkey' => $owner['upubkey'], 'baseurl' => $approfile['generator']['url'], 'gsid' => $owner['gsid'],
2148 'manually-approve' => in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])
2150 } catch (Exception $e) {
2151 // Default values for non existing targets
2153 'name' => $url, 'nick' => $url, 'url' => $url, 'network' => Protocol::PHANTOM,
2154 'photo' => DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO
2158 return self::rearrangeData($data);