3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Network;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
33 use Friendica\Model\Contact;
34 use Friendica\Model\GServer;
35 use Friendica\Model\Profile;
36 use Friendica\Model\User;
37 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
38 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
39 use Friendica\Protocol\ActivityNamespace;
40 use Friendica\Protocol\ActivityPub;
41 use Friendica\Protocol\Email;
42 use Friendica\Protocol\Feed;
43 use Friendica\Util\Crypto;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\Network;
46 use Friendica\Util\Strings;
47 use Friendica\Util\XML;
48 use GuzzleHttp\Psr7\Uri;
51 * This class contain functions for probing URL
55 const HOST_META = '/.well-known/host-meta';
56 const WEBFINGER = '/.well-known/webfinger?resource={uri}';
59 * @var string Base URL
61 private static $baseurl;
64 * @var boolean Whether a timeout has occured
66 private static $isTimeout;
69 * Checks if the provided network can be probed
71 * @param string $network
75 public static function isProbable(string $network): bool
77 return (in_array($network, array_merge(Protocol::FEDERATED, [Protocol::ZOT, Protocol::PHANTOM])));
81 * Remove stuff from an URI that doesn't belong there
83 * @param string $rawUri
84 * @return string Cleaned URI
86 public static function cleanURI(string $rawUri): string
88 // At first remove leading and trailing junk
89 $rawUri = trim($rawUri, "@#?: \t\n\r\0\x0B");
91 $rawUri = Network::convertToIdn($rawUri);
93 $uri = new Uri($rawUri);
94 if (!$uri->getScheme()) {
95 return $uri->__toString();
98 // Remove the URL fragment, since these shouldn't be part of any profile URL
99 $uri = $uri->withFragment('');
101 return $uri->__toString();
105 * Rearrange the array so that it always has the same order
107 * @param array $data Unordered data
108 * @return array Ordered data
110 private static function rearrangeData(array $data): array
112 $fields = ['name', 'nick', 'guid', 'url', 'addr', 'alias', 'photo', 'header',
113 'account-type', 'community', 'keywords', 'location', 'about', 'xmpp', 'matrix',
114 'hide', 'batch', 'notify', 'poll', 'request', 'confirm', 'subscribe', 'poco',
115 'following', 'followers', 'inbox', 'outbox', 'sharedinbox',
116 'priority', 'network', 'pubkey', 'manually-approve', 'baseurl', 'gsid'];
118 $numeric_fields = ['gsid', 'hide', 'account-type', 'manually-approve'];
121 foreach ($fields as $field) {
122 if (isset($data[$field])) {
123 if (in_array($field, $numeric_fields)) {
124 $newdata[$field] = (int)$data[$field];
126 $newdata[$field] = $data[$field];
128 } elseif (!in_array($field, $numeric_fields)) {
129 $newdata[$field] = '';
131 $newdata[$field] = null;
135 // We don't use the "priority" field anymore and replace it with a dummy.
136 $newdata['priority'] = 0;
142 * Check if the hostname belongs to the own server
144 * @param string $host The hostname that is to be checked
145 * @return bool Does the testes hostname belongs to the own server?
147 private static function ownHost(string $host): bool
149 $own_host = DI::baseUrl()->getHostname();
151 $parts = parse_url($host);
153 if (!isset($parts['scheme'])) {
154 $parts = parse_url('http://' . $host);
157 if (!isset($parts['host'])) {
160 return $parts['host'] == $own_host;
164 * Probes for webfinger path via "host-meta"
166 * We have to check if the servers in the future still will offer this.
167 * It seems as if it was dropped from the standard.
169 * @param string $host The host part of an url
171 * @return array with template and type of the webfinger template for JSON or XML
172 * @throws HTTPException\InternalServerErrorException
174 private static function hostMeta(string $host): array
176 // Reset the static variable
179 // Handles the case when the hostname contains the scheme
180 if (!parse_url($host, PHP_URL_SCHEME)) {
181 $ssl_url = 'https://' . $host . self::HOST_META;
182 $url = 'http://' . $host . self::HOST_META;
184 $ssl_url = $host . self::HOST_META;
188 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
190 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
193 $curlResult = DI::httpClient()->get($ssl_url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
194 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
195 if ($curlResult->isSuccess()) {
196 $xml = $curlResult->getBody();
197 $xrd = XML::parseString($xml, true);
199 $host_url = 'https://' . $host;
203 } elseif ($curlResult->isTimeout()) {
204 Logger::info('Probing timeout', ['url' => $ssl_url]);
205 self::$isTimeout = true;
209 if (!is_object($xrd) && !empty($url)) {
210 $curlResult = DI::httpClient()->get($url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
211 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
212 if ($curlResult->isTimeout()) {
213 Logger::info('Probing timeout', ['url' => $url]);
214 self::$isTimeout = true;
216 } elseif ($connection_error && $ssl_connection_error) {
217 self::$isTimeout = true;
221 $xml = $curlResult->getBody();
222 $xrd = XML::parseString($xml, true);
223 $host_url = 'http://'.$host;
225 if (!is_object($xrd)) {
226 Logger::info('No xrd object found', ['host' => $host]);
230 $links = XML::elementToArray($xrd);
231 if (!isset($links['xrd']['link'])) {
232 Logger::info('No xrd data found', ['host' => $host]);
238 foreach ($links['xrd']['link'] as $value => $link) {
239 if (!empty($link['@attributes'])) {
240 $attributes = $link['@attributes'];
241 } elseif ($value == '@attributes') {
247 if (!empty($attributes['rel']) && $attributes['rel'] == 'lrdd' && !empty($attributes['template'])) {
248 $type = (empty($attributes['type']) ? '' : $attributes['type']);
250 $lrdd[$type] = $attributes['template'];
254 if (Network::isUrlBlocked($host_url)) {
255 Logger::info('Domain is blocked', ['url' => $host]);
259 self::$baseurl = $host_url;
261 Logger::info('Probing successful', ['host' => $host]);
267 * Check an URI for LRDD data
269 * @param string $uri Address that should be probed
270 * @return array uri data
271 * @throws HTTPException\InternalServerErrorException
273 public static function lrdd(string $uri): array
275 $data = self::getWebfingerArray($uri);
279 $webfinger = $data['webfinger'];
281 if (empty($webfinger['links'])) {
282 Logger::info('No webfinger links found', ['uri' => $uri]);
288 foreach ($webfinger['links'] as $link) {
289 $data[] = ['@attributes' => $link];
292 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
293 foreach ($webfinger['aliases'] as $alias) {
307 * Fetch information (protocol endpoints and user information) about a given uri
309 * @param string $uri Address that should be probed
310 * @param string $network Test for this specific network
311 * @param integer $uid User ID for the probe (only used for mails)
312 * @param boolean $cache Use cached values?
314 * @return array uri data
315 * @throws HTTPException\InternalServerErrorException
316 * @throws \ImagickException
318 public static function uri(string $uri, string $network = '', int $uid = -1): array
320 // Local profiles aren't probed via network
321 if (empty($network) && Contact::isLocal($uri)) {
322 $data = self::localProbe($uri);
329 $uid = DI::userSession()->getLocalUserId();
332 if (empty($network) || ($network == Protocol::ACTIVITYPUB)) {
333 $ap_profile = ActivityPub::probeProfile($uri);
338 self::$isTimeout = false;
340 if ($network != Protocol::ACTIVITYPUB) {
341 $data = self::detect($uri, $network, $uid, $ap_profile);
342 if (!is_array($data)) {
345 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
347 } elseif (!empty($ap_profile)) {
348 $ap_profile['batch'] = '';
349 $data = array_merge($ap_profile, $data);
355 if (!isset($data['url'])) {
359 if (empty($data['photo'])) {
360 $data['photo'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
363 if (empty($data['name'])) {
364 if (!empty($data['nick'])) {
365 $data['name'] = $data['nick'];
368 if (empty($data['name'])) {
369 $data['name'] = $data['url'];
373 if (empty($data['nick'])) {
374 $data['nick'] = strtolower($data['name']);
376 if (strpos($data['nick'], ' ')) {
377 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
381 if (!empty($data['baseurl']) && empty($data['gsid'])) {
382 $data['gsid'] = GServer::getID($data['baseurl']);
385 if (empty($data['network'])) {
386 $data['network'] = Protocol::PHANTOM;
389 // Ensure that local connections always are DFRN
390 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
391 $data['network'] = Protocol::DFRN;
394 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
395 $data['hide'] = self::getHideStatus($data['url']);
398 return self::rearrangeData($data);
403 * Fetches the "hide" status from the profile
405 * @param string $url URL of the profile
406 * @return boolean "hide" status
408 private static function getHideStatus(string $url): bool
410 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::CONTENT_LENGTH => 1000000]);
411 if (!$curlResult->isSuccess()) {
415 // If it isn't a HTML file then exit
416 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
420 $body = $curlResult->getBody();
425 $doc = new DOMDocument();
426 @$doc->loadHTML($body);
428 $xpath = new DOMXPath($doc);
430 $list = $xpath->query('//meta[@name]');
431 foreach ($list as $node) {
433 if ($node->attributes->length) {
434 foreach ($node->attributes as $attribute) {
435 $meta_tag[$attribute->name] = $attribute->value;
439 if (empty($meta_tag['content'])) {
443 $content = strtolower(trim($meta_tag['content']));
445 switch (strtolower(trim($meta_tag['name']))) {
446 case 'dfrn-global-visibility':
447 if ($content == 'false') {
452 if (strpos($content, 'noindex') !== false) {
463 * Fetch the "subscribe" and add it to the result
465 * @param array $result Result array
466 * @param array $webfinger Webfinger data
468 * @return array result Altered/unaltered result array
470 private static function getSubscribeLink(array $result, array $webfinger): array
472 if (empty($webfinger['links'])) {
476 foreach ($webfinger['links'] as $link) {
477 if (!empty($link['template']) && ($link['rel'] === ActivityNamespace::OSTATUSSUB)) {
478 $result['subscribe'] = $link['template'];
486 * Get webfinger data from a given URI
488 * @param string $uri URI
490 * @return array Webfinger data
491 * @throws HTTPException\InternalServerErrorException
493 private static function getWebfingerArray(string $uri): array
495 $parts = parse_url($uri);
497 if (!empty($parts['scheme']) && !empty($parts['host'])) {
498 $host = $parts['host'];
499 if (!empty($parts['port'])) {
500 $host .= ':' . $parts['port'];
503 $baseurl = $parts['scheme'] . '://' . $host;
508 $path_parts = explode('/', trim($parts['path'] ?? '', '/'));
509 if (!empty($path_parts)) {
510 $nick = ltrim(end($path_parts), '@');
511 $addr = $nick . '@' . $host;
514 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
515 if (empty($webfinger)) {
516 $lrdd = self::hostMeta($host);
519 if (empty($webfinger) && empty($lrdd)) {
520 while (empty($lrdd) && empty($webfinger) && (sizeof($path_parts) > 1)) {
521 $host .= '/' . array_shift($path_parts);
522 $baseurl = $parts['scheme'] . '://' . $host;
525 $addr = $nick . '@' . $host;
528 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
529 if (empty($webfinger)) {
530 $lrdd = self::hostMeta($host);
534 if (empty($lrdd) && empty($webfinger)) {
538 } elseif (strstr($uri, '@')) {
539 // Remove "acct:" from the URI
540 $uri = str_replace('acct:', '', $uri);
542 $host = substr($uri, strpos($uri, '@') + 1);
543 $nick = substr($uri, 0, strpos($uri, '@'));
546 $webfinger = self::getWebfinger('https://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
547 if (self::$isTimeout) {
551 if (empty($webfinger)) {
552 $webfinger = self::getWebfinger('http://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
553 if (self::$isTimeout) {
557 $baseurl = 'https://' . $host;
560 if (empty($webfinger)) {
561 $lrdd = self::hostMeta($host);
562 if (self::$isTimeout) {
565 $baseurl = self::$baseurl;
567 $baseurl = 'http://' . $host;
570 Logger::info('URI was not detectable', ['uri' => $uri]);
574 if (empty($webfinger)) {
575 foreach ($lrdd as $type => $template) {
580 $webfinger = self::getWebfinger($template, $type, $uri, $addr);
584 if (empty($webfinger)) {
588 if ($webfinger['detected'] == $addr) {
589 $webfinger['nick'] = $nick;
590 $webfinger['addr'] = $addr;
593 $webfinger['baseurl'] = $baseurl;
599 * Perform network request for webfinger data
601 * @param string $template
602 * @param string $type
604 * @param string $addr
606 * @return array webfinger results
608 private static function getWebfinger(string $template, string $type, string $uri, string $addr): array
610 if (Network::isUrlBlocked($template)) {
611 Logger::info('Domain is blocked', ['url' => $template]);
615 // First try the address because this is the primary purpose of webfinger
618 $path = str_replace('{uri}', urlencode('acct:' . $addr), $template);
619 $webfinger = self::webfinger($path, $type);
620 if (self::$isTimeout) {
626 if (empty($webfinger) && $uri != $addr) {
628 $path = str_replace('{uri}', urlencode($uri), $template);
629 $webfinger = self::webfinger($path, $type);
630 if (self::$isTimeout) {
635 if (empty($webfinger)) {
639 return ['webfinger' => $webfinger, 'detected' => $detected];
643 * Fetch information (protocol endpoints and user information) about a given uri
645 * This function is only called by the "uri" function that adds caching and rearranging of data.
647 * @param string $uri Address that should be probed
648 * @param string $network Test for this specific network
649 * @param integer $uid User ID for the probe (only used for mails)
650 * @param array $ap_profile Previously probed AP profile
651 * @return array URI data
652 * @throws HTTPException\InternalServerErrorException
654 private static function detect(string $uri, string $network, int $uid, array $ap_profile): array
658 'network' => $network,
663 Hook::callAll('probe_detect', $hookData);
665 if (isset($hookData['result'])) {
666 return is_array($hookData['result']) ? $hookData['result'] : [];
669 $parts = parse_url($uri);
670 if (empty($parts['scheme']) && empty($parts['host']) && !strstr($parts['path'], '@')) {
671 Logger::info('URI was not detectable', ['uri' => $uri]);
675 // If the URI starts with "mailto:" then jump directly to the mail detection
676 if (strpos($uri, 'mailto:') !== false) {
677 $uri = str_replace('mailto:', '', $uri);
678 return self::mail($uri, $uid);
681 if ($network == Protocol::MAIL) {
682 return self::mail($uri, $uid);
685 Logger::info('Probing start', ['uri' => $uri]);
687 if (!empty($ap_profile['addr']) && ($ap_profile['addr'] != $uri)) {
688 $data = self::getWebfingerArray($ap_profile['addr']);
692 $data = self::getWebfingerArray($uri);
696 if (!empty($parts['scheme'])) {
697 return self::feed($uri);
698 } elseif (!empty($uid)) {
699 return self::mail($uri, $uid);
705 $webfinger = $data['webfinger'];
706 $nick = $data['nick'] ?? '';
707 $addr = $data['addr'] ?? '';
708 $baseurl = $data['baseurl'] ?? '';
712 if (in_array($network, ['', Protocol::DFRN])) {
713 $result = self::dfrn($webfinger);
715 if ((!$result && ($network == '')) || ($network == Protocol::DIASPORA)) {
716 $result = self::diaspora($webfinger);
718 if ((!$result && ($network == '')) || ($network == Protocol::OSTATUS)) {
719 $result = self::ostatus($webfinger);
721 if (in_array($network, ['', Protocol::ZOT])) {
722 $result = self::zot($webfinger, $result, $baseurl);
724 if ((!$result && ($network == '')) || ($network == Protocol::PUMPIO)) {
725 $result = self::pumpio($webfinger, $addr);
727 if (empty($result['network']) && empty($ap_profile['network']) || ($network == Protocol::FEED)) {
728 $result = self::feed($uri);
730 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
731 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
732 if ((empty($result['nick']) || (strstr($result['nick'], ' '))) && ($nick != '')) {
733 $result['nick'] = $nick;
736 if (empty($result['addr']) && ($addr != '')) {
737 $result['addr'] = $addr;
741 $result = self::getSubscribeLink($result, $webfinger);
743 if (empty($result['network'])) {
744 $result['network'] = Protocol::PHANTOM;
747 if (empty($result['baseurl']) && !empty($baseurl)) {
748 $result['baseurl'] = $baseurl;
751 if (empty($result['url'])) {
752 $result['url'] = $uri;
755 Logger::info('Probing done', ['uri' => $uri, 'network' => $result['network']]);
761 * Check for Zot contact
763 * @param array $webfinger Webfinger data
764 * @param array $data previously probed data
765 * @param string $baseUrl Base URL
767 * @return array Zot data
768 * @throws HTTPException\InternalServerErrorException
770 private static function zot(array $webfinger, array $data, string $baseurl): array
772 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
773 foreach ($webfinger['aliases'] as $alias) {
774 if (substr($alias, 0, 5) == 'acct:') {
775 $data['addr'] = substr($alias, 5);
780 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
781 $data['addr'] = substr($webfinger['subject'], 5);
785 foreach ($webfinger['links'] as $link) {
786 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
787 $zot_url = $link['href'];
791 if (empty($zot_url) && !empty($data['addr']) && !empty($baseurl)) {
792 $condition = ['nurl' => Strings::normaliseLink($baseurl), 'platform' => ['hubzilla']];
793 if (!DBA::exists('gserver', $condition)) {
796 $zot_url = $baseurl . '/.well-known/zot-info?address=' . $data['addr'];
799 if (empty($zot_url)) {
803 $data = self::pollZot($zot_url, $data);
805 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
806 foreach ($webfinger['aliases'] as $alias) {
807 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
808 $data['alias'] = $alias;
816 public static function pollZot(string $url, array $data): array
818 $curlResult = DI::httpClient()->get($url, HttpClientAccept::JSON);
819 if ($curlResult->isTimeout()) {
822 $content = $curlResult->getBody();
827 $json = json_decode($content, true);
828 if (!is_array($json)) {
832 if (empty($data['network'])) {
833 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
834 $data['network'] = Protocol::ZOT;
835 } elseif (!isset($json['protocols'])) {
836 $data['network'] = Protocol::ZOT;
840 if (!empty($json['guid']) && empty($data['guid'])) {
841 $data['guid'] = $json['guid'];
843 if (!empty($json['key']) && empty($data['pubkey'])) {
844 $data['pubkey'] = $json['key'];
846 if (!empty($json['name'])) {
847 $data['name'] = $json['name'];
849 if (!empty($json['photo'])) {
850 $data['photo'] = $json['photo'];
851 if (!empty($json['photo_updated'])) {
852 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
855 if (!empty($json['address'])) {
856 $data['addr'] = $json['address'];
858 if (!empty($json['url'])) {
859 $data['url'] = $json['url'];
861 if (!empty($json['connections_url'])) {
862 $data['poco'] = $json['connections_url'];
864 if (isset($json['searchable'])) {
865 $data['hide'] = !$json['searchable'];
867 if (!empty($json['public_forum'])) {
868 $data['community'] = $json['public_forum'];
869 $data['account-type'] = User::PAGE_FLAGS_COMMUNITY;
872 if (!empty($json['profile'])) {
873 $profile = $json['profile'];
874 if (!empty($profile['description'])) {
875 $data['about'] = $profile['description'];
877 if (!empty($profile['keywords'])) {
878 $keywords = implode(', ', $profile['keywords']);
879 if (!empty($keywords)) {
880 $data['keywords'] = $keywords;
885 if (!empty($profile['region'])) {
886 $loc['region'] = $profile['region'];
888 if (!empty($profile['country'])) {
889 $loc['country-name'] = $profile['country'];
891 $location = Profile::formatLocation($loc);
892 if (!empty($location)) {
893 $data['location'] = $location;
901 * Perform a webfinger request.
903 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
905 * @param string $url Address that should be probed
906 * @param string $type type
908 * @return array webfinger data
909 * @throws HTTPException\InternalServerErrorException
911 public static function webfinger(string $url, string $type): array
913 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
915 $curlResult = DI::httpClient()->get($url, $type, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
916 if ($curlResult->isTimeout()) {
917 self::$isTimeout = true;
920 $data = $curlResult->getBody();
922 $webfinger = json_decode($data, true);
923 if (!empty($webfinger)) {
924 if (!isset($webfinger['links'])) {
925 Logger::info('No json webfinger links', ['url' => $url]);
931 // If it is not JSON, maybe it is XML
932 $xrd = XML::parseString($data, true);
933 if (!is_object($xrd)) {
934 Logger::info('No webfinger data retrievable', ['url' => $url]);
938 $xrd_arr = XML::elementToArray($xrd);
939 if (!isset($xrd_arr['xrd']['link'])) {
940 Logger::info('No XML webfinger links', ['url' => $url]);
946 if (!empty($xrd_arr['xrd']['subject'])) {
947 $webfinger['subject'] = $xrd_arr['xrd']['subject'];
950 if (!empty($xrd_arr['xrd']['alias'])) {
951 $webfinger['aliases'] = $xrd_arr['xrd']['alias'];
954 $webfinger['links'] = [];
956 foreach ($xrd_arr['xrd']['link'] as $value => $data) {
957 if (!empty($data['@attributes'])) {
958 $attributes = $data['@attributes'];
959 } elseif ($value == '@attributes') {
965 $webfinger['links'][] = $attributes;
971 * Poll the Friendica specific noscrape page.
973 * "noscrape" is a faster alternative to fetch the data from the hcard.
974 * This functionality was originally created for the directory.
976 * @param string $noscrape_url Link to the noscrape page
977 * @param array $data The already fetched data
979 * @return array noscrape data
980 * @throws HTTPException\InternalServerErrorException
982 private static function pollNoscrape(string $noscrape_url, array $data): array
984 $curlResult = DI::httpClient()->get($noscrape_url, HttpClientAccept::JSON);
985 if ($curlResult->isTimeout()) {
986 self::$isTimeout = true;
989 $content = $curlResult->getBody();
991 Logger::info('Empty body', ['url' => $noscrape_url]);
995 $json = json_decode($content, true);
996 if (!is_array($json)) {
997 Logger::info('No json data', ['url' => $noscrape_url]);
1001 if (!empty($json['fn'])) {
1002 $data['name'] = $json['fn'];
1005 if (!empty($json['addr'])) {
1006 $data['addr'] = $json['addr'];
1009 if (!empty($json['nick'])) {
1010 $data['nick'] = $json['nick'];
1013 if (!empty($json['guid'])) {
1014 $data['guid'] = $json['guid'];
1017 if (!empty($json['comm'])) {
1018 $data['community'] = $json['comm'];
1021 if (!empty($json['tags'])) {
1022 $keywords = implode(', ', $json['tags']);
1023 if ($keywords != '') {
1024 $data['keywords'] = $keywords;
1028 $location = Profile::formatLocation($json);
1030 $data['location'] = $location;
1033 if (!empty($json['about'])) {
1034 $data['about'] = $json['about'];
1037 if (!empty($json['xmpp'])) {
1038 $data['xmpp'] = $json['xmpp'];
1041 if (!empty($json['matrix'])) {
1042 $data['matrix'] = $json['matrix'];
1045 if (!empty($json['key'])) {
1046 $data['pubkey'] = $json['key'];
1049 if (!empty($json['photo'])) {
1050 $data['photo'] = $json['photo'];
1053 if (!empty($json['dfrn-request'])) {
1054 $data['request'] = $json['dfrn-request'];
1057 if (!empty($json['dfrn-confirm'])) {
1058 $data['confirm'] = $json['dfrn-confirm'];
1061 if (!empty($json['dfrn-notify'])) {
1062 $data['notify'] = $json['dfrn-notify'];
1065 if (!empty($json['dfrn-poll'])) {
1066 $data['poll'] = $json['dfrn-poll'];
1069 if (isset($json['hide'])) {
1070 $data['hide'] = (bool)$json['hide'];
1072 $data['hide'] = false;
1079 * Check for valid DFRN data
1081 * @param array $data DFRN data
1083 * @return int Number of errors
1085 public static function validDfrn(array $data): int
1088 if (!isset($data['key'])) {
1091 if (!isset($data['dfrn-request'])) {
1094 if (!isset($data['dfrn-confirm'])) {
1097 if (!isset($data['dfrn-notify'])) {
1100 if (!isset($data['dfrn-poll'])) {
1107 * Fetch data from a DFRN profile page and via "noscrape"
1109 * @param string $profile_link Link to the profile page
1110 * @return array profile data
1111 * @throws HTTPException\InternalServerErrorException
1112 * @throws \ImagickException
1114 public static function profile(string $profile_link): array
1118 Logger::info('Check profile', ['link' => $profile_link]);
1120 // Fetch data via noscrape - this is faster
1121 $noscrape_url = str_replace(['/hcard/', '/profile/'], '/noscrape/', $profile_link);
1122 $data = self::pollNoscrape($noscrape_url, $data);
1124 if (!isset($data['notify'])
1125 || !isset($data['confirm'])
1126 || !isset($data['request'])
1127 || !isset($data['poll'])
1128 || !isset($data['name'])
1129 || !isset($data['photo'])
1131 $data = self::pollHcard($profile_link, $data, true);
1136 if (empty($data['addr']) || empty($data['nick'])) {
1137 $probe_data = self::uri($profile_link);
1138 $data['addr'] = ($data['addr'] ?? '') ?: $probe_data['addr'];
1139 $data['nick'] = ($data['nick'] ?? '') ?: $probe_data['nick'];
1142 $prof_data['addr'] = $data['addr'];
1143 $prof_data['nick'] = $data['nick'];
1144 $prof_data['dfrn-request'] = $data['request'] ?? null;
1145 $prof_data['dfrn-confirm'] = $data['confirm'] ?? null;
1146 $prof_data['dfrn-notify'] = $data['notify'] ?? null;
1147 $prof_data['dfrn-poll'] = $data['poll'] ?? null;
1148 $prof_data['photo'] = $data['photo'] ?? null;
1149 $prof_data['fn'] = $data['name'] ?? null;
1150 $prof_data['key'] = $data['pubkey'] ?? null;
1152 Logger::debug('Result', ['link' => $profile_link, 'data' => $prof_data]);
1158 * Check for DFRN contact
1160 * @param array $webfinger Webfinger data
1161 * @return array DFRN data
1162 * @throws HTTPException\InternalServerErrorException
1164 private static function dfrn(array $webfinger): array
1168 // The array is reversed to take into account the order of preference for same-rel links
1169 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1170 foreach (array_reverse($webfinger['links']) as $link) {
1171 if (($link['rel'] == ActivityNamespace::DFRN) && !empty($link['href'])) {
1172 $data['network'] = Protocol::DFRN;
1173 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1174 $data['poll'] = $link['href'];
1175 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1176 $data['url'] = $link['href'];
1177 } elseif (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1178 $hcard_url = $link['href'];
1179 } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1180 $data['poco'] = $link['href'];
1181 } elseif (($link['rel'] == 'http://webfinger.net/rel/avatar') && !empty($link['href'])) {
1182 $data['photo'] = $link['href'];
1183 } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1184 $data['baseurl'] = trim($link['href'], '/');
1185 } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1186 $data['guid'] = $link['href'];
1187 } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1188 $data['pubkey'] = base64_decode($link['href']);
1190 if (strstr($data['pubkey'], 'RSA ')) {
1191 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1196 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1197 foreach ($webfinger['aliases'] as $alias) {
1198 if (empty($data['url']) && !strstr($alias, '@')) {
1199 $data['url'] = $alias;
1200 } elseif (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
1201 $data['alias'] = $alias;
1202 } elseif (substr($alias, 0, 5) == 'acct:') {
1203 $data['addr'] = substr($alias, 5);
1208 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1209 $data['addr'] = substr($webfinger['subject'], 5);
1212 if (!isset($data['network']) || ($hcard_url == '')) {
1216 // Fetch data via noscrape - this is faster
1217 $noscrape_url = str_replace('/hcard/', '/noscrape/', $hcard_url);
1218 $data = self::pollNoscrape($noscrape_url, $data);
1220 if (isset($data['notify'])
1221 && isset($data['confirm'])
1222 && isset($data['request'])
1223 && isset($data['poll'])
1224 && isset($data['name'])
1225 && isset($data['photo'])
1230 $data = self::pollHcard($hcard_url, $data, true);
1236 * Poll the hcard page (Diaspora and Friendica specific)
1238 * @param string $hcard_url Link to the hcard page
1239 * @param array $data The already fetched data
1240 * @param boolean $dfrn Poll DFRN specific data
1241 * @return array hcard data
1242 * @throws HTTPException\InternalServerErrorException
1244 private static function pollHcard(string $hcard_url, array $data, bool $dfrn = false): array
1246 $curlResult = DI::httpClient()->get($hcard_url, HttpClientAccept::HTML);
1247 if ($curlResult->isTimeout()) {
1248 self::$isTimeout = true;
1251 $content = $curlResult->getBody();
1252 if (empty($content)) {
1256 $doc = new DOMDocument();
1257 if (!@$doc->loadHTML($content)) {
1261 $xpath = new DomXPath($doc);
1263 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1264 if (!is_object($vcards)) {
1268 if (!isset($data['baseurl'])) {
1269 $data['baseurl'] = '';
1272 if ($vcards->length > 0) {
1273 $vcard = $vcards->item(0);
1275 // We have to discard the guid from the hcard in favour of the guid from lrdd
1276 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1277 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1278 if (($search->length > 0) && empty($data['guid'])) {
1279 $data['guid'] = $search->item(0)->nodeValue;
1282 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1283 if ($search->length > 0) {
1284 $data['nick'] = $search->item(0)->nodeValue;
1287 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1288 if ($search->length > 0) {
1289 $data['name'] = $search->item(0)->nodeValue;
1292 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1293 if ($search->length > 0) {
1294 $data['searchable'] = $search->item(0)->nodeValue;
1297 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1298 if ($search->length > 0) {
1299 $data['pubkey'] = $search->item(0)->nodeValue;
1300 if (strstr($data['pubkey'], 'RSA ')) {
1301 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1305 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1306 if ($search->length > 0) {
1307 $data['baseurl'] = trim($search->item(0)->nodeValue, '/');
1312 if (!empty($vcard)) {
1313 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1314 foreach ($photos as $photo) {
1316 foreach ($photo->attributes as $attribute) {
1317 $attr[$attribute->name] = trim($attribute->value);
1320 if (isset($attr['src']) && isset($attr['width'])) {
1321 $avatar[$attr['width']] = $attr['src'];
1324 // We don't have a width. So we just take everything that we got.
1325 // This is a Hubzilla workaround which doesn't send a width.
1326 if ((sizeof($avatar) == 0) && !empty($attr['src'])) {
1327 $avatar[] = $attr['src'];
1332 if (sizeof($avatar)) {
1334 $data['photo'] = self::fixAvatar(array_pop($avatar), $data['baseurl']);
1338 // Poll DFRN specific data
1339 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1340 if ($search->length > 0) {
1341 foreach ($search as $link) {
1342 //$data['request'] = $search->item(0)->nodeValue;
1344 foreach ($link->attributes as $attribute) {
1345 $attr[$attribute->name] = trim($attribute->value);
1348 $data[substr($attr['rel'], 5)] = $attr['href'];
1352 // Older Friendica versions had used the "uid" field differently than newer versions
1353 if (!empty($data['nick']) && !empty($data['guid']) && ($data['nick'] == $data['guid'])) {
1354 unset($data['guid']);
1363 * Check for Diaspora contact
1365 * @param array $webfinger Webfinger data
1367 * @return array Diaspora data
1368 * @throws HTTPException\InternalServerErrorException
1370 private static function diaspora(array $webfinger): array
1375 // The array is reversed to take into account the order of preference for same-rel links
1376 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1377 foreach (array_reverse($webfinger['links']) as $link) {
1378 if (($link['rel'] == 'http://microformats.org/profile/hcard') && !empty($link['href'])) {
1379 $hcard_url = $link['href'];
1380 } elseif (($link['rel'] == 'http://joindiaspora.com/seed_location') && !empty($link['href'])) {
1381 $data['baseurl'] = trim($link['href'], '/');
1382 } elseif (($link['rel'] == 'http://joindiaspora.com/guid') && !empty($link['href'])) {
1383 $data['guid'] = $link['href'];
1384 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && (($link['type'] ?? '') == 'text/html') && !empty($link['href'])) {
1385 $data['url'] = $link['href'];
1386 } elseif (($link['rel'] == 'http://webfinger.net/rel/profile-page') && empty($link['type']) && !empty($link['href'])) {
1387 $profile_url = $link['href'];
1388 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1389 $data['poll'] = $link['href'];
1390 } elseif (($link['rel'] == ActivityNamespace::POCO) && !empty($link['href'])) {
1391 $data['poco'] = $link['href'];
1392 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1393 $data['notify'] = $link['href'];
1394 } elseif (($link['rel'] == 'diaspora-public-key') && !empty($link['href'])) {
1395 $data['pubkey'] = base64_decode($link['href']);
1397 if (strstr($data['pubkey'], 'RSA ')) {
1398 $data['pubkey'] = Crypto::rsaToPem($data['pubkey']);
1403 if (empty($data['url']) && !empty($profile_url)) {
1404 $data['url'] = $profile_url;
1407 if (empty($data['url']) || empty($hcard_url)) {
1411 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1412 foreach ($webfinger['aliases'] as $alias) {
1413 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data['url']) && ! strstr($alias, '@')) {
1414 $data['alias'] = $alias;
1415 } elseif (substr($alias, 0, 5) == 'acct:') {
1416 $data['addr'] = substr($alias, 5);
1421 if (!empty($webfinger['subject']) && (substr($webfinger['subject'], 0, 5) == 'acct:')) {
1422 $data['addr'] = substr($webfinger['subject'], 5);
1425 // Fetch further information from the hcard
1426 $data = self::pollHcard($hcard_url, $data);
1432 if (!empty($data['url'])
1433 && !empty($data['guid'])
1434 && !empty($data['baseurl'])
1435 && !empty($data['pubkey'])
1436 && !empty($hcard_url)
1438 $data['network'] = Protocol::DIASPORA;
1439 $data['manually-approve'] = false;
1441 // The Diaspora handle must always be lowercase
1442 if (!empty($data['addr'])) {
1443 $data['addr'] = strtolower($data['addr']);
1446 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1447 $data['notify'] = $data['baseurl'] . '/receive/users/' . $data['guid'];
1448 $data['batch'] = $data['baseurl'] . '/receive/public';
1457 * Check for OStatus contact
1459 * @param array $webfinger Webfinger data
1460 * @param bool $short Short detection mode
1462 * @return array|bool OStatus data or "false" on error or "true" on short mode
1463 * @throws HTTPException\InternalServerErrorException
1465 private static function ostatus(array $webfinger, bool $short = false)
1469 if (!empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
1470 foreach ($webfinger['aliases'] as $alias) {
1471 if (strstr($alias, '@') && !strstr(Strings::normaliseLink($alias), 'http://')) {
1472 $data['addr'] = str_replace('acct:', '', $alias);
1477 if (!empty($webfinger['subject']) && strstr($webfinger['subject'], '@')
1478 && !strstr(Strings::normaliseLink($webfinger['subject']), 'http://')
1480 $data['addr'] = str_replace('acct:', '', $webfinger['subject']);
1483 if (!empty($webfinger['links'])) {
1484 // The array is reversed to take into account the order of preference for same-rel links
1485 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1486 foreach (array_reverse($webfinger['links']) as $link) {
1487 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1488 && (($link['type'] ?? '') == 'text/html')
1489 && ($link['href'] != '')
1491 $data['url'] = $data['alias'] = $link['href'];
1492 } elseif (($link['rel'] == 'salmon') && !empty($link['href'])) {
1493 $data['notify'] = $link['href'];
1494 } elseif (($link['rel'] == ActivityNamespace::FEED) && !empty($link['href'])) {
1495 $data['poll'] = $link['href'];
1496 } elseif (($link['rel'] == 'magic-public-key') && !empty($link['href'])) {
1497 $pubkey = $link['href'];
1499 if (substr($pubkey, 0, 5) === 'data:') {
1500 if (strstr($pubkey, ',')) {
1501 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1503 $pubkey = substr($pubkey, 5);
1505 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1506 $curlResult = DI::httpClient()->get($pubkey, HttpClientAccept::MAGIC_KEY);
1507 if ($curlResult->isTimeout()) {
1508 self::$isTimeout = true;
1509 return $short ? false : [];
1511 Logger::debug('Fetched public key', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $pubkey]);
1512 $pubkey = $curlResult->getBody();
1515 $key = explode('.', $pubkey);
1517 if (sizeof($key) >= 3) {
1518 $m = Strings::base64UrlDecode($key[1]);
1519 $e = Strings::base64UrlDecode($key[2]);
1520 $data['pubkey'] = Crypto::meToPem($m, $e);
1526 if (isset($data['notify']) && isset($data['pubkey'])
1527 && isset($data['poll'])
1528 && isset($data['url'])
1530 $data['network'] = Protocol::OSTATUS;
1531 $data['manually-approve'] = false;
1533 return $short ? false : [];
1540 // Fetch all additional data from the feed
1541 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::FEED_XML);
1542 if ($curlResult->isTimeout()) {
1543 self::$isTimeout = true;
1546 $feed = $curlResult->getBody();
1547 $feed_data = Feed::import($feed);
1552 if (!empty($feed_data['header']['author-name'])) {
1553 $data['name'] = $feed_data['header']['author-name'];
1555 if (!empty($feed_data['header']['author-nick'])) {
1556 $data['nick'] = $feed_data['header']['author-nick'];
1558 if (!empty($feed_data['header']['author-avatar'])) {
1559 $data['photo'] = self::fixAvatar($feed_data['header']['author-avatar'], $data['url']);
1561 if (!empty($feed_data['header']['author-id'])) {
1562 $data['alias'] = $feed_data['header']['author-id'];
1564 if (!empty($feed_data['header']['author-location'])) {
1565 $data['location'] = $feed_data['header']['author-location'];
1567 if (!empty($feed_data['header']['author-about'])) {
1568 $data['about'] = $feed_data['header']['author-about'];
1570 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1571 // So we take the value that we just fetched, although the other one worked as well
1572 if (!empty($feed_data['header']['author-link'])) {
1573 $data['url'] = $feed_data['header']['author-link'];
1576 if ($data['url'] == $data['alias']) {
1577 $data['alias'] = '';
1580 /// @todo Fetch location and "about" from the feed as well
1585 * Fetch data from a pump.io profile page
1587 * @param string $profile_link Link to the profile page
1589 * @return array Profile data
1591 private static function pumpioProfileData(string $profile_link): array
1593 $curlResult = DI::httpClient()->get($profile_link, HttpClientAccept::HTML);
1594 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
1598 $doc = new DOMDocument();
1599 if (!@$doc->loadHTML($curlResult->getBody())) {
1603 $xpath = new DomXPath($doc);
1606 $data['name'] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1608 if ($data['name'] == '') {
1609 // This is ugly - but pump.io doesn't seem to know a better way for it
1610 $data['name'] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1611 $pos = strpos($data['name'], chr(10));
1613 $data['name'] = trim(substr($data['name'], 0, $pos));
1617 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1619 if ($data['location'] == '') {
1620 $data['location'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1623 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1625 if ($data['about'] == '') {
1626 $data['about'] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1629 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1631 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1634 foreach ($avatar->attributes as $attribute) {
1635 if ($attribute->name == 'src') {
1636 $data['photo'] = trim($attribute->value);
1645 * Check for pump.io contact
1647 * @param array $webfinger Webfinger data
1648 * @param string $addr
1650 * @return array pump.io data
1652 private static function pumpio(array $webfinger, string $addr): array
1655 // The array is reversed to take into account the order of preference for same-rel links
1656 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1657 foreach (array_reverse($webfinger['links']) as $link) {
1658 if (($link['rel'] == 'http://webfinger.net/rel/profile-page')
1659 && (($link['type'] ?? '') == 'text/html')
1660 && ($link['href'] != '')
1662 $data['url'] = $link['href'];
1663 } elseif (($link['rel'] == 'activity-inbox') && ($link['href'] != '')) {
1664 $data['notify'] = $link['href'];
1665 } elseif (($link['rel'] == 'activity-outbox') && ($link['href'] != '')) {
1666 $data['poll'] = $link['href'];
1667 } elseif (($link['rel'] == 'dialback') && ($link['href'] != '')) {
1668 $data['dialback'] = $link['href'];
1671 if (isset($data['poll']) && isset($data['notify'])
1672 && isset($data['dialback'])
1673 && isset($data['url'])
1675 // by now we use these fields only for the network type detection
1676 // So we unset all data that isn't used at the moment
1677 unset($data['dialback']);
1679 $data['network'] = Protocol::PUMPIO;
1684 $profile_data = self::pumpioProfileData($data['url']);
1686 if (!$profile_data) {
1690 $data = array_merge($data, $profile_data);
1692 if (($addr != '') && ($data['name'] != '')) {
1693 $name = trim(str_replace($addr, '', $data['name']));
1695 $data['name'] = $name;
1703 * Checks HTML page for RSS feed link
1705 * @param string $url Page link
1706 * @param string $body Page body string
1708 * @return string|false Feed link or false if body was invalid HTML document
1710 public static function getFeedLink(string $url, string $body)
1716 $doc = new DOMDocument();
1717 if (!@$doc->loadHTML($body)) {
1721 $xpath = new DOMXPath($doc);
1723 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1725 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1731 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1733 * Loosely based on RFC 1808
1735 * @see https://tools.ietf.org/html/rfc1808
1737 * @param string $href The potential relative href found in the HTML document
1738 * @param string $base The HTML document URL
1739 * @param DOMXPath $xpath The HTML document XPath
1741 * @return string Absolute URL
1743 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath): string
1745 if (filter_var($href, FILTER_VALIDATE_URL)) {
1749 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1751 $baseParts = parse_url($base);
1752 if (empty($baseParts['host'])) {
1756 // Naked domain case (scheme://basehost)
1757 $path = $baseParts['path'] ?? '/';
1759 // Remove the filename part of the path if it exists (/base/path/file)
1760 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1762 $hrefParts = parse_url($href);
1764 if (!empty($hrefParts['path'])) {
1765 // Root path case (/path) including relative scheme case (//host/path)
1766 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1767 $path = $hrefParts['path'];
1769 $path = $path . '/' . $hrefParts['path'];
1771 // Resolve arbitrary relative path
1772 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1773 $parts = array_filter(explode('/', $path), 'strlen');
1775 foreach ($parts as $part) {
1776 if ('.' == $part) continue;
1777 if ('..' == $part) {
1778 array_pop($absolutes);
1780 $absolutes[] = $part;
1784 $path = '/' . implode('/', $absolutes);
1788 // Relative scheme case (//host/path)
1789 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1790 $baseParts['path'] = $path;
1791 unset($baseParts['query']);
1792 unset($baseParts['fragment']);
1794 return Network::unparseURL($baseParts);
1798 * Check for feed contact
1800 * @param string $url Profile link
1801 * @param boolean $probe Do a probe if the page contains a feed link
1803 * @return array feed data
1804 * @throws HTTPException\InternalServerErrorException
1806 private static function feed(string $url, bool $probe = true): array
1808 $curlResult = DI::httpClient()->get($url, HttpClientAccept::FEED_XML);
1809 if ($curlResult->isTimeout()) {
1810 self::$isTimeout = true;
1813 $feed = $curlResult->getBody();
1814 $feed_data = Feed::import($feed);
1821 $feed_url = self::getFeedLink($url, $feed);
1827 return self::feed($feed_url, false);
1830 if (!empty($feed_data['header']['author-name'])) {
1831 $data['name'] = $feed_data['header']['author-name'];
1834 if (!empty($feed_data['header']['author-nick'])) {
1835 $data['nick'] = $feed_data['header']['author-nick'];
1838 if (!empty($feed_data['header']['author-avatar'])) {
1839 $data['photo'] = $feed_data['header']['author-avatar'];
1842 if (!empty($feed_data['header']['author-id'])) {
1843 $data['alias'] = $feed_data['header']['author-id'];
1846 $data['url'] = $url;
1847 $data['poll'] = $url;
1849 $data['network'] = Protocol::FEED;
1855 * Check for mail contact
1857 * @param string $uri Profile link
1858 * @param integer $uid User ID
1860 * @return array mail data
1861 * @throws \Exception
1863 private static function mail(string $uri, int $uid): array
1865 if (!Network::isEmailDomainValid($uri)) {
1873 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1875 $condition = ["`uid` = ? AND `server` != ''", $uid];
1876 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1877 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1879 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1883 $mailbox = Email::constructMailboxName($mailacct);
1885 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1886 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1891 $msgs = Email::poll($mbox, $uri);
1892 Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
1894 if (!count($msgs)) {
1898 $phost = substr($uri, strpos($uri, '@') + 1);
1902 'network' => Protocol::MAIL,
1903 'name' => substr($uri, 0, strpos($uri, '@')),
1904 'photo' => Network::lookupAvatarByEmail($uri),
1905 'url' => 'mailto:' . $uri,
1906 'notify' => 'smtp ' . Strings::getRandomHex(),
1907 'poll' => 'email ' . Strings::getRandomHex(),
1910 $data['nick'] = $data['name'];
1912 $x = Email::messageMeta($mbox, $msgs[0]);
1914 if (stristr($x[0]->from, $uri)) {
1915 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1916 } elseif (stristr($x[0]->to, $uri)) {
1917 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1921 foreach ($adr as $feadr) {
1922 if ((strcasecmp($feadr->mailbox, $data['name']) == 0)
1923 &&(strcasecmp($feadr->host, $phost) == 0)
1924 && (strlen($feadr->personal))
1926 $personal = imap_mime_header_decode($feadr->personal);
1928 foreach ($personal as $perspart) {
1929 if ($perspart->charset != 'default') {
1930 $data['name'] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1932 $data['name'] .= $perspart->text;
1939 if (!empty($mbox)) {
1947 * Mix two paths together to possibly fix missing parts
1949 * @param string $avatar Path to the avatar
1950 * @param string $base Another path that is hopefully complete
1952 * @return string fixed avatar path
1953 * @throws \Exception
1955 public static function fixAvatar(string $avatar, string $base): string
1957 $base_parts = parse_url($base);
1959 // Remove all parts that could create a problem
1960 unset($base_parts['path']);
1961 unset($base_parts['query']);
1962 unset($base_parts['fragment']);
1964 $avatar_parts = parse_url($avatar);
1967 $parts = array_merge($base_parts, $avatar_parts);
1969 // And put them together again
1970 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1971 $host = isset($parts['host']) ? $parts['host'] : '';
1972 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1973 $path = isset($parts['path']) ? $parts['path'] : '';
1974 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1975 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1977 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1979 Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
1985 * Fetch the last date that the contact had posted something (publically)
1987 * @param array $data probing result
1989 * @return string last activity
1991 public static function getLastUpdate(array $data): string
1993 $uid = User::getIdForURL($data['url']);
1995 $contact = Contact::selectFirst(['url', 'last-item'], ['self' => true, 'uid' => $uid]);
1996 if (!empty($contact['last-item'])) {
1997 return $contact['last-item'];
2001 if ($lastUpdate = self::updateFromNoScrape($data)) {
2005 if (!empty($data['outbox'])) {
2006 return self::updateFromOutbox($data['outbox'], $data);
2007 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
2008 return self::updateFromOutbox($data['poll'], $data);
2009 } elseif (!empty($data['poll'])) {
2010 return self::updateFromFeed($data);
2017 * Fetch the last activity date from the "noscrape" endpoint
2019 * @param array $data Probing result
2021 * @return string last activity or true if update was successful or the server was unreachable
2023 private static function updateFromNoScrape(array $data): string
2025 if (empty($data['baseurl'])) {
2029 // Check the 'noscrape' endpoint when it is a Friendica server
2030 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
2031 Strings::normaliseLink($data['baseurl'])]);
2032 if (!DBA::isResult($gserver)) {
2036 $curlResult = DI::httpClient()->get($gserver['noscrape'] . '/' . $data['nick'], HttpClientAccept::JSON);
2038 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
2039 $noscrape = json_decode($curlResult->getBody(), true);
2040 if (!empty($noscrape) && !empty($noscrape['updated'])) {
2041 return DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2049 * Fetch the last activity date from an ActivityPub Outbox
2051 * @param string $feed
2052 * @param array $data Probing result
2054 * @return string last activity
2055 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2057 private static function updateFromOutbox(string $feed, array $data): string
2059 $outbox = ActivityPub::fetchContent($feed);
2060 if (empty($outbox)) {
2064 if (!empty($outbox['orderedItems'])) {
2065 $items = $outbox['orderedItems'];
2066 } elseif (!empty($outbox['first']['orderedItems'])) {
2067 $items = $outbox['first']['orderedItems'];
2068 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2069 return self::updateFromOutbox($outbox['first']['href'], $data);
2070 } elseif (!empty($outbox['first'])) {
2071 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2072 return self::updateFromOutbox($outbox['first'], $data);
2074 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2082 foreach ($items as $activity) {
2083 if (!empty($activity['published'])) {
2084 $published = DateTimeFormat::utc($activity['published']);
2085 } elseif (!empty($activity['object']['published'])) {
2086 $published = DateTimeFormat::utc($activity['object']['published']);
2091 if ($last_updated < $published) {
2092 $last_updated = $published;
2096 if (!empty($last_updated)) {
2097 return $last_updated;
2104 * Fetch the last activity date from an XML feed
2106 * @param array $data Probing result
2107 * @return string last activity
2109 private static function updateFromFeed(array $data): string
2111 // Search for the newest entry in the feed
2112 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::ATOM_XML);
2113 if (!$curlResult->isSuccess() || !$curlResult->getBody()) {
2117 $doc = new DOMDocument();
2118 @$doc->loadXML($curlResult->getBody());
2120 $xpath = new DOMXPath($doc);
2121 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2123 $entries = $xpath->query('/atom:feed/atom:entry');
2127 foreach ($entries as $entry) {
2128 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2129 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
2130 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2131 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2133 if (empty($published) || empty($updated)) {
2134 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2138 if ($last_updated < $published) {
2139 $last_updated = $published;
2142 if ($last_updated < $updated) {
2143 $last_updated = $updated;
2147 if (!empty($last_updated)) {
2148 return $last_updated;
2155 * Probe data from local profiles without network traffic
2157 * @param string $url
2159 * @return array probed data
2160 * @throws HTTPException\InternalServerErrorException
2161 * @throws HTTPException\NotFoundException
2163 private static function localProbe(string $url): array
2166 $uid = User::getIdForURL($url);
2168 throw new HTTPException\NotFoundException('User not found.');
2171 $owner = User::getOwnerDataById($uid);
2172 $approfile = ActivityPub\Transmitter::getProfile($uid);
2174 if (empty($owner['gsid'])) {
2175 $owner['gsid'] = GServer::getID($approfile['generator']['url']);
2179 'name' => $owner['name'], 'nick' => $owner['nick'], 'guid' => $approfile['diaspora:guid'] ?? '',
2180 'url' => $owner['url'], 'addr' => $owner['addr'], 'alias' => $owner['alias'],
2181 'photo' => User::getAvatarUrl($owner),
2182 'header' => $owner['header'] ? Contact::getHeaderUrlForId($owner['id'], $owner['updated']) : '',
2183 'account-type' => $owner['contact-type'], 'community' => ($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY),
2184 'keywords' => $owner['keywords'], 'location' => $owner['location'], 'about' => $owner['about'],
2185 'xmpp' => $owner['xmpp'], 'matrix' => $owner['matrix'],
2186 'hide' => !$owner['net-publish'], 'batch' => '', 'notify' => $owner['notify'],
2187 'poll' => $owner['poll'], 'request' => $owner['request'], 'confirm' => $owner['confirm'],
2188 'subscribe' => $approfile['generator']['url'] . '/follow?url={uri}', 'poco' => $owner['poco'],
2189 'following' => $approfile['following'], 'followers' => $approfile['followers'],
2190 'inbox' => $approfile['inbox'], 'outbox' => $approfile['outbox'],
2191 'sharedinbox' => $approfile['endpoints']['sharedInbox'], 'network' => Protocol::DFRN,
2192 'pubkey' => $owner['upubkey'], 'baseurl' => $approfile['generator']['url'], 'gsid' => $owner['gsid'],
2193 'manually-approve' => in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])
2195 } catch (Exception $e) {
2196 // Default values for non existing targets
2198 'name' => $url, 'nick' => $url, 'url' => $url, 'network' => Protocol::PHANTOM,
2199 'photo' => DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO
2203 return self::rearrangeData($data);