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\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\Diaspora;
42 use Friendica\Protocol\Email;
43 use Friendica\Protocol\Feed;
44 use Friendica\Protocol\Salmon;
45 use Friendica\Util\Crypto;
46 use Friendica\Util\DateTimeFormat;
47 use Friendica\Util\Network;
48 use Friendica\Util\Strings;
49 use Friendica\Util\XML;
50 use GuzzleHttp\Psr7\Uri;
53 * This class contain functions for probing URL
57 const HOST_META = '/.well-known/host-meta';
58 const WEBFINGER = '/.well-known/webfinger?resource={uri}';
61 * @var string Base URL
63 private static $baseurl;
66 * @var boolean Whether a timeout has occurred
68 private static $isTimeout;
71 * Checks if the provided network can be probed
73 * @param string $network
77 public static function isProbable(string $network): bool
79 return (in_array($network, array_merge(Protocol::FEDERATED, [Protocol::ZOT, Protocol::PHANTOM])));
83 * Remove stuff from an URI that doesn't belong there
85 * @param string $rawUri
86 * @return string Cleaned URI
88 public static function cleanURI(string $rawUri): string
90 // At first remove leading and trailing junk
91 $rawUri = trim($rawUri, "@#?: \t\n\r\0\x0B");
93 $rawUri = Network::convertToIdn($rawUri);
95 $uri = new Uri($rawUri);
96 if (!$uri->getScheme()) {
97 return $uri->__toString();
100 // Remove the URL fragment, since these shouldn't be part of any profile URL
101 $uri = $uri->withFragment('');
103 return $uri->__toString();
107 * Rearrange the array so that it always has the same order
109 * @param array $data Unordered data
110 * @return array Ordered data
112 private static function rearrangeData(array $data): array
114 $fields = ['name', 'given_name', 'family_name', 'nick', 'guid', 'url', 'addr', 'alias',
115 'photo', 'photo_medium', 'photo_small', 'header',
116 'account-type', 'community', 'keywords', 'location', 'about', 'xmpp', 'matrix',
117 'hide', 'batch', 'notify', 'poll', 'request', 'confirm', 'subscribe', 'poco',
118 'following', 'followers', 'inbox', 'outbox', 'sharedinbox',
119 'priority', 'network', 'pubkey', 'manually-approve', 'baseurl', 'gsid'];
121 $numeric_fields = ['gsid', 'hide', 'account-type', 'manually-approve'];
123 if (!empty($data['photo'])) {
124 $data['photo'] = Network::addBasePath($data['photo'], $data['url']);
126 if (!Network::isValidHttpUrl($data['photo'])) {
127 Logger::warning('Invalid URL for photo', ['url' => $data['url'], 'photo' => $data['photo']]);
128 unset($data['photo']);
133 foreach ($fields as $field) {
134 if (isset($data[$field])) {
135 if (in_array($field, $numeric_fields)) {
136 $newdata[$field] = (int)$data[$field];
138 $newdata[$field] = trim($data[$field]);
140 } elseif (!in_array($field, $numeric_fields)) {
141 $newdata[$field] = '';
143 $newdata[$field] = null;
147 $newdata['networks'] = [];
148 foreach ([Protocol::DIASPORA, Protocol::OSTATUS] as $network) {
149 if (!empty($data['networks'][$network])) {
150 $data['networks'][$network]['subscribe'] = $newdata['subscribe'] ?? '';
151 if (empty($data['networks'][$network]['baseurl'])) {
152 $data['networks'][$network]['baseurl'] = $newdata['baseurl'] ?? '';
154 $newdata['baseurl'] = $data['networks'][$network]['baseurl'];
156 if (!empty($newdata['baseurl'])) {
157 $newdata['gsid'] = $data['networks'][$network]['gsid'] = GServer::getID($newdata['baseurl']);
159 $newdata['gsid'] = $data['networks'][$network]['gsid'] = null;
162 $newdata['networks'][$network] = self::rearrangeData($data['networks'][$network]);
163 unset($newdata['networks'][$network]['networks']);
167 // We don't use the "priority" field anymore and replace it with a dummy.
168 $newdata['priority'] = 0;
174 * Check if the hostname belongs to the own server
176 * @param string $host The hostname that is to be checked
177 * @return bool Does the testes hostname belongs to the own server?
179 private static function ownHost(string $host): bool
181 $own_host = DI::baseUrl()->getHost();
183 $parts = parse_url($host);
185 if (!isset($parts['scheme'])) {
186 $parts = parse_url('http://' . $host);
189 if (!isset($parts['host'])) {
192 return $parts['host'] == $own_host;
196 * Probes for webfinger path via "host-meta"
198 * We have to check if the servers in the future still will offer this.
199 * It seems as if it was dropped from the standard.
201 * @param string $host The host part of an url
203 * @return array with template and type of the webfinger template for JSON or XML
204 * @throws HTTPException\InternalServerErrorException
206 private static function hostMeta(string $host): array
208 // Reset the static variable
211 // Handles the case when the hostname contains the scheme
212 if (!parse_url($host, PHP_URL_SCHEME)) {
213 $ssl_url = 'https://' . $host . self::HOST_META;
214 $url = 'http://' . $host . self::HOST_META;
216 $ssl_url = $host . self::HOST_META;
220 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
222 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
225 $curlResult = DI::httpClient()->get($ssl_url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
226 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
227 if ($curlResult->isSuccess()) {
228 $xml = $curlResult->getBody();
229 $xrd = XML::parseString($xml, true);
231 $host_url = 'https://' . $host;
235 } elseif ($curlResult->isTimeout()) {
236 Logger::info('Probing timeout', ['url' => $ssl_url]);
237 self::$isTimeout = true;
241 if (!is_object($xrd) && !empty($url)) {
242 $curlResult = DI::httpClient()->get($url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
243 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
244 if ($curlResult->isTimeout()) {
245 Logger::info('Probing timeout', ['url' => $url]);
246 self::$isTimeout = true;
248 } elseif ($connection_error && $ssl_connection_error) {
249 self::$isTimeout = true;
253 $xml = $curlResult->getBody();
254 $xrd = XML::parseString($xml, true);
255 $host_url = 'http://'.$host;
257 if (!is_object($xrd)) {
258 Logger::info('No xrd object found', ['host' => $host]);
262 $links = XML::elementToArray($xrd);
263 if (!isset($links['xrd']['link'])) {
264 Logger::info('No xrd data found', ['host' => $host]);
270 foreach ($links['xrd']['link'] as $value => $link) {
271 if (!empty($link['@attributes'])) {
272 $attributes = $link['@attributes'];
273 } elseif ($value == '@attributes') {
279 if (!empty($attributes['rel']) && $attributes['rel'] == 'lrdd' && !empty($attributes['template'])) {
280 $type = (empty($attributes['type']) ? '' : $attributes['type']);
282 $lrdd[$type] = $attributes['template'];
286 if (Network::isUrlBlocked($host_url)) {
287 Logger::info('Domain is blocked', ['url' => $host]);
291 self::$baseurl = $host_url;
293 Logger::info('Probing successful', ['host' => $host]);
299 * Check an URI for LRDD data
301 * @param string $uri Address that should be probed
302 * @return array uri data
303 * @throws HTTPException\InternalServerErrorException
305 public static function lrdd(string $uri): array
307 $data = self::getWebfingerArray($uri);
311 $webfinger = $data['webfinger'];
313 if (empty($webfinger['links'])) {
314 Logger::info('No webfinger links found', ['uri' => $uri]);
320 foreach ($webfinger['links'] as $link) {
321 $data[] = ['@attributes' => $link];
324 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
325 foreach ($webfinger['aliases'] as $alias) {
339 * Fetch information (protocol endpoints and user information) about a given uri
341 * @param string $uri Address that should be probed
342 * @param string $network Test for this specific network
343 * @param integer $uid User ID for the probe (only used for mails)
345 * @return array uri data
346 * @throws HTTPException\InternalServerErrorException
347 * @throws \ImagickException
349 public static function uri(string $uri, string $network = '', int $uid = -1): array
351 // Local profiles aren't probed via network
352 if (empty($network) && Contact::isLocal($uri)) {
353 $data = self::localProbe($uri);
360 $uid = DI::userSession()->getLocalUserId();
363 if (empty($network) || ($network == Protocol::ACTIVITYPUB)) {
364 $ap_profile = ActivityPub::probeProfile($uri);
369 self::$isTimeout = false;
371 if ($network != Protocol::ACTIVITYPUB) {
372 $data = self::detect($uri, $network, $uid, $ap_profile);
373 if (!is_array($data)) {
376 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
377 $networks = $data['networks'] ?? [];
378 unset($data['networks']);
379 if (!empty($data['network'])) {
380 $networks[$data['network']] = $data;
383 $data['networks'] = $networks;
384 } elseif (!empty($ap_profile)) {
385 $ap_profile['batch'] = '';
386 $data = array_merge($ap_profile, $data);
392 if (!isset($data['url'])) {
396 if (empty($data['photo'])) {
397 $data['photo'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
400 if (empty($data['name'])) {
401 if (!empty($data['nick'])) {
402 $data['name'] = $data['nick'];
405 if (empty($data['name'])) {
406 $data['name'] = $data['url'];
410 if (empty($data['nick'])) {
411 $data['nick'] = strtolower($data['name']);
413 if (strpos($data['nick'], ' ')) {
414 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
418 if (!empty($data['baseurl']) && empty($data['gsid'])) {
419 $data['gsid'] = GServer::getID($data['baseurl']);
422 if (empty($data['network'])) {
423 $data['network'] = Protocol::PHANTOM;
426 // Ensure that local connections always are DFRN
427 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
428 $data['network'] = Protocol::DFRN;
431 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
432 $data['hide'] = self::getHideStatus($data['url']);
435 return self::rearrangeData($data);
440 * Fetches the "hide" status from the profile
442 * @param string $url URL of the profile
443 * @return boolean "hide" status
445 private static function getHideStatus(string $url): bool
447 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::CONTENT_LENGTH => 1000000]);
448 if (!$curlResult->isSuccess()) {
452 // If it isn't a HTML file then exit
453 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
457 $body = $curlResult->getBody();
462 $doc = new DOMDocument();
463 @$doc->loadHTML($body);
465 $xpath = new DOMXPath($doc);
467 $list = $xpath->query('//meta[@name]');
468 foreach ($list as $node) {
470 if ($node->attributes->length) {
471 foreach ($node->attributes as $attribute) {
472 $meta_tag[$attribute->name] = $attribute->value;
476 if (empty($meta_tag['content'])) {
480 $content = strtolower(trim($meta_tag['content']));
482 switch (strtolower(trim($meta_tag['name']))) {
483 case 'dfrn-global-visibility':
484 if ($content == 'false') {
489 if (strpos($content, 'noindex') !== false) {
500 * Fetch the "subscribe" and add it to the result
502 * @param array $result Result array
503 * @param array $webfinger Webfinger data
505 * @return array result Altered/unaltered result array
507 private static function getSubscribeLink(array $result, array $webfinger): array
509 if (empty($webfinger['links'])) {
513 foreach ($webfinger['links'] as $link) {
514 if (!empty($link['template']) && ($link['rel'] === ActivityNamespace::OSTATUSSUB)) {
515 $result['subscribe'] = $link['template'];
523 * Get webfinger data from a given URI
525 * @param string $uri URI
527 * @return array Webfinger data
528 * @throws HTTPException\InternalServerErrorException
530 public static function getWebfingerArray(string $uri): array
532 $parts = parse_url($uri);
534 if (!empty($parts['scheme']) && !empty($parts['host'])) {
535 $host = $parts['host'];
536 if (!empty($parts['port'])) {
537 $host .= ':' . $parts['port'];
540 $baseurl = $parts['scheme'] . '://' . $host;
545 $path_parts = explode('/', trim($parts['path'] ?? '', '/'));
546 if (!empty($path_parts)) {
547 $nick = ltrim(end($path_parts), '@');
548 $addr = $nick . '@' . $host;
551 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
552 if (empty($webfinger)) {
553 $lrdd = self::hostMeta($host);
556 if (empty($webfinger) && empty($lrdd)) {
557 while (empty($lrdd) && empty($webfinger) && (sizeof($path_parts) > 1)) {
558 $host .= '/' . array_shift($path_parts);
559 $baseurl = $parts['scheme'] . '://' . $host;
562 $addr = $nick . '@' . $host;
565 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
566 if (empty($webfinger)) {
567 $lrdd = self::hostMeta($host);
571 if (empty($lrdd) && empty($webfinger)) {
575 } elseif (strstr($uri, '@')) {
576 // Remove "acct:" from the URI
577 $uri = str_replace('acct:', '', $uri);
579 $host = substr($uri, strpos($uri, '@') + 1);
580 $nick = substr($uri, 0, strpos($uri, '@'));
583 $webfinger = self::getWebfinger('https://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
584 if (self::$isTimeout) {
588 if (empty($webfinger)) {
589 $webfinger = self::getWebfinger('http://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
590 if (self::$isTimeout) {
594 $baseurl = 'https://' . $host;
597 if (empty($webfinger)) {
598 $lrdd = self::hostMeta($host);
599 if (self::$isTimeout) {
602 $baseurl = self::$baseurl;
604 $baseurl = 'http://' . $host;
607 Logger::info('URI was not detectable', ['uri' => $uri]);
611 if (empty($webfinger)) {
612 foreach ($lrdd as $type => $template) {
617 $webfinger = self::getWebfinger($template, $type, $uri, $addr);
621 if (empty($webfinger)) {
625 if ($webfinger['detected'] == $addr) {
626 $webfinger['nick'] = $nick;
627 $webfinger['addr'] = $addr;
630 $webfinger['baseurl'] = $baseurl;
636 * Perform network request for webfinger data
638 * @param string $template
639 * @param string $type
641 * @param string $addr
643 * @return array webfinger results
645 private static function getWebfinger(string $template, string $type, string $uri, string $addr): array
647 if (Network::isUrlBlocked($template)) {
648 Logger::info('Domain is blocked', ['url' => $template]);
652 // First try the address because this is the primary purpose of webfinger
655 $path = str_replace('{uri}', urlencode('acct:' . $addr), $template);
656 $webfinger = self::webfinger($path, $type);
657 if (self::$isTimeout) {
663 if (empty($webfinger) && $uri != $addr) {
665 $path = str_replace('{uri}', urlencode($uri), $template);
666 $webfinger = self::webfinger($path, $type);
667 if (self::$isTimeout) {
672 if (empty($webfinger)) {
676 return ['webfinger' => $webfinger, 'detected' => $detected];
680 * Fetch information (protocol endpoints and user information) about a given uri
682 * This function is only called by the "uri" function that adds caching and rearranging of data.
684 * @param string $uri Address that should be probed
685 * @param string $network Test for this specific network
686 * @param integer $uid User ID for the probe (only used for mails)
687 * @param array $ap_profile Previously probed AP profile
688 * @return array URI data
689 * @throws HTTPException\InternalServerErrorException
691 private static function detect(string $uri, string $network, int $uid, array $ap_profile): array
695 'network' => $network,
700 Hook::callAll('probe_detect', $hookData);
702 if (isset($hookData['result'])) {
703 return is_array($hookData['result']) ? $hookData['result'] : [];
706 $parts = parse_url($uri);
707 if (empty($parts['scheme']) && empty($parts['host']) && (empty($parts['path']) || strpos($parts['path'], '@') === false)) {
708 Logger::info('URI was not detectable', ['uri' => $uri]);
712 // If the URI starts with "mailto:" then jump directly to the mail detection
713 if (strpos($uri, 'mailto:') !== false) {
714 $uri = str_replace('mailto:', '', $uri);
715 return self::mail($uri, $uid);
718 if ($network == Protocol::MAIL) {
719 return self::mail($uri, $uid);
722 Logger::info('Probing start', ['uri' => $uri]);
724 if (!empty($ap_profile['addr']) && ($ap_profile['addr'] != $uri)) {
725 $data = self::getWebfingerArray($ap_profile['addr']);
729 $data = self::getWebfingerArray($uri);
733 if (!empty($parts['scheme'])) {
734 return self::feed($uri);
735 } elseif (!empty($uid)) {
736 return self::mail($uri, $uid);
742 $webfinger = $data['webfinger'];
743 $nick = $data['nick'] ?? '';
744 $addr = $data['addr'] ?? '';
745 $baseurl = $data['baseurl'] ?? '';
749 if (in_array($network, ['', Protocol::DFRN])) {
750 $result = self::dfrn($webfinger);
752 if ((!$result && ($network == '')) || ($network == Protocol::DIASPORA)) {
753 $result = self::diaspora($webfinger);
755 $result['networks'][Protocol::DIASPORA] = self::diaspora($webfinger);
757 if ((!$result && ($network == '')) || ($network == Protocol::OSTATUS)) {
758 $result = self::ostatus($webfinger);
760 $result['networks'][Protocol::OSTATUS] = self::ostatus($webfinger);
762 if (in_array($network, ['', Protocol::ZOT])) {
763 $result = self::zot($webfinger, $result, $baseurl);
765 if ((!$result && ($network == '')) || ($network == Protocol::PUMPIO)) {
766 $result = self::pumpio($webfinger, $addr, $baseurl);
768 if (empty($result['network']) && empty($ap_profile['network']) || ($network == Protocol::FEED)) {
769 $result = self::feed($uri);
771 // We overwrite the detected nick with our try if the previous routines hadn't detected it.
772 // Additionally, it is overwritten when the nickname doesn't make sense (contains spaces).
773 if ((empty($result['nick']) || (strstr($result['nick'], ' '))) && ($nick != '')) {
774 $result['nick'] = $nick;
777 if (empty($result['addr']) && ($addr != '')) {
778 $result['addr'] = $addr;
782 $result = self::getSubscribeLink($result, $webfinger);
784 if (empty($result['network'])) {
785 $result['network'] = Protocol::PHANTOM;
788 if (empty($result['baseurl']) && !empty($baseurl)) {
789 $result['baseurl'] = $baseurl;
792 if (empty($result['url'])) {
793 $result['url'] = $uri;
796 Logger::info('Probing done', ['uri' => $uri, 'network' => $result['network']]);
802 * Check for Zot contact
804 * @param array $webfinger Webfinger data
805 * @param array $data previously probed data
806 * @param string $baseUrl Base URL
808 * @return array Zot data
809 * @throws HTTPException\InternalServerErrorException
811 private static function zot(array $webfinger, array $data, string $baseurl): array
813 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
814 foreach ($webfinger['aliases'] as $alias) {
815 if (substr($alias, 0, 5) == 'acct:') {
816 $data['addr'] = substr($alias, 5);
821 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
822 $data['addr'] = substr($webfinger['subject'], 5);
826 foreach ($webfinger['links'] as $link) {
827 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
828 $zot_url = $link['href'];
832 if (empty($zot_url) && !empty($data['addr']) && !empty($baseurl)) {
833 $condition = ['nurl' => Strings::normaliseLink($baseurl), 'platform' => ['hubzilla']];
834 if (!DBA::exists('gserver', $condition)) {
837 $zot_url = $baseurl . '/.well-known/zot-info?address=' . $data['addr'];
840 if (empty($zot_url)) {
844 $data = self::pollZot($zot_url, $data);
846 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
847 foreach ($webfinger['aliases'] as $alias) {
848 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
849 $data['alias'] = $alias;
857 public static function pollZot(string $url, array $data): array
859 $curlResult = DI::httpClient()->get($url, HttpClientAccept::JSON);
860 if ($curlResult->isTimeout()) {
863 $content = $curlResult->getBody();
868 $json = json_decode($content, true);
869 if (!is_array($json)) {
873 if (empty($data['network'])) {
874 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
875 $data['network'] = Protocol::ZOT;
876 } elseif (!isset($json['protocols'])) {
877 $data['network'] = Protocol::ZOT;
881 if (!empty($json['guid']) && empty($data['guid'])) {
882 $data['guid'] = $json['guid'];
884 if (!empty($json['key']) && empty($data['pubkey'])) {
885 $data['pubkey'] = $json['key'];
887 if (!empty($json['name'])) {
888 $data['name'] = $json['name'];
890 if (!empty($json['photo'])) {
891 $data['photo'] = $json['photo'];
892 if (!empty($json['photo_updated'])) {
893 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
896 if (!empty($json['address'])) {
897 $data['addr'] = $json['address'];
899 if (!empty($json['url'])) {
900 $data['url'] = $json['url'];
902 if (!empty($json['connections_url'])) {
903 $data['poco'] = $json['connections_url'];
905 if (isset($json['searchable'])) {
906 $data['hide'] = !$json['searchable'];
908 if (!empty($json['public_forum'])) {
909 $data['community'] = $json['public_forum'];
910 $data['account-type'] = User::PAGE_FLAGS_COMMUNITY;
913 if (!empty($json['profile'])) {
914 $profile = $json['profile'];
915 if (!empty($profile['description'])) {
916 $data['about'] = $profile['description'];
918 if (!empty($profile['keywords'])) {
919 $keywords = implode(', ', $profile['keywords']);
920 if (!empty($keywords)) {
921 $data['keywords'] = $keywords;
926 if (!empty($profile['region'])) {
927 $loc['region'] = $profile['region'];
929 if (!empty($profile['country'])) {
930 $loc['country-name'] = $profile['country'];
932 $location = Profile::formatLocation($loc);
933 if (!empty($location)) {
934 $data['location'] = $location;
942 * Perform a webfinger request.
944 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
946 * @param string $url Address that should be probed
947 * @param string $type type
949 * @return array webfinger data
950 * @throws HTTPException\InternalServerErrorException
952 public static function webfinger(string $url, string $type): array
955 $curlResult = DI::httpClient()->get(
958 [HttpClientOptions::TIMEOUT => DI::config()->get('system', 'xrd_timeout', 20)]
960 } catch (\Throwable $e) {
961 Logger::notice($e->getMessage(), ['url' => $url, 'type' => $type, 'class' => get_class($e)]);
965 if ($curlResult->isTimeout()) {
966 self::$isTimeout = true;
969 $data = $curlResult->getBody();
971 $webfinger = json_decode($data, true);
972 if (!empty($webfinger)) {
973 if (!isset($webfinger['links'])) {
974 Logger::info('No json webfinger links', ['url' => $url]);
980 // If it is not JSON, maybe it is XML
981 $xrd = XML::parseString($data, true);
982 if (!is_object($xrd)) {
983 Logger::info('No webfinger data retrievable', ['url' => $url]);
987 $xrd_arr = XML::elementToArray($xrd);
988 if (!isset($xrd_arr['xrd']['link'])) {
989 Logger::info('No XML webfinger links', ['url' => $url]);
995 if (!empty($xrd_arr['xrd']['subject'])) {
996 $webfinger['subject'] = $xrd_arr['xrd']['subject'];
999 if (!empty($xrd_arr['xrd']['alias'])) {
1000 $webfinger['aliases'] = $xrd_arr['xrd']['alias'];
1003 $webfinger['links'] = [];
1005 foreach ($xrd_arr['xrd']['link'] as $value => $data) {
1006 if (!empty($data['@attributes'])) {
1007 $attributes = $data['@attributes'];
1008 } elseif ($value == '@attributes') {
1009 $attributes = $data;
1014 $webfinger['links'][] = $attributes;
1020 * Poll the Friendica specific noscrape page.
1022 * "noscrape" is a faster alternative to fetch the data from the hcard.
1023 * This functionality was originally created for the directory.
1025 * @param string $noscrape_url Link to the noscrape page
1026 * @param array $data The already fetched data
1028 * @return array noscrape data
1029 * @throws HTTPException\InternalServerErrorException
1031 private static function pollNoscrape(string $noscrape_url, array $data): array
1033 $curlResult = DI::httpClient()->get($noscrape_url, HttpClientAccept::JSON);
1034 if ($curlResult->isTimeout()) {
1035 self::$isTimeout = true;
1038 $content = $curlResult->getBody();
1040 Logger::info('Empty body', ['url' => $noscrape_url]);
1044 $json = json_decode($content, true);
1045 if (!is_array($json)) {
1046 Logger::info('No json data', ['url' => $noscrape_url]);
1050 if (!empty($json['fn'])) {
1051 $data['name'] = $json['fn'];
1054 if (!empty($json['addr'])) {
1055 $data['addr'] = $json['addr'];
1058 if (!empty($json['nick'])) {
1059 $data['nick'] = $json['nick'];
1062 if (!empty($json['guid'])) {
1063 $data['guid'] = $json['guid'];
1066 if (!empty($json['comm'])) {
1067 $data['community'] = $json['comm'];
1070 if (!empty($json['tags'])) {
1071 $keywords = implode(', ', $json['tags']);
1072 if ($keywords != '') {
1073 $data['keywords'] = $keywords;
1077 $location = Profile::formatLocation($json);
1079 $data['location'] = $location;
1082 if (!empty($json['about'])) {
1083 $data['about'] = $json['about'];
1086 if (!empty($json['xmpp'])) {
1087 $data['xmpp'] = $json['xmpp'];
1090 if (!empty($json['matrix'])) {
1091 $data['matrix'] = $json['matrix'];
1094 if (!empty($json['key'])) {
1095 $data['pubkey'] = $json['key'];
1098 if (!empty($json['photo'])) {
1099 $data['photo'] = $json['photo'];
1102 if (!empty($json['dfrn-request'])) {
1103 $data['request'] = $json['dfrn-request'];
1106 if (!empty($json['dfrn-confirm'])) {
1107 $data['confirm'] = $json['dfrn-confirm'];
1110 if (!empty($json['dfrn-notify'])) {
1111 $data['notify'] = $json['dfrn-notify'];
1114 if (!empty($json['dfrn-poll'])) {
1115 $data['poll'] = $json['dfrn-poll'];
1118 if (isset($json['hide'])) {
1119 $data['hide'] = (bool)$json['hide'];
1121 $data['hide'] = false;
1128 * Check for valid DFRN data
1130 * @param array $data DFRN data
1132 * @return int Number of errors
1134 public static function validDfrn(array $data): int
1137 if (!isset($data['key'])) {
1140 if (!isset($data['dfrn-request'])) {
1143 if (!isset($data['dfrn-confirm'])) {
1146 if (!isset($data['dfrn-notify'])) {
1149 if (!isset($data['dfrn-poll'])) {
1156 * Fetch data from a DFRN profile page and via "noscrape"
1158 * @param string $profile_link Link to the profile page
1159 * @return array profile data
1160 * @throws HTTPException\InternalServerErrorException
1161 * @throws \ImagickException
1163 public static function profile(string $profile_link): array
1167 Logger::info('Check profile', ['link' => $profile_link]);
1169 // Fetch data via noscrape - this is faster
1170 $noscrape_url = str_replace(['/hcard/', '/profile/'], '/noscrape/', $profile_link);
1171 $data = self::pollNoscrape($noscrape_url, $data);
1173 if (!isset($data['notify'])
1174 || !isset($data['confirm'])
1175 || !isset($data['request'])
1176 || !isset($data['poll'])
1177 || !isset($data['name'])
1178 || !isset($data['photo'])
1180 $data = self::pollHcard($profile_link, $data, true);
1185 if (empty($data['addr']) || empty($data['nick'])) {
1186 $probe_data = self::uri($profile_link);
1187 $data['addr'] = ($data['addr'] ?? '') ?: $probe_data['addr'];
1188 $data['nick'] = ($data['nick'] ?? '') ?: $probe_data['nick'];
1191 $prof_data['addr'] = $data['addr'];
1192 $prof_data['nick'] = $data['nick'];
1193 $prof_data['dfrn-request'] = $data['request'] ?? null;
1194 $prof_data['dfrn-confirm'] = $data['confirm'] ?? null;
1195 $prof_data['dfrn-notify'] = $data['notify'] ?? null;
1196 $prof_data['dfrn-poll'] = $data['poll'] ?? null;
1197 $prof_data['photo'] = $data['photo'] ?? null;
1198 $prof_data['fn'] = $data['name'] ?? null;
1199 $prof_data['key'] = $data['pubkey'] ?? null;
1201 Logger::debug('Result', ['link' => $profile_link, 'data' => $prof_data]);
1207 * Check for DFRN contact
1209 * @param array $webfinger Webfinger data
1210 * @return array DFRN data
1211 * @throws HTTPException\InternalServerErrorException
1213 private static function dfrn(array $webfinger): array
1217 // The array is reversed to take into account the order of preference for same-rel links
1218 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1219 foreach (array_reverse($webfinger['links']) as $link) {
1220 if (($link['rel'] == ActivityNamespace::DFRN) && !empty($link['href'])) {
1221 $data['network'] = Protocol::DFRN;
1222 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1223 $data['poll'] = $link['href'];
1224 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1225 $data['url'] = $link['href'];
1226 } elseif (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1227 $hcard_url = $link['href'];
1228 } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1229 $data['poco'] = $link['href'];
1230 } elseif (($link['rel'] == 'http://webfinger.net/rel/avatar') && !empty($link['href'])) {
1231 $data['photo'] = $link['href'];
1232 } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1233 $data['baseurl'] = trim($link['href'], '/');
1234 } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1235 $data['guid'] = $link['href'];
1236 } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1237 $data['pubkey'] = base64_decode($link['href']);
1239 if (strstr($data['pubkey'], 'RSA ')) {
1240 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1245 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1246 foreach ($webfinger['aliases'] as $alias) {
1247 if (empty($data['url']) && !strstr($alias, '@')) {
1248 $data['url'] = $alias;
1249 } elseif (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
1250 $data['alias'] = $alias;
1251 } elseif (substr($alias, 0, 5) == 'acct:') {
1252 $data['addr'] = substr($alias, 5);
1257 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1258 $data['addr'] = substr($webfinger['subject'], 5);
1261 if (!isset($data['network']) || ($hcard_url == '')) {
1265 // Fetch data via noscrape - this is faster
1266 $noscrape_url = str_replace('/hcard/', '/noscrape/', $hcard_url);
1267 $data = self::pollNoscrape($noscrape_url, $data);
1269 if (isset($data['notify'])
1270 && isset($data['confirm'])
1271 && isset($data['request'])
1272 && isset($data['poll'])
1273 && isset($data['name'])
1274 && isset($data['photo'])
1279 $data = self::pollHcard($hcard_url, $data, true);
1285 * Poll the hcard page (Diaspora and Friendica specific)
1287 * @param string $hcard_url Link to the hcard page
1288 * @param array $data The already fetched data
1289 * @param boolean $dfrn Poll DFRN specific data
1290 * @return array hcard data
1291 * @throws HTTPException\InternalServerErrorException
1293 private static function pollHcard(string $hcard_url, array $data, bool $dfrn = false): array
1295 $curlResult = DI::httpClient()->get($hcard_url, HttpClientAccept::HTML);
1296 if ($curlResult->isTimeout()) {
1297 self::$isTimeout = true;
1300 $content = $curlResult->getBody();
1301 if (empty($content)) {
1305 $doc = new DOMDocument();
1306 if (!@$doc->loadHTML($content)) {
1310 $xpath = new DomXPath($doc);
1312 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1313 if (!is_object($vcards)) {
1317 if (!isset($data['baseurl'])) {
1318 $data['baseurl'] = '';
1321 if ($vcards->length > 0) {
1322 $vcard = $vcards->item(0);
1324 // We have to discard the guid from the hcard in favour of the guid from lrdd
1325 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1326 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1327 if (($search->length > 0) && empty($data['guid'])) {
1328 $data['guid'] = $search->item(0)->nodeValue;
1331 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1332 if ($search->length > 0) {
1333 $data['nick'] = $search->item(0)->nodeValue;
1336 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1337 if ($search->length > 0) {
1338 $data['name'] = $search->item(0)->nodeValue;
1341 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' given_name ')]", $vcard); // */
1342 if ($search->length > 0) {
1343 $data["given_name"] = $search->item(0)->nodeValue;
1346 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' family_name ')]", $vcard); // */
1347 if ($search->length > 0) {
1348 $data["family_name"] = $search->item(0)->nodeValue;
1351 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1352 if ($search->length > 0) {
1353 $data['hide'] = (strtolower($search->item(0)->nodeValue) != 'true');
1356 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1357 if ($search->length > 0) {
1358 $data['pubkey'] = $search->item(0)->nodeValue;
1359 if (strstr($data['pubkey'], 'RSA ')) {
1360 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1364 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1365 if ($search->length > 0) {
1366 $data['baseurl'] = trim($search->item(0)->nodeValue, '/');
1371 if (!empty($vcard)) {
1372 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1373 foreach ($photos as $photo) {
1375 foreach ($photo->attributes as $attribute) {
1376 $attr[$attribute->name] = trim($attribute->value);
1379 if (isset($attr['src']) && isset($attr['width'])) {
1380 $avatars[$attr['width']] = self::fixAvatar($attr['src'], $data['baseurl']);
1383 // We don't have a width. So we just take everything that we got.
1384 // This is a Hubzilla workaround which doesn't send a width.
1385 if (!$avatars && !empty($attr['src'])) {
1386 $avatars[] = self::fixAvatar($attr['src'], $data['baseurl']);
1393 $data['photo'] = array_pop($avatars);
1395 $data['photo_medium'] = array_pop($avatars);
1399 $data['photo_small'] = array_pop($avatars);
1404 // Poll DFRN specific data
1405 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1406 if ($search->length > 0) {
1407 foreach ($search as $link) {
1408 //$data['request'] = $search->item(0)->nodeValue;
1410 foreach ($link->attributes as $attribute) {
1411 $attr[$attribute->name] = trim($attribute->value);
1414 $data[substr($attr['rel'], 5)] = $attr['href'];
1418 // Older Friendica versions had used the "uid" field differently than newer versions
1419 if (!empty($data['nick']) && !empty($data['guid']) && ($data['nick'] == $data['guid'])) {
1420 unset($data['guid']);
1428 * Check for Diaspora contact
1430 * @param array $webfinger Webfinger data
1432 * @return array Diaspora data
1433 * @throws HTTPException\InternalServerErrorException
1435 private static function diaspora(array $webfinger): array
1440 // The array is reversed to take into account the order of preference for same-rel links
1441 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1442 foreach (array_reverse($webfinger['links']) as $link) {
1443 if (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1444 $hcard_url = $link['href'];
1445 } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1446 $data['baseurl'] = trim($link['href'], '/');
1447 } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1448 $data['guid'] = $link['href'];
1449 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1450 $data['url'] = $link['href'];
1451 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && empty($link['type']) && !empty($link['href'])) {
1452 $profile_url = $link['href'];
1453 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1454 $data['poll'] = $link['href'];
1455 } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1456 $data['poco'] = $link['href'];
1457 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1458 $data['notify'] = $link['href'];
1459 } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1460 $data['pubkey'] = base64_decode($link['href']);
1462 if (strstr($data['pubkey'], 'RSA ')) {
1463 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1468 if (empty($data['url']) && !empty($profile_url)) {
1469 $data['url'] = $profile_url;
1472 if (empty($data['url']) || empty($hcard_url)) {
1476 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1477 foreach ($webfinger['aliases'] as $alias) {
1478 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data['url']) && ! strstr($alias, '@')) {
1479 $data['alias'] = $alias;
1480 } elseif (substr($alias, 0, 5) == 'acct:') {
1481 $data['addr'] = substr($alias, 5);
1486 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1487 $data['addr'] = substr($webfinger['subject'], 5);
1490 // Fetch further information from the hcard
1491 $data = self::pollHcard($hcard_url, $data);
1497 if (!empty($data['url'])
1498 && !empty($data['guid'])
1499 && !empty($data['baseurl'])
1500 && !empty($data['pubkey'])
1501 && !empty($hcard_url)
1503 $data['network'] = Protocol::DIASPORA;
1504 $data['manually-approve'] = false;
1506 // The Diaspora handle must always be lowercase
1507 if (!empty($data['addr'])) {
1508 $data['addr'] = strtolower($data['addr']);
1511 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1512 $data['notify'] = $data['baseurl'] . '/receive/users/' . $data['guid'];
1513 $data['batch'] = $data['baseurl'] . '/receive/public';
1522 * Check for OStatus contact
1524 * @param array $webfinger Webfinger data
1525 * @param bool $short Short detection mode
1527 * @return array|bool OStatus data or "false" on error or "true" on short mode
1528 * @throws HTTPException\InternalServerErrorException
1530 private static function ostatus(array $webfinger, bool $short = false)
1534 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1535 foreach ($webfinger['aliases'] as $alias) {
1536 if (strstr($alias, '@') && !strstr(Strings::normaliseLink($alias), 'http://')) {
1537 $data['addr'] = str_replace('acct:', '', $alias);
1542 if (!empty($webfinger['subject']) && strstr($webfinger['subject'], '@')
1543 && !strstr(Strings::normaliseLink($webfinger['subject']), 'http://')
1545 $data['addr'] = str_replace('acct:', '', $webfinger['subject']);
1548 if (!empty($webfinger['links'])) {
1549 // The array is reversed to take into account the order of preference for same-rel links
1550 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1551 foreach (array_reverse($webfinger['links']) as $link) {
1552 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1553 && (($link['type'] ?? '') == 'text/html')
1554 && ($link['href'] != '')
1556 $data['url'] = $data['alias'] = $link['href'];
1557 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1558 $data['notify'] = $link['href'];
1559 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1560 $data['poll'] = $link['href'];
1561 } elseif (($link['rel'] == 'magic-public-key') && !empty($link['href'])) {
1562 $pubkey = $link['href'];
1564 if (substr($pubkey, 0, 5) === 'data:') {
1565 if (strstr($pubkey, ',')) {
1566 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1568 $pubkey = substr($pubkey, 5);
1570 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1571 $curlResult = DI::httpClient()->get($pubkey, HttpClientAccept::MAGIC_KEY);
1572 if ($curlResult->isTimeout()) {
1573 self::$isTimeout = true;
1574 return $short ? false : [];
1576 Logger::debug('Fetched public key', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $pubkey]);
1577 $pubkey = $curlResult->getBody();
1581 $data['pubkey'] = Salmon::magicKeyToPem($pubkey);
1582 } catch (\Throwable $e) {
1589 if (isset($data['notify']) && isset($data['pubkey'])
1590 && isset($data['poll'])
1591 && isset($data['url'])
1593 $data['network'] = Protocol::OSTATUS;
1594 $data['manually-approve'] = false;
1596 return $short ? false : [];
1603 // Fetch all additional data from the feed
1604 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::FEED_XML);
1605 if ($curlResult->isTimeout()) {
1606 self::$isTimeout = true;
1609 $feed = $curlResult->getBody();
1610 $feed_data = Feed::import($feed);
1615 if (!empty($feed_data['header']['author-name'])) {
1616 $data['name'] = $feed_data['header']['author-name'];
1618 if (!empty($feed_data['header']['author-nick'])) {
1619 $data['nick'] = $feed_data['header']['author-nick'];
1621 if (!empty($feed_data['header']['author-avatar'])) {
1622 $data['photo'] = self::fixAvatar($feed_data['header']['author-avatar'], $data['url']);
1624 if (!empty($feed_data['header']['author-id'])) {
1625 $data['alias'] = $feed_data['header']['author-id'];
1627 if (!empty($feed_data['header']['author-location'])) {
1628 $data['location'] = $feed_data['header']['author-location'];
1630 if (!empty($feed_data['header']['author-about'])) {
1631 $data['about'] = $feed_data['header']['author-about'];
1633 // OStatus has serious issues when the url doesn't fit (ssl vs. non ssl)
1634 // So we take the value that we just fetched, although the other one worked as well
1635 if (!empty($feed_data['header']['author-link'])) {
1636 $data['url'] = $feed_data['header']['author-link'];
1639 if ($data['url'] == $data['alias']) {
1640 $data['alias'] = '';
1643 /// @todo Fetch location and "about" from the feed as well
1648 * Fetch data from a pump.io profile page
1650 * @param string $profile_link Link to the profile page
1652 * @return array Profile data
1654 private static function pumpioProfileData(string $profile_link, string $baseurl): array
1656 $curlResult = DI::httpClient()->get($profile_link, HttpClientAccept::HTML);
1657 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
1661 $doc = new DOMDocument();
1662 if (!@$doc->loadHTML($curlResult->getBody())) {
1666 $xpath = new DomXPath($doc);
1669 $data['name'] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1671 if ($data['name'] == '') {
1672 // This is ugly - but pump.io doesn't seem to know a better way for it
1673 $data['name'] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1674 $pos = strpos($data['name'], chr(10));
1676 $data['name'] = trim(substr($data['name'], 0, $pos));
1680 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1682 if ($data['location'] == '') {
1683 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1686 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1688 if ($data['about'] == '') {
1689 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1692 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1694 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1697 foreach ($avatar->attributes as $attribute) {
1698 if (($attribute->name == 'src') && !empty($attribute->value)) {
1699 $data['photo'] = Network::addBasePath($attribute->value, $baseurl);
1708 * Check for pump.io contact
1710 * @param array $webfinger Webfinger data
1711 * @param string $addr
1713 * @return array pump.io data
1715 private static function pumpio(array $webfinger, string $addr, string $baseurl): array
1718 // The array is reversed to take into account the order of preference for same-rel links
1719 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1720 foreach (array_reverse($webfinger['links']) as $link) {
1721 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1722 && (($link['type'] ?? '') == 'text/html')
1723 && ($link['href'] != '')
1725 $data['url'] = $link['href'];
1726 } elseif (($link['rel'] == 'activity-inbox') && ($link['href'] != '')) {
1727 $data['notify'] = $link['href'];
1728 } elseif (($link['rel'] == 'activity-outbox') && ($link['href'] != '')) {
1729 $data['poll'] = $link['href'];
1730 } elseif (($link['rel'] == 'dialback') && ($link['href'] != '')) {
1731 $data['dialback'] = $link['href'];
1734 if (isset($data['poll']) && isset($data['notify'])
1735 && isset($data['dialback'])
1736 && isset($data['url'])
1738 // by now we use these fields only for the network type detection
1739 // So we unset all data that isn't used at the moment
1740 unset($data['dialback']);
1742 $data['network'] = Protocol::PUMPIO;
1747 $profile_data = self::pumpioProfileData($data['url'], $baseurl);
1749 if (!$profile_data) {
1753 $data = array_merge($data, $profile_data);
1755 if (($addr != '') && ($data['name'] != '')) {
1756 $name = trim(str_replace($addr, '', $data['name']));
1758 $data['name'] = $name;
1766 * Checks HTML page for RSS feed link
1768 * @param string $url Page link
1769 * @param string $body Page body string
1771 * @return string|false Feed link or false if body was invalid HTML document
1773 public static function getFeedLink(string $url, string $body)
1779 $doc = new DOMDocument();
1780 if (!@$doc->loadHTML($body)) {
1784 $xpath = new DOMXPath($doc);
1786 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1787 $feedUrl = $feedUrl ?: $xpath->evaluate('string(/html/head/link[@type="application/atom+xml" and @rel="alternate"]/@href)');
1789 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1795 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1797 * Loosely based on RFC 1808
1799 * @see https://tools.ietf.org/html/rfc1808
1801 * @param string $href The potential relative href found in the HTML document
1802 * @param string $base The HTML document URL
1803 * @param DOMXPath $xpath The HTML document XPath
1805 * @return string Absolute URL
1807 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath): string
1809 if (filter_var($href, FILTER_VALIDATE_URL)) {
1813 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1815 $baseParts = parse_url($base);
1816 if (empty($baseParts['host'])) {
1820 // Naked domain case (scheme://basehost)
1821 $path = $baseParts['path'] ?? '/';
1823 // Remove the filename part of the path if it exists (/base/path/file)
1824 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1826 $hrefParts = parse_url($href);
1828 if (!empty($hrefParts['path'])) {
1829 // Root path case (/path) including relative scheme case (//host/path)
1830 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1831 $path = $hrefParts['path'];
1833 $path = $path . '/' . $hrefParts['path'];
1835 // Resolve arbitrary relative path
1836 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1837 $parts = array_filter(explode('/', $path), 'strlen');
1839 foreach ($parts as $part) {
1840 if ('.' == $part) continue;
1841 if ('..' == $part) {
1842 array_pop($absolutes);
1844 $absolutes[] = $part;
1848 $path = '/' . implode('/', $absolutes);
1852 // Relative scheme case (//host/path)
1853 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1854 $baseParts['path'] = $path;
1855 unset($baseParts['query']);
1856 unset($baseParts['fragment']);
1858 return Network::unparseURL($baseParts);
1862 * Check for feed contact
1864 * @param string $url Profile link
1865 * @param boolean $probe Do a probe if the page contains a feed link
1867 * @return array feed data
1868 * @throws HTTPException\InternalServerErrorException
1870 private static function feed(string $url, bool $probe = true): array
1873 $curlResult = DI::httpClient()->get($url, HttpClientAccept::FEED_XML);
1874 } catch(\Throwable $e) {
1875 DI::logger()->info('Error requesting feed URL', ['url' => $url, 'exception' => $e]);
1879 if ($curlResult->isTimeout()) {
1880 self::$isTimeout = true;
1884 $feed = $curlResult->getBody();
1885 $feed_data = Feed::import($feed);
1892 $feed_url = self::getFeedLink($url, $feed);
1898 return self::feed($feed_url, false);
1901 if (!empty($feed_data['header']['author-name'])) {
1902 $data['name'] = $feed_data['header']['author-name'];
1905 if (!empty($feed_data['header']['author-nick'])) {
1906 $data['nick'] = $feed_data['header']['author-nick'];
1909 if (!empty($feed_data['header']['author-avatar'])) {
1910 $data['photo'] = $feed_data['header']['author-avatar'];
1913 if (!empty($feed_data['header']['author-id'])) {
1914 $data['alias'] = $feed_data['header']['author-id'];
1917 $data['url'] = $url;
1918 $data['poll'] = $url;
1920 $data['network'] = Protocol::FEED;
1926 * Check for mail contact
1928 * @param string $uri Profile link
1929 * @param integer $uid User ID
1931 * @return array mail data
1932 * @throws \Exception
1934 private static function mail(string $uri, int $uid): array
1936 if (!Network::isEmailDomainValid($uri)) {
1944 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1946 $condition = ["`uid` = ? AND `server` != ''", $uid];
1947 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1948 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1950 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1954 $mailbox = Email::constructMailboxName($mailacct);
1956 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1957 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1962 $msgs = Email::poll($mbox, $uri);
1963 Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
1965 if (!count($msgs)) {
1969 $phost = substr($uri, strpos($uri, '@') + 1);
1973 'network' => Protocol::MAIL,
1974 'name' => substr($uri, 0, strpos($uri, '@')),
1975 'photo' => Network::lookupAvatarByEmail($uri),
1976 'url' => 'mailto:' . $uri,
1977 'notify' => 'smtp ' . Strings::getRandomHex(),
1978 'poll' => 'email ' . Strings::getRandomHex(),
1981 $data['nick'] = $data['name'];
1983 $x = Email::messageMeta($mbox, $msgs[0]);
1985 if (stristr($x[0]->from, $uri)) {
1986 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1987 } elseif (stristr($x[0]->to, $uri)) {
1988 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1992 foreach ($adr as $feadr) {
1993 if ((strcasecmp($feadr->mailbox, $data['name']) == 0)
1994 &&(strcasecmp($feadr->host, $phost) == 0)
1995 && (strlen($feadr->personal))
1997 $personal = imap_mime_header_decode($feadr->personal);
1999 foreach ($personal as $perspart) {
2000 if ($perspart->charset != 'default') {
2001 $data['name'] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
2003 $data['name'] .= $perspart->text;
2010 if (!empty($mbox)) {
2018 * Mix two paths together to possibly fix missing parts
2020 * @param string $avatar Path to the avatar
2021 * @param string $base Another path that is hopefully complete
2023 * @return string fixed avatar path
2024 * @throws \Exception
2026 public static function fixAvatar(string $avatar, string $base): string
2028 $base_parts = parse_url($base);
2030 // Remove all parts that could create a problem
2031 unset($base_parts['path']);
2032 unset($base_parts['query']);
2033 unset($base_parts['fragment']);
2035 $avatar_parts = parse_url($avatar);
2038 $parts = array_merge($base_parts, $avatar_parts);
2040 // And put them together again
2041 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
2042 $host = isset($parts['host']) ? $parts['host'] : '';
2043 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
2044 $path = isset($parts['path']) ? $parts['path'] : '';
2045 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
2046 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
2048 $fixed = $scheme.$host.$port.$path.$query.$fragment;
2050 Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
2056 * Fetch the last date that the contact had posted something (publically)
2058 * @param array $data probing result
2060 * @return string last activity
2062 public static function getLastUpdate(array $data): string
2064 $uid = User::getIdForURL($data['url']);
2066 $contact = Contact::selectFirst(['url', 'last-item'], ['self' => true, 'uid' => $uid]);
2067 if (!empty($contact['last-item'])) {
2068 return $contact['last-item'];
2072 if ($lastUpdate = self::updateFromNoScrape($data)) {
2076 if (!empty($data['outbox'])) {
2077 return self::updateFromOutbox($data['outbox'], $data);
2078 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
2079 return self::updateFromOutbox($data['poll'], $data);
2080 } elseif (!empty($data['poll'])) {
2081 return self::updateFromFeed($data);
2088 * Fetch the last activity date from the "noscrape" endpoint
2090 * @param array $data Probing result
2092 * @return string last activity or true if update was successful or the server was unreachable
2094 private static function updateFromNoScrape(array $data): string
2096 if (empty($data['baseurl'])) {
2100 // Check the 'noscrape' endpoint when it is a Friendica server
2101 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
2102 Strings::normaliseLink($data['baseurl'])]);
2103 if (!DBA::isResult($gserver)) {
2107 $curlResult = DI::httpClient()->get($gserver['noscrape'] . '/' . $data['nick'], HttpClientAccept::JSON);
2109 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
2110 $noscrape = json_decode($curlResult->getBody(), true);
2111 if (!empty($noscrape) && !empty($noscrape['updated'])) {
2112 return DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2120 * Fetch the last activity date from an ActivityPub Outbox
2122 * @param string $feed
2123 * @param array $data Probing result
2125 * @return string last activity
2126 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2128 private static function updateFromOutbox(string $feed, array $data): string
2130 $outbox = ActivityPub::fetchContent($feed);
2131 if (empty($outbox)) {
2135 if (!empty($outbox['orderedItems'])) {
2136 $items = $outbox['orderedItems'];
2137 } elseif (!empty($outbox['first']['orderedItems'])) {
2138 $items = $outbox['first']['orderedItems'];
2139 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2140 return self::updateFromOutbox($outbox['first']['href'], $data);
2141 } elseif (!empty($outbox['first'])) {
2142 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2143 return self::updateFromOutbox($outbox['first'], $data);
2145 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2153 foreach ($items as $activity) {
2154 if (!empty($activity['published'])) {
2155 $published = DateTimeFormat::utc($activity['published']);
2156 } elseif (!empty($activity['object']['published'])) {
2157 $published = DateTimeFormat::utc($activity['object']['published']);
2162 if ($last_updated < $published) {
2163 $last_updated = $published;
2167 if (!empty($last_updated)) {
2168 return $last_updated;
2175 * Fetch the last activity date from an XML feed
2177 * @param array $data Probing result
2178 * @return string last activity
2180 private static function updateFromFeed(array $data): string
2182 // Search for the newest entry in the feed
2183 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::ATOM_XML);
2184 if (!$curlResult->isSuccess() || !$curlResult->getBody()) {
2188 $doc = new DOMDocument();
2189 @$doc->loadXML($curlResult->getBody());
2191 $xpath = new DOMXPath($doc);
2192 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2194 $entries = $xpath->query('/atom:feed/atom:entry');
2198 foreach ($entries as $entry) {
2199 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2200 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
2201 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2202 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2204 if (empty($published) || empty($updated)) {
2205 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2209 if ($last_updated < $published) {
2210 $last_updated = $published;
2213 if ($last_updated < $updated) {
2214 $last_updated = $updated;
2218 if (!empty($last_updated)) {
2219 return $last_updated;
2226 * Probe data from local profiles without network traffic
2228 * @param string $url
2230 * @return array probed data
2231 * @throws HTTPException\InternalServerErrorException
2232 * @throws HTTPException\NotFoundException
2234 private static function localProbe(string $url): array
2237 $uid = User::getIdForURL($url);
2239 throw new HTTPException\NotFoundException('User not found.');
2242 $owner = User::getOwnerDataById($uid);
2243 $approfile = ActivityPub\Transmitter::getProfile($uid);
2245 $split_name = Diaspora::splitName($owner['name']);
2247 if (empty($owner['gsid'])) {
2248 $owner['gsid'] = GServer::getID($approfile['generator']['url']);
2252 'name' => $owner['name'], 'nick' => $owner['nick'], 'guid' => $approfile['diaspora:guid'] ?? '',
2253 'url' => $owner['url'], 'addr' => $owner['addr'], 'alias' => $owner['alias'],
2254 'photo' => User::getAvatarUrl($owner),
2255 'header' => $owner['header'] ? Contact::getHeaderUrlForId($owner['id'], $owner['updated']) : '',
2256 'account-type' => $owner['contact-type'], 'community' => ($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY),
2257 'keywords' => $owner['keywords'], 'location' => $owner['location'], 'about' => $owner['about'],
2258 'xmpp' => $owner['xmpp'], 'matrix' => $owner['matrix'],
2259 'hide' => !$owner['net-publish'], 'batch' => '', 'notify' => $owner['notify'],
2260 'poll' => $owner['poll'], 'request' => $owner['request'], 'confirm' => $owner['confirm'],
2261 'subscribe' => $approfile['generator']['url'] . '/contact/follow?url={uri}', 'poco' => $owner['poco'],
2262 'following' => $approfile['following'], 'followers' => $approfile['followers'],
2263 'inbox' => $approfile['inbox'], 'outbox' => $approfile['outbox'],
2264 'sharedinbox' => $approfile['endpoints']['sharedInbox'], 'network' => Protocol::DFRN,
2265 'pubkey' => $owner['upubkey'], 'baseurl' => $approfile['generator']['url'], 'gsid' => $owner['gsid'],
2266 'manually-approve' => in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]),
2268 Protocol::DIASPORA => [
2269 'name' => $owner['name'],
2270 'given_name' => $split_name['first'],
2271 'family_name' => $split_name['last'],
2272 'nick' => $owner['nick'],
2273 'guid' => $approfile['diaspora:guid'],
2274 'url' => $owner['url'],
2275 'addr' => $owner['addr'],
2276 'alias' => $owner['alias'],
2277 'photo' => $owner['photo'],
2278 'photo_medium' => $owner['thumb'],
2279 'photo_small' => $owner['micro'],
2280 'batch' => $approfile['generator']['url'] . '/receive/public',
2281 'notify' => $owner['notify'],
2282 'poll' => $owner['poll'],
2283 'poco' => $owner['poco'],
2284 'network' => Protocol::DIASPORA,
2285 'pubkey' => $owner['upubkey'],
2289 } catch (Exception $e) {
2290 // Default values for nonexistent targets
2292 'name' => $url, 'nick' => $url, 'url' => $url, 'network' => Protocol::PHANTOM,
2293 'photo' => DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO
2297 return self::rearrangeData($data);