3 * @copyright Copyright (C) 2010-2023, 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\Database\DBA;
32 use Friendica\Model\Contact;
33 use Friendica\Model\GServer;
34 use Friendica\Model\Profile;
35 use Friendica\Model\User;
36 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
37 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
38 use Friendica\Protocol\ActivityNamespace;
39 use Friendica\Protocol\ActivityPub;
40 use Friendica\Protocol\Diaspora;
41 use Friendica\Protocol\Email;
42 use Friendica\Protocol\Feed;
43 use Friendica\Protocol\Salmon;
44 use Friendica\Util\Crypto;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Network;
47 use Friendica\Util\Strings;
48 use Friendica\Util\XML;
49 use GuzzleHttp\Psr7\Uri;
52 * This class contain functions for probing URL
56 const HOST_META = '/.well-known/host-meta';
57 const WEBFINGER = '/.well-known/webfinger?resource={uri}';
60 * @var string Base URL
62 private static $baseurl;
65 * @var boolean Whether a timeout has occurred
67 private static $isTimeout;
70 * Checks if the provided network can be probed
72 * @param string $network
76 public static function isProbable(string $network): bool
78 return (in_array($network, array_merge(Protocol::FEDERATED, [Protocol::ZOT, Protocol::PHANTOM])));
82 * Remove stuff from an URI that doesn't belong there
84 * @param string $rawUri
85 * @return string Cleaned URI
87 public static function cleanURI(string $rawUri): string
89 // At first remove leading and trailing junk
90 $rawUri = trim($rawUri, "@#?: \t\n\r\0\x0B");
92 $rawUri = Network::convertToIdn($rawUri);
94 $uri = new Uri($rawUri);
95 if (!$uri->getScheme()) {
96 return $uri->__toString();
99 // Remove the URL fragment, since these shouldn't be part of any profile URL
100 $uri = $uri->withFragment('');
102 return $uri->__toString();
106 * Rearrange the array so that it always has the same order
108 * @param array $data Unordered data
109 * @return array Ordered data
111 private static function rearrangeData(array $data): array
113 $fields = ['name', 'given_name', 'family_name', 'nick', 'guid', 'url', 'addr', 'alias',
114 'photo', 'photo_medium', 'photo_small', 'header',
115 'account-type', 'community', 'keywords', 'location', 'about', 'xmpp', 'matrix',
116 'hide', 'batch', 'notify', 'poll', 'request', 'confirm', 'subscribe', 'poco',
117 'following', 'followers', 'inbox', 'outbox', 'sharedinbox',
118 'priority', 'network', 'pubkey', 'manually-approve', 'baseurl', 'gsid'];
120 $numeric_fields = ['gsid', 'hide', 'account-type', 'manually-approve'];
122 if (!empty($data['photo'])) {
123 $data['photo'] = Network::addBasePath($data['photo'], $data['url']);
125 if (!Network::isValidHttpUrl($data['photo'])) {
126 Logger::warning('Invalid URL for photo', ['url' => $data['url'], 'photo' => $data['photo']]);
127 unset($data['photo']);
132 foreach ($fields as $field) {
133 if (isset($data[$field])) {
134 if (in_array($field, $numeric_fields)) {
135 $newdata[$field] = (int)$data[$field];
137 $newdata[$field] = trim($data[$field]);
139 } elseif (!in_array($field, $numeric_fields)) {
140 $newdata[$field] = '';
142 $newdata[$field] = null;
146 $newdata['networks'] = [];
147 foreach ([Protocol::DIASPORA, Protocol::OSTATUS] as $network) {
148 if (!empty($data['networks'][$network])) {
149 $data['networks'][$network]['subscribe'] = $newdata['subscribe'] ?? '';
150 if (empty($data['networks'][$network]['baseurl'])) {
151 $data['networks'][$network]['baseurl'] = $newdata['baseurl'] ?? '';
153 $newdata['baseurl'] = $data['networks'][$network]['baseurl'];
155 if (!empty($newdata['baseurl'])) {
156 $newdata['gsid'] = $data['networks'][$network]['gsid'] = GServer::getID($newdata['baseurl']);
158 $newdata['gsid'] = $data['networks'][$network]['gsid'] = null;
161 $newdata['networks'][$network] = self::rearrangeData($data['networks'][$network]);
162 unset($newdata['networks'][$network]['networks']);
166 // We don't use the "priority" field anymore and replace it with a dummy.
167 $newdata['priority'] = 0;
173 * Check if the hostname belongs to the own server
175 * @param string $host The hostname that is to be checked
176 * @return bool Does the testes hostname belongs to the own server?
178 private static function ownHost(string $host): bool
180 $own_host = DI::baseUrl()->getHost();
182 $parts = parse_url($host);
184 if (!isset($parts['scheme'])) {
185 $parts = parse_url('http://' . $host);
188 if (!isset($parts['host'])) {
191 return $parts['host'] == $own_host;
195 * Probes for webfinger path via "host-meta"
197 * We have to check if the servers in the future still will offer this.
198 * It seems as if it was dropped from the standard.
200 * @param string $host The host part of an url
202 * @return array with template and type of the webfinger template for JSON or XML
203 * @throws HTTPException\InternalServerErrorException
205 private static function hostMeta(string $host): array
207 // Reset the static variable
210 // Handles the case when the hostname contains the scheme
211 if (!parse_url($host, PHP_URL_SCHEME)) {
212 $ssl_url = 'https://' . $host . self::HOST_META;
213 $url = 'http://' . $host . self::HOST_META;
215 $ssl_url = $host . self::HOST_META;
219 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
221 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url]);
224 $curlResult = DI::httpClient()->get($ssl_url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
225 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
226 if ($curlResult->isSuccess()) {
227 $xml = $curlResult->getBody();
228 $xrd = XML::parseString($xml, true);
230 $host_url = 'https://' . $host;
234 } elseif ($curlResult->isTimeout()) {
235 Logger::info('Probing timeout', ['url' => $ssl_url]);
236 self::$isTimeout = true;
240 if (!is_object($xrd) && !empty($url)) {
241 $curlResult = DI::httpClient()->get($url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
242 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
243 if ($curlResult->isTimeout()) {
244 Logger::info('Probing timeout', ['url' => $url]);
245 self::$isTimeout = true;
247 } elseif ($connection_error && $ssl_connection_error) {
248 self::$isTimeout = true;
252 $xml = $curlResult->getBody();
253 $xrd = XML::parseString($xml, true);
254 $host_url = 'http://'.$host;
256 if (!is_object($xrd)) {
257 Logger::info('No xrd object found', ['host' => $host]);
261 $links = XML::elementToArray($xrd);
262 if (!isset($links['xrd']['link'])) {
263 Logger::info('No xrd data found', ['host' => $host]);
269 foreach ($links['xrd']['link'] as $value => $link) {
270 if (!empty($link['@attributes'])) {
271 $attributes = $link['@attributes'];
272 } elseif ($value == '@attributes') {
278 if (!empty($attributes['rel']) && $attributes['rel'] == 'lrdd' && !empty($attributes['template'])) {
279 $type = (empty($attributes['type']) ? '' : $attributes['type']);
281 $lrdd[$type] = $attributes['template'];
285 if (Network::isUrlBlocked($host_url)) {
286 Logger::info('Domain is blocked', ['url' => $host]);
290 self::$baseurl = $host_url;
292 Logger::info('Probing successful', ['host' => $host]);
298 * Check an URI for LRDD data
300 * @param string $uri Address that should be probed
301 * @return array uri data
302 * @throws HTTPException\InternalServerErrorException
304 public static function lrdd(string $uri): array
306 $data = self::getWebfingerArray($uri);
310 $webfinger = $data['webfinger'];
312 if (empty($webfinger['links'])) {
313 Logger::info('No webfinger links found', ['uri' => $uri]);
319 foreach ($webfinger['links'] as $link) {
320 $data[] = ['@attributes' => $link];
323 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
324 foreach ($webfinger['aliases'] as $alias) {
338 * Fetch information (protocol endpoints and user information) about a given uri
340 * @param string $uri Address that should be probed
341 * @param string $network Test for this specific network
342 * @param integer $uid User ID for the probe (only used for mails)
344 * @return array uri data
345 * @throws HTTPException\InternalServerErrorException
346 * @throws \ImagickException
348 public static function uri(string $uri, string $network = '', int $uid = -1): array
350 // Local profiles aren't probed via network
351 if (empty($network) && Contact::isLocal($uri)) {
352 $data = self::localProbe($uri);
359 $uid = DI::userSession()->getLocalUserId();
362 if (empty($network) || ($network == Protocol::ACTIVITYPUB)) {
363 $ap_profile = ActivityPub::probeProfile($uri);
368 self::$isTimeout = false;
370 if ($network != Protocol::ACTIVITYPUB) {
371 $data = self::detect($uri, $network, $uid, $ap_profile);
372 if (!is_array($data)) {
375 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
376 $networks = $data['networks'] ?? [];
377 unset($data['networks']);
378 if (!empty($data['network'])) {
379 $networks[$data['network']] = $data;
382 $data['networks'] = $networks;
383 } elseif (!empty($ap_profile)) {
384 $ap_profile['batch'] = '';
385 $data = array_merge($ap_profile, $data);
391 if (!isset($data['url'])) {
395 if (empty($data['photo'])) {
396 $data['photo'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
399 if (empty($data['name'])) {
400 if (!empty($data['nick'])) {
401 $data['name'] = $data['nick'];
404 if (empty($data['name'])) {
405 $data['name'] = $data['url'];
409 if (empty($data['nick'])) {
410 $data['nick'] = strtolower($data['name']);
412 if (strpos($data['nick'], ' ')) {
413 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
417 if (empty($data['network'])) {
418 $data['network'] = Protocol::PHANTOM;
421 $baseurl = parse_url($data['url'], PHP_URL_SCHEME) . '://' . parse_url($data['url'], PHP_URL_HOST);
422 if (empty($data['baseurl']) && ($data['network'] == Protocol::ACTIVITYPUB) && (rtrim($data['url'], '/') == $baseurl)) {
423 $data['baseurl'] = $baseurl;
426 if (!empty($data['baseurl']) && empty($data['gsid'])) {
427 $data['gsid'] = GServer::getID($data['baseurl']);
430 // Ensure that local connections always are DFRN
431 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
432 $data['network'] = Protocol::DFRN;
435 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
436 $data['hide'] = self::getHideStatus($data['url']);
439 return self::rearrangeData($data);
444 * Fetches the "hide" status from the profile
446 * @param string $url URL of the profile
447 * @return boolean "hide" status
449 private static function getHideStatus(string $url): bool
451 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::CONTENT_LENGTH => 1000000]);
452 if (!$curlResult->isSuccess()) {
456 // If it isn't a HTML file then exit
457 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
461 $body = $curlResult->getBody();
466 $doc = new DOMDocument();
467 @$doc->loadHTML($body);
469 $xpath = new DOMXPath($doc);
471 $list = $xpath->query('//meta[@name]');
472 foreach ($list as $node) {
474 if ($node->attributes->length) {
475 foreach ($node->attributes as $attribute) {
476 $meta_tag[$attribute->name] = $attribute->value;
480 if (empty($meta_tag['content'])) {
484 $content = strtolower(trim($meta_tag['content']));
486 switch (strtolower(trim($meta_tag['name']))) {
487 case 'dfrn-global-visibility':
488 if ($content == 'false') {
493 if (strpos($content, 'noindex') !== false) {
504 * Fetch the "subscribe" and add it to the result
506 * @param array $result Result array
507 * @param array $webfinger Webfinger data
509 * @return array result Altered/unaltered result array
511 private static function getSubscribeLink(array $result, array $webfinger): array
513 if (empty($webfinger['links'])) {
517 foreach ($webfinger['links'] as $link) {
518 if (!empty($link['template']) && ($link['rel'] === ActivityNamespace::OSTATUSSUB)) {
519 $result['subscribe'] = $link['template'];
527 * Get webfinger data from a given URI
529 * @param string $uri URI
531 * @return array Webfinger data
532 * @throws HTTPException\InternalServerErrorException
534 public static function getWebfingerArray(string $uri): array
536 $parts = parse_url($uri);
538 if (!empty($parts['scheme']) && !empty($parts['host'])) {
539 $host = $parts['host'];
540 if (!empty($parts['port'])) {
541 $host .= ':' . $parts['port'];
544 $baseurl = $parts['scheme'] . '://' . $host;
549 $path_parts = explode('/', trim($parts['path'] ?? '', '/'));
550 if (!empty($path_parts)) {
551 $nick = ltrim(end($path_parts), '@');
552 $addr = $nick . '@' . $host;
555 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
556 if (empty($webfinger)) {
557 $lrdd = self::hostMeta($host);
560 if (empty($webfinger) && empty($lrdd)) {
561 while (empty($lrdd) && empty($webfinger) && (sizeof($path_parts) > 1)) {
562 $host .= '/' . array_shift($path_parts);
563 $baseurl = $parts['scheme'] . '://' . $host;
566 $addr = $nick . '@' . $host;
569 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
570 if (empty($webfinger)) {
571 $lrdd = self::hostMeta($host);
575 if (empty($lrdd) && empty($webfinger)) {
579 } elseif (strstr($uri, '@')) {
580 // Remove "acct:" from the URI
581 $uri = str_replace('acct:', '', $uri);
583 $host = substr($uri, strpos($uri, '@') + 1);
584 $nick = substr($uri, 0, strpos($uri, '@'));
587 $webfinger = self::getWebfinger('https://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
588 if (self::$isTimeout) {
592 if (empty($webfinger)) {
593 $webfinger = self::getWebfinger('http://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
594 if (self::$isTimeout) {
598 $baseurl = 'https://' . $host;
601 if (empty($webfinger)) {
602 $lrdd = self::hostMeta($host);
603 if (self::$isTimeout) {
606 $baseurl = self::$baseurl;
608 $baseurl = 'http://' . $host;
611 Logger::info('URI was not detectable', ['uri' => $uri]);
615 if (empty($webfinger)) {
616 foreach ($lrdd as $type => $template) {
621 $webfinger = self::getWebfinger($template, $type, $uri, $addr);
625 if (empty($webfinger)) {
629 if ($webfinger['detected'] == $addr) {
630 $webfinger['nick'] = $nick;
631 $webfinger['addr'] = $addr;
634 $webfinger['baseurl'] = $baseurl;
640 * Perform network request for webfinger data
642 * @param string $template
643 * @param string $type
645 * @param string $addr
647 * @return array webfinger results
649 private static function getWebfinger(string $template, string $type, string $uri, string $addr): array
651 if (Network::isUrlBlocked($template)) {
652 Logger::info('Domain is blocked', ['url' => $template]);
656 // First try the address because this is the primary purpose of webfinger
659 $path = str_replace('{uri}', urlencode('acct:' . $addr), $template);
660 $webfinger = self::webfinger($path, $type);
661 if (self::$isTimeout) {
667 if (empty($webfinger) && $uri != $addr) {
669 $path = str_replace('{uri}', urlencode($uri), $template);
670 $webfinger = self::webfinger($path, $type);
671 if (self::$isTimeout) {
676 if (empty($webfinger)) {
680 return ['webfinger' => $webfinger, 'detected' => $detected];
684 * Fetch information (protocol endpoints and user information) about a given uri
686 * This function is only called by the "uri" function that adds caching and rearranging of data.
688 * @param string $uri Address that should be probed
689 * @param string $network Test for this specific network
690 * @param integer $uid User ID for the probe (only used for mails)
691 * @param array $ap_profile Previously probed AP profile
692 * @return array URI data
693 * @throws HTTPException\InternalServerErrorException
695 private static function detect(string $uri, string $network, int $uid, array $ap_profile): array
699 'network' => $network,
704 Hook::callAll('probe_detect', $hookData);
706 if (isset($hookData['result'])) {
707 return is_array($hookData['result']) ? $hookData['result'] : [];
710 $parts = parse_url($uri);
711 if (empty($parts['scheme']) && empty($parts['host']) && (empty($parts['path']) || strpos($parts['path'], '@') === false)) {
712 Logger::info('URI was not detectable', ['uri' => $uri]);
716 // If the URI starts with "mailto:" then jump directly to the mail detection
717 if (strpos($uri, 'mailto:') !== false) {
718 $uri = str_replace('mailto:', '', $uri);
719 return self::mail($uri, $uid);
722 if ($network == Protocol::MAIL) {
723 return self::mail($uri, $uid);
726 Logger::info('Probing start', ['uri' => $uri]);
728 if (!empty($ap_profile['addr']) && ($ap_profile['addr'] != $uri)) {
729 $data = self::getWebfingerArray($ap_profile['addr']);
733 $data = self::getWebfingerArray($uri);
737 if (!empty($parts['scheme'])) {
738 return self::feed($uri);
739 } elseif (!empty($uid)) {
740 return self::mail($uri, $uid);
746 $webfinger = $data['webfinger'];
747 $nick = $data['nick'] ?? '';
748 $addr = $data['addr'] ?? '';
749 $baseurl = $data['baseurl'] ?? '';
753 if (in_array($network, ['', Protocol::DFRN])) {
754 $result = self::dfrn($webfinger);
756 if ((!$result && ($network == '')) || ($network == Protocol::DIASPORA)) {
757 $result = self::diaspora($webfinger);
759 $result['networks'][Protocol::DIASPORA] = self::diaspora($webfinger);
761 if ((!$result && ($network == '')) || ($network == Protocol::OSTATUS)) {
762 $result = self::ostatus($webfinger);
764 $result['networks'][Protocol::OSTATUS] = self::ostatus($webfinger);
766 if (in_array($network, ['', Protocol::ZOT])) {
767 $result = self::zot($webfinger, $result, $baseurl);
769 if ((!$result && ($network == '')) || ($network == Protocol::PUMPIO)) {
770 $result = self::pumpio($webfinger, $addr, $baseurl);
772 if (empty($result['network']) && empty($ap_profile['network']) || ($network == Protocol::FEED)) {
773 $result = self::feed($uri);
775 // We overwrite the detected nick with our try if the previous routines hadn't detected it.
776 // Additionally, it is overwritten when the nickname doesn't make sense (contains spaces).
777 if ((empty($result['nick']) || (strstr($result['nick'], ' '))) && ($nick != '')) {
778 $result['nick'] = $nick;
781 if (empty($result['addr']) && ($addr != '')) {
782 $result['addr'] = $addr;
786 $result = self::getSubscribeLink($result, $webfinger);
788 if (empty($result['network'])) {
789 $result['network'] = Protocol::PHANTOM;
792 if (empty($result['baseurl']) && !empty($baseurl)) {
793 $result['baseurl'] = $baseurl;
796 if (empty($result['url'])) {
797 $result['url'] = $uri;
800 Logger::info('Probing done', ['uri' => $uri, 'network' => $result['network']]);
806 * Check for Zot contact
808 * @param array $webfinger Webfinger data
809 * @param array $data previously probed data
810 * @param string $baseUrl Base URL
812 * @return array Zot data
813 * @throws HTTPException\InternalServerErrorException
815 private static function zot(array $webfinger, array $data, string $baseurl): array
817 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
818 foreach ($webfinger['aliases'] as $alias) {
819 if (substr($alias, 0, 5) == 'acct:') {
820 $data['addr'] = substr($alias, 5);
825 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
826 $data['addr'] = substr($webfinger['subject'], 5);
830 foreach ($webfinger['links'] as $link) {
831 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
832 $zot_url = $link['href'];
836 if (empty($zot_url) && !empty($data['addr']) && !empty($baseurl)) {
837 $condition = ['nurl' => Strings::normaliseLink($baseurl), 'platform' => ['hubzilla']];
838 if (!DBA::exists('gserver', $condition)) {
841 $zot_url = $baseurl . '/.well-known/zot-info?address=' . $data['addr'];
844 if (empty($zot_url)) {
848 $data = self::pollZot($zot_url, $data);
850 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
851 foreach ($webfinger['aliases'] as $alias) {
852 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
853 $data['alias'] = $alias;
861 public static function pollZot(string $url, array $data): array
863 $curlResult = DI::httpClient()->get($url, HttpClientAccept::JSON);
864 if ($curlResult->isTimeout()) {
867 $content = $curlResult->getBody();
872 $json = json_decode($content, true);
873 if (!is_array($json)) {
877 if (empty($data['network'])) {
878 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
879 $data['network'] = Protocol::ZOT;
880 } elseif (!isset($json['protocols'])) {
881 $data['network'] = Protocol::ZOT;
885 if (!empty($json['guid']) && empty($data['guid'])) {
886 $data['guid'] = $json['guid'];
888 if (!empty($json['key']) && empty($data['pubkey'])) {
889 $data['pubkey'] = $json['key'];
891 if (!empty($json['name'])) {
892 $data['name'] = $json['name'];
894 if (!empty($json['photo'])) {
895 $data['photo'] = $json['photo'];
896 if (!empty($json['photo_updated'])) {
897 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
900 if (!empty($json['address'])) {
901 $data['addr'] = $json['address'];
903 if (!empty($json['url'])) {
904 $data['url'] = $json['url'];
906 if (!empty($json['connections_url'])) {
907 $data['poco'] = $json['connections_url'];
909 if (isset($json['searchable'])) {
910 $data['hide'] = !$json['searchable'];
912 if (!empty($json['public_forum'])) {
913 $data['community'] = $json['public_forum'];
914 $data['account-type'] = User::PAGE_FLAGS_COMMUNITY;
917 if (!empty($json['profile'])) {
918 $profile = $json['profile'];
919 if (!empty($profile['description'])) {
920 $data['about'] = $profile['description'];
922 if (!empty($profile['keywords'])) {
923 $keywords = implode(', ', $profile['keywords']);
924 if (!empty($keywords)) {
925 $data['keywords'] = $keywords;
930 if (!empty($profile['region'])) {
931 $loc['region'] = $profile['region'];
933 if (!empty($profile['country'])) {
934 $loc['country-name'] = $profile['country'];
936 $location = Profile::formatLocation($loc);
937 if (!empty($location)) {
938 $data['location'] = $location;
946 * Perform a webfinger request.
948 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
950 * @param string $url Address that should be probed
951 * @param string $type type
953 * @return array webfinger data
954 * @throws HTTPException\InternalServerErrorException
956 public static function webfinger(string $url, string $type): array
959 $curlResult = DI::httpClient()->get(
962 [HttpClientOptions::TIMEOUT => DI::config()->get('system', 'xrd_timeout', 20)]
964 } catch (\Throwable $e) {
965 Logger::notice($e->getMessage(), ['url' => $url, 'type' => $type, 'class' => get_class($e)]);
969 if ($curlResult->isTimeout()) {
970 self::$isTimeout = true;
973 $data = $curlResult->getBody();
975 $webfinger = json_decode($data, true);
976 if (!empty($webfinger)) {
977 if (!isset($webfinger['links'])) {
978 Logger::info('No json webfinger links', ['url' => $url]);
984 // If it is not JSON, maybe it is XML
985 $xrd = XML::parseString($data, true);
986 if (!is_object($xrd)) {
987 Logger::info('No webfinger data retrievable', ['url' => $url]);
991 $xrd_arr = XML::elementToArray($xrd);
992 if (!isset($xrd_arr['xrd']['link'])) {
993 Logger::info('No XML webfinger links', ['url' => $url]);
999 if (!empty($xrd_arr['xrd']['subject'])) {
1000 $webfinger['subject'] = $xrd_arr['xrd']['subject'];
1003 if (!empty($xrd_arr['xrd']['alias'])) {
1004 $webfinger['aliases'] = $xrd_arr['xrd']['alias'];
1007 $webfinger['links'] = [];
1009 foreach ($xrd_arr['xrd']['link'] as $value => $data) {
1010 if (!empty($data['@attributes'])) {
1011 $attributes = $data['@attributes'];
1012 } elseif ($value == '@attributes') {
1013 $attributes = $data;
1018 $webfinger['links'][] = $attributes;
1024 * Poll the Friendica specific noscrape page.
1026 * "noscrape" is a faster alternative to fetch the data from the hcard.
1027 * This functionality was originally created for the directory.
1029 * @param string $noscrape_url Link to the noscrape page
1030 * @param array $data The already fetched data
1032 * @return array noscrape data
1033 * @throws HTTPException\InternalServerErrorException
1035 private static function pollNoscrape(string $noscrape_url, array $data): array
1037 $curlResult = DI::httpClient()->get($noscrape_url, HttpClientAccept::JSON);
1038 if ($curlResult->isTimeout()) {
1039 self::$isTimeout = true;
1042 $content = $curlResult->getBody();
1044 Logger::info('Empty body', ['url' => $noscrape_url]);
1048 $json = json_decode($content, true);
1049 if (!is_array($json)) {
1050 Logger::info('No json data', ['url' => $noscrape_url]);
1054 if (!empty($json['fn'])) {
1055 $data['name'] = $json['fn'];
1058 if (!empty($json['addr'])) {
1059 $data['addr'] = $json['addr'];
1062 if (!empty($json['nick'])) {
1063 $data['nick'] = $json['nick'];
1066 if (!empty($json['guid'])) {
1067 $data['guid'] = $json['guid'];
1070 if (!empty($json['comm'])) {
1071 $data['community'] = $json['comm'];
1074 if (!empty($json['tags'])) {
1075 $keywords = implode(', ', $json['tags']);
1076 if ($keywords != '') {
1077 $data['keywords'] = $keywords;
1081 $location = Profile::formatLocation($json);
1083 $data['location'] = $location;
1086 if (!empty($json['about'])) {
1087 $data['about'] = $json['about'];
1090 if (!empty($json['xmpp'])) {
1091 $data['xmpp'] = $json['xmpp'];
1094 if (!empty($json['matrix'])) {
1095 $data['matrix'] = $json['matrix'];
1098 if (!empty($json['key'])) {
1099 $data['pubkey'] = $json['key'];
1102 if (!empty($json['photo'])) {
1103 $data['photo'] = $json['photo'];
1106 if (!empty($json['dfrn-request'])) {
1107 $data['request'] = $json['dfrn-request'];
1110 if (!empty($json['dfrn-confirm'])) {
1111 $data['confirm'] = $json['dfrn-confirm'];
1114 if (!empty($json['dfrn-notify'])) {
1115 $data['notify'] = $json['dfrn-notify'];
1118 if (!empty($json['dfrn-poll'])) {
1119 $data['poll'] = $json['dfrn-poll'];
1122 if (isset($json['hide'])) {
1123 $data['hide'] = (bool)$json['hide'];
1125 $data['hide'] = false;
1132 * Check for valid DFRN data
1134 * @param array $data DFRN data
1136 * @return int Number of errors
1138 public static function validDfrn(array $data): int
1141 if (!isset($data['key'])) {
1144 if (!isset($data['dfrn-request'])) {
1147 if (!isset($data['dfrn-confirm'])) {
1150 if (!isset($data['dfrn-notify'])) {
1153 if (!isset($data['dfrn-poll'])) {
1160 * Fetch data from a DFRN profile page and via "noscrape"
1162 * @param string $profile_link Link to the profile page
1163 * @return array profile data
1164 * @throws HTTPException\InternalServerErrorException
1165 * @throws \ImagickException
1167 public static function profile(string $profile_link): array
1171 Logger::info('Check profile', ['link' => $profile_link]);
1173 // Fetch data via noscrape - this is faster
1174 $noscrape_url = str_replace(['/hcard/', '/profile/'], '/noscrape/', $profile_link);
1175 $data = self::pollNoscrape($noscrape_url, $data);
1177 if (!isset($data['notify'])
1178 || !isset($data['confirm'])
1179 || !isset($data['request'])
1180 || !isset($data['poll'])
1181 || !isset($data['name'])
1182 || !isset($data['photo'])
1184 $data = self::pollHcard($profile_link, $data, true);
1188 if (empty($data['addr']) || empty($data['nick'])) {
1189 $probe_data = self::uri($profile_link);
1190 $data['addr'] = ($data['addr'] ?? '') ?: $probe_data['addr'];
1191 $data['nick'] = ($data['nick'] ?? '') ?: $probe_data['nick'];
1195 'addr' => $data['addr'],
1196 'nick' => $data['nick'],
1197 'dfrn-request' => $data['request'] ?? null,
1198 'dfrn-confirm' => $data['confirm'] ?? null,
1199 'dfrn-notify' => $data['notify'] ?? null,
1200 'dfrn-poll' => $data['poll'] ?? null,
1201 'photo' => $data['photo'] ?? null,
1202 'fn' => $data['name'] ?? null,
1203 'key' => $data['pubkey'] ?? null,
1206 Logger::debug('Result', ['link' => $profile_link, 'data' => $prof_data]);
1212 * Check for DFRN contact
1214 * @param array $webfinger Webfinger data
1215 * @return array DFRN data
1216 * @throws HTTPException\InternalServerErrorException
1218 private static function dfrn(array $webfinger): array
1222 // The array is reversed to take into account the order of preference for same-rel links
1223 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1224 foreach (array_reverse($webfinger['links']) as $link) {
1225 if (($link['rel'] == ActivityNamespace::DFRN) && !empty($link['href'])) {
1226 $data['network'] = Protocol::DFRN;
1227 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1228 $data['poll'] = $link['href'];
1229 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1230 $data['url'] = $link['href'];
1231 } elseif (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1232 $hcard_url = $link['href'];
1233 } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1234 $data['poco'] = $link['href'];
1235 } elseif (($link['rel'] == 'http://webfinger.net/rel/avatar') && !empty($link['href'])) {
1236 $data['photo'] = $link['href'];
1237 } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1238 $data['baseurl'] = trim($link['href'], '/');
1239 } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1240 $data['guid'] = $link['href'];
1241 } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1242 $data['pubkey'] = base64_decode($link['href']);
1244 if (strstr($data['pubkey'], 'RSA ')) {
1245 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1250 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1251 foreach ($webfinger['aliases'] as $alias) {
1252 if (empty($data['url']) && !strstr($alias, '@')) {
1253 $data['url'] = $alias;
1254 } elseif (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
1255 $data['alias'] = $alias;
1256 } elseif (substr($alias, 0, 5) == 'acct:') {
1257 $data['addr'] = substr($alias, 5);
1262 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1263 $data['addr'] = substr($webfinger['subject'], 5);
1266 if (!isset($data['network']) || ($hcard_url == '')) {
1270 // Fetch data via noscrape - this is faster
1271 $noscrape_url = str_replace('/hcard/', '/noscrape/', $hcard_url);
1272 $data = self::pollNoscrape($noscrape_url, $data);
1274 if (isset($data['notify'])
1275 && isset($data['confirm'])
1276 && isset($data['request'])
1277 && isset($data['poll'])
1278 && isset($data['name'])
1279 && isset($data['photo'])
1284 $data = self::pollHcard($hcard_url, $data, true);
1290 * Poll the hcard page (Diaspora and Friendica specific)
1292 * @param string $hcard_url Link to the hcard page
1293 * @param array $data The already fetched data
1294 * @param boolean $dfrn Poll DFRN specific data
1295 * @return array hcard data
1296 * @throws HTTPException\InternalServerErrorException
1298 private static function pollHcard(string $hcard_url, array $data, bool $dfrn = false): array
1300 $curlResult = DI::httpClient()->get($hcard_url, HttpClientAccept::HTML);
1301 if ($curlResult->isTimeout()) {
1302 self::$isTimeout = true;
1305 $content = $curlResult->getBody();
1306 if (empty($content)) {
1310 $doc = new DOMDocument();
1311 if (!@$doc->loadHTML($content)) {
1315 $xpath = new DomXPath($doc);
1317 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1318 if (!is_object($vcards)) {
1322 if (!isset($data['baseurl'])) {
1323 $data['baseurl'] = '';
1326 if ($vcards->length > 0) {
1327 $vcard = $vcards->item(0);
1329 // We have to discard the guid from the hcard in favour of the guid from lrdd
1330 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1331 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1332 if (($search->length > 0) && empty($data['guid'])) {
1333 $data['guid'] = $search->item(0)->nodeValue;
1336 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1337 if ($search->length > 0) {
1338 $data['nick'] = $search->item(0)->nodeValue;
1341 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1342 if ($search->length > 0) {
1343 $data['name'] = $search->item(0)->nodeValue;
1346 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' given_name ')]", $vcard); // */
1347 if ($search->length > 0) {
1348 $data["given_name"] = $search->item(0)->nodeValue;
1351 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' family_name ')]", $vcard); // */
1352 if ($search->length > 0) {
1353 $data["family_name"] = $search->item(0)->nodeValue;
1356 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1357 if ($search->length > 0) {
1358 $data['hide'] = (strtolower($search->item(0)->nodeValue) != 'true');
1361 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1362 if ($search->length > 0) {
1363 $data['pubkey'] = $search->item(0)->nodeValue;
1364 if (strstr($data['pubkey'], 'RSA ')) {
1365 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1369 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1370 if ($search->length > 0) {
1371 $data['baseurl'] = trim($search->item(0)->nodeValue, '/');
1376 if (!empty($vcard)) {
1377 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1378 foreach ($photos as $photo) {
1380 foreach ($photo->attributes as $attribute) {
1381 $attr[$attribute->name] = trim($attribute->value);
1384 if (isset($attr['src']) && isset($attr['width'])) {
1385 $avatars[$attr['width']] = self::fixAvatar($attr['src'], $data['baseurl']);
1388 // We don't have a width. So we just take everything that we got.
1389 // This is a Hubzilla workaround which doesn't send a width.
1390 if (!$avatars && !empty($attr['src'])) {
1391 $avatars[] = self::fixAvatar($attr['src'], $data['baseurl']);
1398 $data['photo'] = array_pop($avatars);
1400 $data['photo_medium'] = array_pop($avatars);
1404 $data['photo_small'] = array_pop($avatars);
1409 // Poll DFRN specific data
1410 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1411 if ($search->length > 0) {
1412 foreach ($search as $link) {
1413 //$data['request'] = $search->item(0)->nodeValue;
1415 foreach ($link->attributes as $attribute) {
1416 $attr[$attribute->name] = trim($attribute->value);
1419 $data[substr($attr['rel'], 5)] = $attr['href'];
1423 // Older Friendica versions had used the "uid" field differently than newer versions
1424 if (!empty($data['nick']) && !empty($data['guid']) && ($data['nick'] == $data['guid'])) {
1425 unset($data['guid']);
1433 * Check for Diaspora contact
1435 * @param array $webfinger Webfinger data
1437 * @return array Diaspora data
1438 * @throws HTTPException\InternalServerErrorException
1440 private static function diaspora(array $webfinger): array
1445 // The array is reversed to take into account the order of preference for same-rel links
1446 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1447 foreach (array_reverse($webfinger['links']) as $link) {
1448 if (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1449 $hcard_url = $link['href'];
1450 } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1451 $data['baseurl'] = trim($link['href'], '/');
1452 } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1453 $data['guid'] = $link['href'];
1454 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1455 $data['url'] = $link['href'];
1456 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && empty($link['type']) && !empty($link['href'])) {
1457 $profile_url = $link['href'];
1458 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1459 $data['poll'] = $link['href'];
1460 } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1461 $data['poco'] = $link['href'];
1462 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1463 $data['notify'] = $link['href'];
1464 } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1465 $data['pubkey'] = base64_decode($link['href']);
1467 if (strstr($data['pubkey'], 'RSA ')) {
1468 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1473 if (empty($data['url']) && !empty($profile_url)) {
1474 $data['url'] = $profile_url;
1477 if (empty($data['url']) || empty($hcard_url)) {
1481 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1482 foreach ($webfinger['aliases'] as $alias) {
1483 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data['url']) && ! strstr($alias, '@')) {
1484 $data['alias'] = $alias;
1485 } elseif (substr($alias, 0, 5) == 'acct:') {
1486 $data['addr'] = substr($alias, 5);
1491 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1492 $data['addr'] = substr($webfinger['subject'], 5);
1495 // Fetch further information from the hcard
1496 $data = self::pollHcard($hcard_url, $data);
1502 if (!empty($data['url'])
1503 && !empty($data['guid'])
1504 && !empty($data['baseurl'])
1505 && !empty($data['pubkey'])
1506 && !empty($hcard_url)
1508 $data['network'] = Protocol::DIASPORA;
1509 $data['manually-approve'] = false;
1511 // The Diaspora handle must always be lowercase
1512 if (!empty($data['addr'])) {
1513 $data['addr'] = strtolower($data['addr']);
1516 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1517 $data['notify'] = $data['baseurl'] . '/receive/users/' . $data['guid'];
1518 $data['batch'] = $data['baseurl'] . '/receive/public';
1527 * Check for OStatus contact
1529 * @param array $webfinger Webfinger data
1530 * @param bool $short Short detection mode
1532 * @return array|bool OStatus data or "false" on error or "true" on short mode
1533 * @throws HTTPException\InternalServerErrorException
1535 private static function ostatus(array $webfinger, bool $short = false)
1539 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1540 foreach ($webfinger['aliases'] as $alias) {
1541 if (strstr($alias, '@') && !strstr(Strings::normaliseLink($alias), 'http://')) {
1542 $data['addr'] = str_replace('acct:', '', $alias);
1547 if (!empty($webfinger['subject']) && strstr($webfinger['subject'], '@')
1548 && !strstr(Strings::normaliseLink($webfinger['subject']), 'http://')
1550 $data['addr'] = str_replace('acct:', '', $webfinger['subject']);
1553 if (!empty($webfinger['links'])) {
1554 // The array is reversed to take into account the order of preference for same-rel links
1555 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1556 foreach (array_reverse($webfinger['links']) as $link) {
1557 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1558 && (($link['type'] ?? '') == 'text/html')
1559 && ($link['href'] != '')
1561 $data['url'] = $data['alias'] = $link['href'];
1562 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1563 $data['notify'] = $link['href'];
1564 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1565 $data['poll'] = $link['href'];
1566 } elseif (($link['rel'] == 'magic-public-key') && !empty($link['href'])) {
1567 $pubkey = $link['href'];
1569 if (substr($pubkey, 0, 5) === 'data:') {
1570 if (strstr($pubkey, ',')) {
1571 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1573 $pubkey = substr($pubkey, 5);
1575 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1576 $curlResult = DI::httpClient()->get($pubkey, HttpClientAccept::MAGIC_KEY);
1577 if ($curlResult->isTimeout()) {
1578 self::$isTimeout = true;
1579 return $short ? false : [];
1581 Logger::debug('Fetched public key', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $pubkey]);
1582 $pubkey = $curlResult->getBody();
1586 $data['pubkey'] = Salmon::magicKeyToPem($pubkey);
1587 } catch (\Throwable $e) {
1594 if (isset($data['notify']) && isset($data['pubkey'])
1595 && isset($data['poll'])
1596 && isset($data['url'])
1598 $data['network'] = Protocol::OSTATUS;
1599 $data['manually-approve'] = false;
1601 return $short ? false : [];
1608 // Fetch all additional data from the feed
1609 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::FEED_XML);
1610 if ($curlResult->isTimeout()) {
1611 self::$isTimeout = true;
1614 $feed = $curlResult->getBody();
1615 $feed_data = Feed::import($feed);
1620 if (!empty($feed_data['header']['author-name'])) {
1621 $data['name'] = $feed_data['header']['author-name'];
1623 if (!empty($feed_data['header']['author-nick'])) {
1624 $data['nick'] = $feed_data['header']['author-nick'];
1626 if (!empty($feed_data['header']['author-avatar'])) {
1627 $data['photo'] = self::fixAvatar($feed_data['header']['author-avatar'], $data['url']);
1629 if (!empty($feed_data['header']['author-id'])) {
1630 $data['alias'] = $feed_data['header']['author-id'];
1632 if (!empty($feed_data['header']['author-location'])) {
1633 $data['location'] = $feed_data['header']['author-location'];
1635 if (!empty($feed_data['header']['author-about'])) {
1636 $data['about'] = $feed_data['header']['author-about'];
1638 // OStatus has serious issues when the url doesn't fit (ssl vs. non ssl)
1639 // So we take the value that we just fetched, although the other one worked as well
1640 if (!empty($feed_data['header']['author-link'])) {
1641 $data['url'] = $feed_data['header']['author-link'];
1644 if ($data['url'] == $data['alias']) {
1645 $data['alias'] = '';
1648 /// @todo Fetch location and "about" from the feed as well
1653 * Fetch data from a pump.io profile page
1655 * @param string $profile_link Link to the profile page
1657 * @return array Profile data
1659 private static function pumpioProfileData(string $profile_link, string $baseurl): array
1661 $curlResult = DI::httpClient()->get($profile_link, HttpClientAccept::HTML);
1662 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
1666 $doc = new DOMDocument();
1667 if (!@$doc->loadHTML($curlResult->getBody())) {
1671 $xpath = new DomXPath($doc);
1674 $data['name'] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1676 if ($data['name'] == '') {
1677 // This is ugly - but pump.io doesn't seem to know a better way for it
1678 $data['name'] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1679 $pos = strpos($data['name'], chr(10));
1681 $data['name'] = trim(substr($data['name'], 0, $pos));
1685 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1687 if ($data['location'] == '') {
1688 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1691 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1693 if ($data['about'] == '') {
1694 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1697 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1699 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1702 foreach ($avatar->attributes as $attribute) {
1703 if (($attribute->name == 'src') && !empty($attribute->value)) {
1704 $data['photo'] = Network::addBasePath($attribute->value, $baseurl);
1713 * Check for pump.io contact
1715 * @param array $webfinger Webfinger data
1716 * @param string $addr
1718 * @return array pump.io data
1720 private static function pumpio(array $webfinger, string $addr, string $baseurl): array
1723 // The array is reversed to take into account the order of preference for same-rel links
1724 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1725 foreach (array_reverse($webfinger['links']) as $link) {
1726 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1727 && (($link['type'] ?? '') == 'text/html')
1728 && ($link['href'] != '')
1730 $data['url'] = $link['href'];
1731 } elseif (($link['rel'] == 'activity-inbox') && ($link['href'] != '')) {
1732 $data['notify'] = $link['href'];
1733 } elseif (($link['rel'] == 'activity-outbox') && ($link['href'] != '')) {
1734 $data['poll'] = $link['href'];
1735 } elseif (($link['rel'] == 'dialback') && ($link['href'] != '')) {
1736 $data['dialback'] = $link['href'];
1739 if (isset($data['poll']) && isset($data['notify'])
1740 && isset($data['dialback'])
1741 && isset($data['url'])
1743 // by now we use these fields only for the network type detection
1744 // So we unset all data that isn't used at the moment
1745 unset($data['dialback']);
1747 $data['network'] = Protocol::PUMPIO;
1752 $profile_data = self::pumpioProfileData($data['url'], $baseurl);
1754 if (!$profile_data) {
1758 $data = array_merge($data, $profile_data);
1760 if (($addr != '') && ($data['name'] != '')) {
1761 $name = trim(str_replace($addr, '', $data['name']));
1763 $data['name'] = $name;
1771 * Checks HTML page for RSS feed link
1773 * @param string $url Page link
1774 * @param string $body Page body string
1776 * @return string|false Feed link or false if body was invalid HTML document
1778 public static function getFeedLink(string $url, string $body)
1784 $doc = new DOMDocument();
1785 if (!@$doc->loadHTML($body)) {
1789 $xpath = new DOMXPath($doc);
1791 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1792 $feedUrl = $feedUrl ?: $xpath->evaluate('string(/html/head/link[@type="application/atom+xml" and @rel="alternate"]/@href)');
1794 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1800 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1802 * Loosely based on RFC 1808
1804 * @see https://tools.ietf.org/html/rfc1808
1806 * @param string $href The potential relative href found in the HTML document
1807 * @param string $base The HTML document URL
1808 * @param DOMXPath $xpath The HTML document XPath
1810 * @return string Absolute URL
1812 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath): string
1814 if (filter_var($href, FILTER_VALIDATE_URL)) {
1818 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1820 $baseParts = parse_url($base);
1821 if (empty($baseParts['host'])) {
1825 // Naked domain case (scheme://basehost)
1826 $path = $baseParts['path'] ?? '/';
1828 // Remove the filename part of the path if it exists (/base/path/file)
1829 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1831 $hrefParts = parse_url($href);
1833 if (!empty($hrefParts['path'])) {
1834 // Root path case (/path) including relative scheme case (//host/path)
1835 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1836 $path = $hrefParts['path'];
1838 $path = $path . '/' . $hrefParts['path'];
1840 // Resolve arbitrary relative path
1841 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1842 $parts = array_filter(explode('/', $path), 'strlen');
1844 foreach ($parts as $part) {
1845 if ('.' == $part) continue;
1846 if ('..' == $part) {
1847 array_pop($absolutes);
1849 $absolutes[] = $part;
1853 $path = '/' . implode('/', $absolutes);
1857 // Relative scheme case (//host/path)
1858 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1859 $baseParts['path'] = $path;
1860 unset($baseParts['query']);
1861 unset($baseParts['fragment']);
1863 return Network::unparseURL($baseParts);
1867 * Check for feed contact
1869 * @param string $url Profile link
1870 * @param boolean $probe Do a probe if the page contains a feed link
1872 * @return array feed data
1873 * @throws HTTPException\InternalServerErrorException
1875 private static function feed(string $url, bool $probe = true): array
1878 $curlResult = DI::httpClient()->get($url, HttpClientAccept::FEED_XML);
1879 } catch(\Throwable $e) {
1880 DI::logger()->info('Error requesting feed URL', ['url' => $url, 'exception' => $e]);
1884 if ($curlResult->isTimeout()) {
1885 self::$isTimeout = true;
1889 $feed = $curlResult->getBody();
1890 $feed_data = Feed::import($feed);
1897 $feed_url = self::getFeedLink($url, $feed);
1903 return self::feed($feed_url, false);
1906 if (!empty($feed_data['header']['author-name'])) {
1907 $data['name'] = $feed_data['header']['author-name'];
1910 if (!empty($feed_data['header']['author-nick'])) {
1911 $data['nick'] = $feed_data['header']['author-nick'];
1914 if (!empty($feed_data['header']['author-avatar'])) {
1915 $data['photo'] = $feed_data['header']['author-avatar'];
1918 if (!empty($feed_data['header']['author-id'])) {
1919 $data['alias'] = $feed_data['header']['author-id'];
1922 $data['url'] = $url;
1923 $data['poll'] = $url;
1925 $data['network'] = Protocol::FEED;
1931 * Check for mail contact
1933 * @param string $uri Profile link
1934 * @param integer $uid User ID
1936 * @return array mail data
1937 * @throws \Exception
1939 private static function mail(string $uri, int $uid): array
1941 if (!Network::isEmailDomainValid($uri)) {
1949 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1951 $condition = ["`uid` = ? AND `server` != ''", $uid];
1952 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1953 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1955 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1959 $mailbox = Email::constructMailboxName($mailacct);
1961 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1962 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1967 $msgs = Email::poll($mbox, $uri);
1968 Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
1970 if (!count($msgs)) {
1974 $phost = substr($uri, strpos($uri, '@') + 1);
1978 'network' => Protocol::MAIL,
1979 'name' => substr($uri, 0, strpos($uri, '@')),
1980 'photo' => Network::lookupAvatarByEmail($uri),
1981 'url' => 'mailto:' . $uri,
1982 'notify' => 'smtp ' . Strings::getRandomHex(),
1983 'poll' => 'email ' . Strings::getRandomHex(),
1986 $data['nick'] = $data['name'];
1988 $x = Email::messageMeta($mbox, $msgs[0]);
1990 if (stristr($x[0]->from, $uri)) {
1991 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1992 } elseif (stristr($x[0]->to, $uri)) {
1993 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1997 foreach ($adr as $feadr) {
1998 if ((strcasecmp($feadr->mailbox, $data['name']) == 0)
1999 &&(strcasecmp($feadr->host, $phost) == 0)
2000 && (strlen($feadr->personal))
2002 $personal = imap_mime_header_decode($feadr->personal);
2004 foreach ($personal as $perspart) {
2005 if ($perspart->charset != 'default') {
2006 $data['name'] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
2008 $data['name'] .= $perspart->text;
2015 if (!empty($mbox)) {
2023 * Mix two paths together to possibly fix missing parts
2025 * @param string $avatar Path to the avatar
2026 * @param string $base Another path that is hopefully complete
2028 * @return string fixed avatar path
2029 * @throws \Exception
2031 public static function fixAvatar(string $avatar, string $base): string
2033 $base_parts = parse_url($base);
2035 // Remove all parts that could create a problem
2036 unset($base_parts['path']);
2037 unset($base_parts['query']);
2038 unset($base_parts['fragment']);
2040 $avatar_parts = parse_url($avatar);
2043 $parts = array_merge($base_parts, $avatar_parts);
2045 // And put them together again
2046 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
2047 $host = isset($parts['host']) ? $parts['host'] : '';
2048 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
2049 $path = isset($parts['path']) ? $parts['path'] : '';
2050 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
2051 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
2053 $fixed = $scheme.$host.$port.$path.$query.$fragment;
2055 Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
2061 * Fetch the last date that the contact had posted something (publically)
2063 * @param array $data probing result
2065 * @return string last activity
2067 public static function getLastUpdate(array $data): string
2069 $uid = User::getIdForURL($data['url']);
2071 $contact = Contact::selectFirst(['url', 'last-item'], ['self' => true, 'uid' => $uid]);
2072 if (!empty($contact['last-item'])) {
2073 return $contact['last-item'];
2077 if ($lastUpdate = self::updateFromNoScrape($data)) {
2081 if (!empty($data['outbox'])) {
2082 return self::updateFromOutbox($data['outbox'], $data);
2083 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
2084 return self::updateFromOutbox($data['poll'], $data);
2085 } elseif (!empty($data['poll'])) {
2086 return self::updateFromFeed($data);
2093 * Fetch the last activity date from the "noscrape" endpoint
2095 * @param array $data Probing result
2097 * @return string last activity or true if update was successful or the server was unreachable
2099 private static function updateFromNoScrape(array $data): string
2101 if (empty($data['baseurl'])) {
2105 // Check the 'noscrape' endpoint when it is a Friendica server
2106 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
2107 Strings::normaliseLink($data['baseurl'])]);
2108 if (!DBA::isResult($gserver)) {
2112 $curlResult = DI::httpClient()->get($gserver['noscrape'] . '/' . $data['nick'], HttpClientAccept::JSON);
2114 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
2115 $noscrape = json_decode($curlResult->getBody(), true);
2116 if (!empty($noscrape) && !empty($noscrape['updated'])) {
2117 return DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2125 * Fetch the last activity date from an ActivityPub Outbox
2127 * @param string $feed
2128 * @param array $data Probing result
2130 * @return string last activity
2131 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2133 private static function updateFromOutbox(string $feed, array $data): string
2135 $outbox = ActivityPub::fetchContent($feed);
2136 if (empty($outbox)) {
2140 if (!empty($outbox['orderedItems'])) {
2141 $items = $outbox['orderedItems'];
2142 } elseif (!empty($outbox['first']['orderedItems'])) {
2143 $items = $outbox['first']['orderedItems'];
2144 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2145 return self::updateFromOutbox($outbox['first']['href'], $data);
2146 } elseif (!empty($outbox['first'])) {
2147 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2148 return self::updateFromOutbox($outbox['first'], $data);
2150 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2158 foreach ($items as $activity) {
2159 if (!empty($activity['published'])) {
2160 $published = DateTimeFormat::utc($activity['published']);
2161 } elseif (!empty($activity['object']['published'])) {
2162 $published = DateTimeFormat::utc($activity['object']['published']);
2167 if ($last_updated < $published) {
2168 $last_updated = $published;
2172 if (!empty($last_updated)) {
2173 return $last_updated;
2180 * Fetch the last activity date from an XML feed
2182 * @param array $data Probing result
2183 * @return string last activity
2185 private static function updateFromFeed(array $data): string
2187 // Search for the newest entry in the feed
2188 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::ATOM_XML);
2189 if (!$curlResult->isSuccess() || !$curlResult->getBody()) {
2193 $doc = new DOMDocument();
2194 @$doc->loadXML($curlResult->getBody());
2196 $xpath = new DOMXPath($doc);
2197 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2199 $entries = $xpath->query('/atom:feed/atom:entry');
2203 foreach ($entries as $entry) {
2204 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2205 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
2206 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2207 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2209 if (empty($published) || empty($updated)) {
2210 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2214 if ($last_updated < $published) {
2215 $last_updated = $published;
2218 if ($last_updated < $updated) {
2219 $last_updated = $updated;
2223 if (!empty($last_updated)) {
2224 return $last_updated;
2231 * Probe data from local profiles without network traffic
2233 * @param string $url
2235 * @return array probed data
2236 * @throws HTTPException\InternalServerErrorException
2237 * @throws HTTPException\NotFoundException
2239 private static function localProbe(string $url): array
2242 $uid = User::getIdForURL($url);
2244 throw new HTTPException\NotFoundException('User not found.');
2247 $owner = User::getOwnerDataById($uid);
2248 $approfile = ActivityPub\Transmitter::getProfile($uid);
2250 $split_name = Diaspora::splitName($owner['name']);
2252 if (empty($owner['gsid'])) {
2253 $owner['gsid'] = GServer::getID($approfile['generator']['url']);
2257 'name' => $owner['name'], 'nick' => $owner['nick'], 'guid' => $approfile['diaspora:guid'] ?? '',
2258 'url' => $owner['url'], 'addr' => $owner['addr'], 'alias' => $owner['alias'],
2259 'photo' => User::getAvatarUrl($owner),
2260 'header' => $owner['header'] ? Contact::getHeaderUrlForId($owner['id'], $owner['updated']) : '',
2261 'account-type' => $owner['contact-type'], 'community' => ($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY),
2262 'keywords' => $owner['keywords'], 'location' => $owner['location'], 'about' => $owner['about'],
2263 'xmpp' => $owner['xmpp'], 'matrix' => $owner['matrix'],
2264 'hide' => !$owner['net-publish'], 'batch' => '', 'notify' => $owner['notify'],
2265 'poll' => $owner['poll'], 'request' => $owner['request'], 'confirm' => $owner['confirm'],
2266 'subscribe' => $approfile['generator']['url'] . '/contact/follow?url={uri}', 'poco' => $owner['poco'],
2267 'following' => $approfile['following'], 'followers' => $approfile['followers'],
2268 'inbox' => $approfile['inbox'], 'outbox' => $approfile['outbox'],
2269 'sharedinbox' => $approfile['endpoints']['sharedInbox'], 'network' => Protocol::DFRN,
2270 'pubkey' => $owner['upubkey'], 'baseurl' => $approfile['generator']['url'], 'gsid' => $owner['gsid'],
2271 'manually-approve' => in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]),
2273 Protocol::DIASPORA => [
2274 'name' => $owner['name'],
2275 'given_name' => $split_name['first'],
2276 'family_name' => $split_name['last'],
2277 'nick' => $owner['nick'],
2278 'guid' => $approfile['diaspora:guid'],
2279 'url' => $owner['url'],
2280 'addr' => $owner['addr'],
2281 'alias' => $owner['alias'],
2282 'photo' => $owner['photo'],
2283 'photo_medium' => $owner['thumb'],
2284 'photo_small' => $owner['micro'],
2285 'batch' => $approfile['generator']['url'] . '/receive/public',
2286 'notify' => $owner['notify'],
2287 'poll' => $owner['poll'],
2288 'poco' => $owner['poco'],
2289 'network' => Protocol::DIASPORA,
2290 'pubkey' => $owner['upubkey'],
2294 } catch (Exception $e) {
2295 // Default values for nonexistent targets
2297 'name' => $url, 'nick' => $url, 'url' => $url, 'network' => Protocol::PHANTOM,
2298 'photo' => DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO
2302 return self::rearrangeData($data);