3 * @copyright Copyright (C) 2010-2021, 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\HttpClientOptions;
38 use Friendica\Protocol\ActivityNamespace;
39 use Friendica\Protocol\ActivityPub;
40 use Friendica\Protocol\Email;
41 use Friendica\Protocol\Feed;
42 use Friendica\Util\Crypto;
43 use Friendica\Util\DateTimeFormat;
44 use Friendica\Util\Network;
45 use Friendica\Util\Strings;
46 use Friendica\Util\XML;
49 * This class contain functions for probing URL
53 const WEBFINGER = '/.well-known/webfinger?resource={uri}';
55 private static $baseurl;
56 private static $istimeout;
59 * Remove stuff from an URI that doesn't belong there
62 * @return string Cleaned URI
64 public static function cleanURI(string $URI)
66 // At first remove leading and trailing junk
67 $URI = trim($URI, "@#?:/ \t\n\r\0\x0B");
69 $parts = parse_url($URI);
71 if (empty($parts['scheme'])) {
75 // Remove the URL fragment, since these shouldn't be part of any profile URL
76 unset($parts['fragment']);
78 $URI = Network::unparseURL($parts);
84 * Rearrange the array so that it always has the same order
86 * @param array $data Unordered data
88 * @return array Ordered data
90 private static function rearrangeData($data)
92 $fields = ["name", "nick", "guid", "url", "addr", "alias", "photo", "header",
93 "account-type", "community", "keywords", "location", "about", "xmpp", "matrix",
94 "hide", "batch", "notify", "poll", "request", "confirm", "subscribe", "poco",
95 "following", "followers", "inbox", "outbox", "sharedinbox",
96 "priority", "network", "pubkey", "manually-approve", "baseurl", "gsid"];
98 $numeric_fields = ["gsid", "hide", "account-type", "manually-approve"];
101 foreach ($fields as $field) {
102 if (isset($data[$field])) {
103 if (in_array($field, $numeric_fields)) {
104 $newdata[$field] = (int)$data[$field];
106 $newdata[$field] = $data[$field];
108 } elseif (!in_array($field, $numeric_fields)) {
109 $newdata[$field] = "";
111 $newdata[$field] = null;
115 // We don't use the "priority" field anymore and replace it with a dummy.
116 $newdata["priority"] = 0;
122 * Check if the hostname belongs to the own server
124 * @param string $host The hostname that is to be checked
126 * @return bool Does the testes hostname belongs to the own server?
128 private static function ownHost($host)
130 $own_host = DI::baseUrl()->getHostname();
132 $parts = parse_url($host);
134 if (!isset($parts['scheme'])) {
135 $parts = parse_url('http://'.$host);
138 if (!isset($parts['host'])) {
141 return $parts['host'] == $own_host;
145 * Probes for webfinger path via "host-meta"
147 * We have to check if the servers in the future still will offer this.
148 * It seems as if it was dropped from the standard.
150 * @param string $host The host part of an url
152 * @return array with template and type of the webfinger template for JSON or XML
153 * @throws HTTPException\InternalServerErrorException
155 private static function hostMeta($host)
157 // Reset the static variable
160 // Handles the case when the hostname contains the scheme
161 if (!parse_url($host, PHP_URL_SCHEME)) {
162 $ssl_url = "https://" . $host . "/.well-known/host-meta";
163 $url = "http://" . $host . "/.well-known/host-meta";
165 $ssl_url = $host . "/.well-known/host-meta";
169 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
171 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
174 $curlResult = DI::httpClient()->get($ssl_url, [HttpClientOptions::TIMEOUT => $xrd_timeout, HttpClientOptions::ACCEPT_CONTENT => ['application/xrd+xml']]);
175 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
176 if ($curlResult->isSuccess()) {
177 $xml = $curlResult->getBody();
178 $xrd = XML::parseString($xml, true);
180 $host_url = 'https://' . $host;
184 } elseif ($curlResult->isTimeout()) {
185 Logger::info('Probing timeout', ['url' => $ssl_url]);
186 self::$istimeout = true;
190 if (!is_object($xrd) && !empty($url)) {
191 $curlResult = DI::httpClient()->get($url, [HttpClientOptions::TIMEOUT => $xrd_timeout, HttpClientOptions::ACCEPT_CONTENT => ['application/xrd+xml']]);
192 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
193 if ($curlResult->isTimeout()) {
194 Logger::info('Probing timeout', ['url' => $url]);
195 self::$istimeout = true;
197 } elseif ($connection_error && $ssl_connection_error) {
198 self::$istimeout = true;
202 $xml = $curlResult->getBody();
203 $xrd = XML::parseString($xml, true);
204 $host_url = 'http://'.$host;
206 if (!is_object($xrd)) {
207 Logger::info('No xrd object found', ['host' => $host]);
211 $links = XML::elementToArray($xrd);
212 if (!isset($links["xrd"]["link"])) {
213 Logger::info('No xrd data found', ['host' => $host]);
219 foreach ($links["xrd"]["link"] as $value => $link) {
220 if (!empty($link["@attributes"])) {
221 $attributes = $link["@attributes"];
222 } elseif ($value == "@attributes") {
228 if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
229 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
231 $lrdd[$type] = $attributes["template"];
235 if (Network::isUrlBlocked($host_url)) {
236 Logger::info('Domain is blocked', ['url' => $host]);
240 self::$baseurl = $host_url;
242 Logger::info('Probing successful', ['host' => $host]);
248 * Perform Webfinger lookup and return DFRN data
250 * Given an email style address, perform webfinger lookup and
251 * return the resulting DFRN profile URL, or if no DFRN profile URL
252 * is located, returns an OStatus subscription template (prefixed
253 * with the string 'stat:' to identify it as on OStatus template).
254 * If this isn't an email style address just return $webbie.
255 * Return an empty string if email-style addresses but webfinger fails,
256 * or if the resultant personal XRD doesn't contain a supported
257 * subscription/friend-request attribute.
259 * amended 7/9/2011 to return an hcard which could save potentially loading
260 * a lengthy content page to scrape dfrn attributes
262 * @param string $webbie Address that should be probed
263 * @param string $hcard_url Link to the hcard - is returned by reference
265 * @return string profile link
266 * @throws HTTPException\InternalServerErrorException
268 public static function webfingerDfrn(string $webbie, string &$hcard_url)
272 $links = self::lrdd($webbie);
273 Logger::debug('Result', ['url' => $webbie, 'links' => $links]);
274 if (!empty($links) && is_array($links)) {
275 foreach ($links as $link) {
276 if ($link['@attributes']['rel'] === ActivityNamespace::DFRN) {
277 $profile_link = $link['@attributes']['href'];
279 if (($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) && ($profile_link == "")) {
280 $profile_link = 'stat:'.$link['@attributes']['template'];
282 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
283 $hcard_url = $link['@attributes']['href'];
287 return $profile_link;
291 * Check an URI for LRDD data
293 * @param string $uri Address that should be probed
295 * @return array uri data
296 * @throws HTTPException\InternalServerErrorException
298 public static function lrdd(string $uri)
300 $data = self::getWebfingerArray($uri);
304 $webfinger = $data['webfinger'];
306 if (empty($webfinger["links"])) {
307 Logger::info('No webfinger links found', ['uri' => $uri]);
313 foreach ($webfinger["links"] as $link) {
314 $data[] = ["@attributes" => $link];
317 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
318 foreach ($webfinger["aliases"] as $alias) {
319 $data[] = ["@attributes" =>
329 * Fetch information (protocol endpoints and user information) about a given uri
331 * @param string $uri Address that should be probed
332 * @param string $network Test for this specific network
333 * @param integer $uid User ID for the probe (only used for mails)
334 * @param boolean $cache Use cached values?
336 * @return array uri data
337 * @throws HTTPException\InternalServerErrorException
338 * @throws \ImagickException
340 public static function uri($uri, $network = '', $uid = -1)
342 // Local profiles aren't probed via network
343 if (empty($network) && Contact::isLocal($uri)) {
344 $data = self::localProbe($uri);
354 if (empty($network) || ($network == Protocol::ACTIVITYPUB)) {
355 $ap_profile = ActivityPub::probeProfile($uri);
360 self::$istimeout = false;
362 if ($network != Protocol::ACTIVITYPUB) {
363 $data = self::detect($uri, $network, $uid, $ap_profile);
364 if (!is_array($data)) {
367 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
369 } elseif (!empty($ap_profile)) {
370 $ap_profile['batch'] = '';
371 $data = array_merge($ap_profile, $data);
377 if (!isset($data['url'])) {
381 if (empty($data['photo'])) {
382 $data['photo'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
385 if (empty($data['name'])) {
386 if (!empty($data['nick'])) {
387 $data['name'] = $data['nick'];
390 if (empty($data['name'])) {
391 $data['name'] = $data['url'];
395 if (empty($data['nick'])) {
396 $data['nick'] = strtolower($data['name']);
398 if (strpos($data['nick'], ' ')) {
399 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
403 if (!empty($data['baseurl']) && empty($data['gsid'])) {
404 $data['gsid'] = GServer::getID($data['baseurl']);
407 if (empty($data['network'])) {
408 $data['network'] = Protocol::PHANTOM;
411 // Ensure that local connections always are DFRN
412 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
413 $data['network'] = Protocol::DFRN;
416 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
417 $data['hide'] = self::getHideStatus($data['url']);
420 return self::rearrangeData($data);
425 * Fetches the "hide" status from the profile
427 * @param string $url URL of the profile
429 * @return boolean "hide" status
431 private static function getHideStatus($url)
433 $curlResult = DI::httpClient()->get($url, [HttpClientOptions::CONTENT_LENGTH => 1000000]);
434 if (!$curlResult->isSuccess()) {
438 // If it isn't a HTML file then exit
439 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
443 $body = $curlResult->getBody();
448 $doc = new DOMDocument();
449 @$doc->loadHTML($body);
451 $xpath = new DOMXPath($doc);
453 $list = $xpath->query('//meta[@name]');
454 foreach ($list as $node) {
456 if ($node->attributes->length) {
457 foreach ($node->attributes as $attribute) {
458 $meta_tag[$attribute->name] = $attribute->value;
462 if (empty($meta_tag['content'])) {
466 $content = strtolower(trim($meta_tag['content']));
468 switch (strtolower(trim($meta_tag['name']))) {
469 case 'dfrn-global-visibility':
470 if ($content == 'false') {
475 if (strpos($content, 'noindex') !== false) {
486 * Fetch the "subscribe" and add it to the result
488 * @param array $result
489 * @param array $webfinger
490 * @return array result
492 private static function getSubscribeLink(array $result, array $webfinger)
494 if (empty($webfinger['links'])) {
498 foreach ($webfinger['links'] as $link) {
499 if (!empty($link['template']) && ($link['rel'] === ActivityNamespace::OSTATUSSUB)) {
500 $result['subscribe'] = $link['template'];
508 * Get webfinger data from a given URI
512 * @throws HTTPException\InternalServerErrorException
514 private static function getWebfingerArray(string $uri): array
516 $parts = parse_url($uri);
518 if (!empty($parts['scheme']) && !empty($parts['host'])) {
519 $host = $parts['host'];
520 if (!empty($parts['port'])) {
521 $host .= ':' . $parts['port'];
524 $baseurl = $parts['scheme'] . '://' . $host;
529 $path_parts = explode('/', trim($parts['path'] ?? '', '/'));
530 if (!empty($path_parts)) {
531 $nick = ltrim(end($path_parts), '@');
532 $addr = $nick . '@' . $host;
535 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
536 if (empty($webfinger)) {
537 $lrdd = self::hostMeta($host);
540 if (empty($webfinger) && empty($lrdd)) {
541 while (empty($lrdd) && empty($webfinger) && (sizeof($path_parts) > 1)) {
542 $host .= '/' . array_shift($path_parts);
543 $baseurl = $parts['scheme'] . '://' . $host;
546 $addr = $nick . '@' . $host;
549 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
550 if (empty($webfinger)) {
551 $lrdd = self::hostMeta($host);
555 if (empty($lrdd) && empty($webfinger)) {
559 } elseif (strstr($uri, '@')) {
560 // Remove "acct:" from the URI
561 $uri = str_replace('acct:', '', $uri);
563 $host = substr($uri, strpos($uri, '@') + 1);
564 $nick = substr($uri, 0, strpos($uri, '@'));
567 $webfinger = self::getWebfinger('https://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
568 if (self::$istimeout) {
572 if (empty($webfinger)) {
573 $webfinger = self::getWebfinger('http://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
574 if (self::$istimeout) {
578 $baseurl = 'https://' . $host;
581 if (empty($webfinger)) {
582 $lrdd = self::hostMeta($host);
583 if (self::$istimeout) {
586 $baseurl = self::$baseurl;
588 $baseurl = 'http://' . $host;
591 Logger::info('URI was not detectable', ['uri' => $uri]);
595 if (empty($webfinger)) {
596 foreach ($lrdd as $type => $template) {
601 $webfinger = self::getWebfinger($template, $type, $uri, $addr);
605 if (empty($webfinger)) {
609 if ($webfinger['detected'] == $addr) {
610 $webfinger['nick'] = $nick;
611 $webfinger['addr'] = $addr;
614 $webfinger['baseurl'] = $baseurl;
620 * Perform network request for webfinger data
622 * @param string $template
623 * @param string $type
625 * @param string $addr
626 * @return array webfinger results
628 private static function getWebfinger(string $template, string $type, string $uri, string $addr)
630 if (Network::isUrlBlocked($template)) {
631 Logger::info('Domain is blocked', ['url' => $template]);
635 // First try the address because this is the primary purpose of webfinger
638 $path = str_replace('{uri}', urlencode("acct:" . $addr), $template);
639 $webfinger = self::webfinger($path, $type);
640 if (self::$istimeout) {
646 if (empty($webfinger) && $uri != $addr) {
648 $path = str_replace('{uri}', urlencode($uri), $template);
649 $webfinger = self::webfinger($path, $type);
650 if (self::$istimeout) {
655 if (empty($webfinger)) {
659 return ['webfinger' => $webfinger, 'detected' => $detected];
663 * Fetch information (protocol endpoints and user information) about a given uri
665 * This function is only called by the "uri" function that adds caching and rearranging of data.
667 * @param string $uri Address that should be probed
668 * @param string $network Test for this specific network
669 * @param integer $uid User ID for the probe (only used for mails)
670 * @param array $ap_profile Previously probed AP profile
672 * @return array uri data
673 * @throws HTTPException\InternalServerErrorException
675 private static function detect(string $uri, string $network, int $uid, array $ap_profile)
679 'network' => $network,
684 Hook::callAll('probe_detect', $hookData);
686 if (isset($hookData['result'])) {
687 return is_array($hookData['result']) ? $hookData['result'] : [];
690 $parts = parse_url($uri);
692 if (empty($parts['scheme']) || !empty($parts['host']) && strstr($uri, '@')) {
693 // If the URI starts with "mailto:" then jump directly to the mail detection
694 if (strpos($uri, 'mailto:') !== false) {
695 $uri = str_replace('mailto:', '', $uri);
696 return self::mail($uri, $uid);
699 if ($network == Protocol::MAIL) {
700 return self::mail($uri, $uid);
703 Logger::info('URI was not detectable', ['uri' => $uri]);
707 Logger::info('Probing start', ['uri' => $uri]);
709 if (!empty($ap_profile['addr']) && ($ap_profile['addr'] != $uri)) {
710 $data = self::getWebfingerArray($ap_profile['addr']);
714 $data = self::getWebfingerArray($uri);
718 if (!empty($parts['scheme'])) {
719 return self::feed($uri);
720 } elseif (!empty($uid)) {
721 return self::mail($uri, $uid);
727 $webfinger = $data['webfinger'];
728 $nick = $data['nick'] ?? '';
729 $addr = $data['addr'] ?? '';
730 $baseurl = $data['baseurl'] ?? '';
734 if (in_array($network, ["", Protocol::DFRN])) {
735 $result = self::dfrn($webfinger);
737 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
738 $result = self::diaspora($webfinger);
740 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
741 $result = self::ostatus($webfinger);
743 if (in_array($network, ['', Protocol::ZOT])) {
744 $result = self::zot($webfinger, $result, $baseurl);
746 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
747 $result = self::pumpio($webfinger, $addr);
749 if (empty($result['network']) && empty($ap_profile['network']) || ($network == Protocol::FEED)) {
750 $result = self::feed($uri);
752 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
753 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
754 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
755 $result["nick"] = $nick;
758 if (empty($result["addr"]) && ($addr != "")) {
759 $result["addr"] = $addr;
763 $result = self::getSubscribeLink($result, $webfinger);
765 if (empty($result["network"])) {
766 $result["network"] = Protocol::PHANTOM;
769 if (empty($result['baseurl']) && !empty($baseurl)) {
770 $result['baseurl'] = $baseurl;
773 if (empty($result["url"])) {
774 $result["url"] = $uri;
777 Logger::info('Probing done', ['uri' => $uri, 'network' => $result["network"]]);
783 * Check for Zot contact
785 * @param array $webfinger Webfinger data
786 * @param array $data previously probed data
788 * @return array Zot data
789 * @throws HTTPException\InternalServerErrorException
791 private static function zot($webfinger, $data, $baseurl)
793 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
794 foreach ($webfinger["aliases"] as $alias) {
795 if (substr($alias, 0, 5) == 'acct:') {
796 $data["addr"] = substr($alias, 5);
801 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
802 $data["addr"] = substr($webfinger["subject"], 5);
806 foreach ($webfinger['links'] as $link) {
807 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
808 $zot_url = $link['href'];
812 if (empty($zot_url) && !empty($data['addr']) && !empty($baseurl)) {
813 $condition = ['nurl' => Strings::normaliseLink($baseurl), 'platform' => ['hubzilla']];
814 if (!DBA::exists('gserver', $condition)) {
817 $zot_url = $baseurl . '/.well-known/zot-info?address=' . $data['addr'];
820 if (empty($zot_url)) {
824 $data = self::pollZot($zot_url, $data);
826 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
827 foreach ($webfinger['aliases'] as $alias) {
828 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
829 $data['alias'] = $alias;
837 public static function pollZot($url, $data)
839 $curlResult = DI::httpClient()->get($url);
840 if ($curlResult->isTimeout()) {
843 $content = $curlResult->getBody();
848 $json = json_decode($content, true);
849 if (!is_array($json)) {
853 if (empty($data['network'])) {
854 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
855 $data['network'] = Protocol::ZOT;
856 } elseif (!isset($json['protocols'])) {
857 $data['network'] = Protocol::ZOT;
861 if (!empty($json['guid']) && empty($data['guid'])) {
862 $data['guid'] = $json['guid'];
864 if (!empty($json['key']) && empty($data['pubkey'])) {
865 $data['pubkey'] = $json['key'];
867 if (!empty($json['name'])) {
868 $data['name'] = $json['name'];
870 if (!empty($json['photo'])) {
871 $data['photo'] = $json['photo'];
872 if (!empty($json['photo_updated'])) {
873 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
876 if (!empty($json['address'])) {
877 $data['addr'] = $json['address'];
879 if (!empty($json['url'])) {
880 $data['url'] = $json['url'];
882 if (!empty($json['connections_url'])) {
883 $data['poco'] = $json['connections_url'];
885 if (isset($json['searchable'])) {
886 $data['hide'] = !$json['searchable'];
888 if (!empty($json['public_forum'])) {
889 $data['community'] = $json['public_forum'];
890 $data['account-type'] = User::PAGE_FLAGS_COMMUNITY;
893 if (!empty($json['profile'])) {
894 $profile = $json['profile'];
895 if (!empty($profile['description'])) {
896 $data['about'] = $profile['description'];
898 if (!empty($profile['keywords'])) {
899 $keywords = implode(', ', $profile['keywords']);
900 if (!empty($keywords)) {
901 $data['keywords'] = $keywords;
906 if (!empty($profile['region'])) {
907 $loc['region'] = $profile['region'];
909 if (!empty($profile['country'])) {
910 $loc['country-name'] = $profile['country'];
912 $location = Profile::formatLocation($loc);
913 if (!empty($location)) {
914 $data['location'] = $location;
922 * Perform a webfinger request.
924 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
926 * @param string $url Address that should be probed
927 * @param string $type type
929 * @return array webfinger data
930 * @throws HTTPException\InternalServerErrorException
932 public static function webfinger($url, $type)
934 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
936 $curlResult = DI::httpClient()->get($url, [HttpClientOptions::TIMEOUT => $xrd_timeout, HttpClientOptions::ACCEPT_CONTENT => [$type]]);
937 if ($curlResult->isTimeout()) {
938 self::$istimeout = true;
941 $data = $curlResult->getBody();
943 $webfinger = json_decode($data, true);
944 if (!empty($webfinger)) {
945 if (!isset($webfinger["links"])) {
946 Logger::info('No json webfinger links', ['url' => $url]);
952 // If it is not JSON, maybe it is XML
953 $xrd = XML::parseString($data, true);
954 if (!is_object($xrd)) {
955 Logger::info('No webfinger data retrievable', ['url' => $url]);
959 $xrd_arr = XML::elementToArray($xrd);
960 if (!isset($xrd_arr["xrd"]["link"])) {
961 Logger::info('No XML webfinger links', ['url' => $url]);
967 if (!empty($xrd_arr["xrd"]["subject"])) {
968 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
971 if (!empty($xrd_arr["xrd"]["alias"])) {
972 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
975 $webfinger["links"] = [];
977 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
978 if (!empty($data["@attributes"])) {
979 $attributes = $data["@attributes"];
980 } elseif ($value == "@attributes") {
986 $webfinger["links"][] = $attributes;
992 * Poll the Friendica specific noscrape page.
994 * "noscrape" is a faster alternative to fetch the data from the hcard.
995 * This functionality was originally created for the directory.
997 * @param string $noscrape_url Link to the noscrape page
998 * @param array $data The already fetched data
1000 * @return array noscrape data
1001 * @throws HTTPException\InternalServerErrorException
1003 private static function pollNoscrape($noscrape_url, $data)
1005 $curlResult = DI::httpClient()->get($noscrape_url);
1006 if ($curlResult->isTimeout()) {
1007 self::$istimeout = true;
1010 $content = $curlResult->getBody();
1012 Logger::info('Empty body', ['url' => $noscrape_url]);
1016 $json = json_decode($content, true);
1017 if (!is_array($json)) {
1018 Logger::info('No json data', ['url' => $noscrape_url]);
1022 if (!empty($json["fn"])) {
1023 $data["name"] = $json["fn"];
1026 if (!empty($json["addr"])) {
1027 $data["addr"] = $json["addr"];
1030 if (!empty($json["nick"])) {
1031 $data["nick"] = $json["nick"];
1034 if (!empty($json["guid"])) {
1035 $data["guid"] = $json["guid"];
1038 if (!empty($json["comm"])) {
1039 $data["community"] = $json["comm"];
1042 if (!empty($json["tags"])) {
1043 $keywords = implode(", ", $json["tags"]);
1044 if ($keywords != "") {
1045 $data["keywords"] = $keywords;
1049 $location = Profile::formatLocation($json);
1051 $data["location"] = $location;
1054 if (!empty($json["about"])) {
1055 $data["about"] = $json["about"];
1058 if (!empty($json["xmpp"])) {
1059 $data["xmpp"] = $json["xmpp"];
1062 if (!empty($json["matrix"])) {
1063 $data["matrix"] = $json["matrix"];
1066 if (!empty($json["key"])) {
1067 $data["pubkey"] = $json["key"];
1070 if (!empty($json["photo"])) {
1071 $data["photo"] = $json["photo"];
1074 if (!empty($json["dfrn-request"])) {
1075 $data["request"] = $json["dfrn-request"];
1078 if (!empty($json["dfrn-confirm"])) {
1079 $data["confirm"] = $json["dfrn-confirm"];
1082 if (!empty($json["dfrn-notify"])) {
1083 $data["notify"] = $json["dfrn-notify"];
1086 if (!empty($json["dfrn-poll"])) {
1087 $data["poll"] = $json["dfrn-poll"];
1090 if (isset($json["hide"])) {
1091 $data["hide"] = (bool)$json["hide"];
1093 $data["hide"] = false;
1100 * Check for valid DFRN data
1102 * @param array $data DFRN data
1104 * @return int Number of errors
1106 public static function validDfrn($data)
1109 if (!isset($data['key'])) {
1112 if (!isset($data['dfrn-request'])) {
1115 if (!isset($data['dfrn-confirm'])) {
1118 if (!isset($data['dfrn-notify'])) {
1121 if (!isset($data['dfrn-poll'])) {
1128 * Fetch data from a DFRN profile page and via "noscrape"
1130 * @param string $profile_link Link to the profile page
1132 * @return array profile data
1133 * @throws HTTPException\InternalServerErrorException
1134 * @throws \ImagickException
1136 public static function profile($profile_link)
1140 Logger::info('Check profile', ['link' => $profile_link]);
1142 // Fetch data via noscrape - this is faster
1143 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1144 $data = self::pollNoscrape($noscrape_url, $data);
1146 if (!isset($data["notify"])
1147 || !isset($data["confirm"])
1148 || !isset($data["request"])
1149 || !isset($data["poll"])
1150 || !isset($data["name"])
1151 || !isset($data["photo"])
1153 $data = self::pollHcard($profile_link, $data, true);
1158 if (empty($data["addr"]) || empty($data["nick"])) {
1159 $probe_data = self::uri($profile_link);
1160 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1161 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1164 $prof_data["addr"] = $data["addr"];
1165 $prof_data["nick"] = $data["nick"];
1166 $prof_data["dfrn-request"] = $data['request'] ?? null;
1167 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1168 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1169 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1170 $prof_data["photo"] = $data['photo'] ?? null;
1171 $prof_data["fn"] = $data['name'] ?? null;
1172 $prof_data["key"] = $data['pubkey'] ?? null;
1174 Logger::debug('Result', ['link' => $profile_link, 'data' => $prof_data]);
1180 * Check for DFRN contact
1182 * @param array $webfinger Webfinger data
1184 * @return array DFRN data
1185 * @throws HTTPException\InternalServerErrorException
1187 private static function dfrn($webfinger)
1191 // The array is reversed to take into account the order of preference for same-rel links
1192 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1193 foreach (array_reverse($webfinger["links"]) as $link) {
1194 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1195 $data["network"] = Protocol::DFRN;
1196 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1197 $data["poll"] = $link["href"];
1198 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1199 $data["url"] = $link["href"];
1200 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1201 $hcard_url = $link["href"];
1202 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1203 $data["poco"] = $link["href"];
1204 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1205 $data["photo"] = $link["href"];
1206 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1207 $data["baseurl"] = trim($link["href"], '/');
1208 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1209 $data["guid"] = $link["href"];
1210 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1211 $data["pubkey"] = base64_decode($link["href"]);
1213 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1214 if (strstr($data["pubkey"], 'RSA ')) {
1215 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1220 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1221 foreach ($webfinger["aliases"] as $alias) {
1222 if (empty($data["url"]) && !strstr($alias, "@")) {
1223 $data["url"] = $alias;
1224 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1225 $data["alias"] = $alias;
1226 } elseif (substr($alias, 0, 5) == 'acct:') {
1227 $data["addr"] = substr($alias, 5);
1232 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1233 $data["addr"] = substr($webfinger["subject"], 5);
1236 if (!isset($data["network"]) || ($hcard_url == "")) {
1240 // Fetch data via noscrape - this is faster
1241 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1242 $data = self::pollNoscrape($noscrape_url, $data);
1244 if (isset($data["notify"])
1245 && isset($data["confirm"])
1246 && isset($data["request"])
1247 && isset($data["poll"])
1248 && isset($data["name"])
1249 && isset($data["photo"])
1254 $data = self::pollHcard($hcard_url, $data, true);
1260 * Poll the hcard page (Diaspora and Friendica specific)
1262 * @param string $hcard_url Link to the hcard page
1263 * @param array $data The already fetched data
1264 * @param boolean $dfrn Poll DFRN specific data
1266 * @return array hcard data
1267 * @throws HTTPException\InternalServerErrorException
1269 private static function pollHcard($hcard_url, $data, $dfrn = false)
1271 $curlResult = DI::httpClient()->get($hcard_url);
1272 if ($curlResult->isTimeout()) {
1273 self::$istimeout = true;
1276 $content = $curlResult->getBody();
1277 if (empty($content)) {
1281 $doc = new DOMDocument();
1282 if (!@$doc->loadHTML($content)) {
1286 $xpath = new DomXPath($doc);
1288 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1289 if (!is_object($vcards)) {
1293 if (!isset($data["baseurl"])) {
1294 $data["baseurl"] = "";
1297 if ($vcards->length > 0) {
1298 $vcard = $vcards->item(0);
1300 // We have to discard the guid from the hcard in favour of the guid from lrdd
1301 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1302 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1303 if (($search->length > 0) && empty($data["guid"])) {
1304 $data["guid"] = $search->item(0)->nodeValue;
1307 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1308 if ($search->length > 0) {
1309 $data["nick"] = $search->item(0)->nodeValue;
1312 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1313 if ($search->length > 0) {
1314 $data["name"] = $search->item(0)->nodeValue;
1317 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1318 if ($search->length > 0) {
1319 $data["searchable"] = $search->item(0)->nodeValue;
1322 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1323 if ($search->length > 0) {
1324 $data["pubkey"] = $search->item(0)->nodeValue;
1325 if (strstr($data["pubkey"], 'RSA ')) {
1326 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1330 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1331 if ($search->length > 0) {
1332 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1337 if (!empty($vcard)) {
1338 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1339 foreach ($photos as $photo) {
1341 foreach ($photo->attributes as $attribute) {
1342 $attr[$attribute->name] = trim($attribute->value);
1345 if (isset($attr["src"]) && isset($attr["width"])) {
1346 $avatar[$attr["width"]] = $attr["src"];
1349 // We don't have a width. So we just take everything that we got.
1350 // This is a Hubzilla workaround which doesn't send a width.
1351 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1352 $avatar[] = $attr["src"];
1357 if (sizeof($avatar)) {
1359 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1363 // Poll DFRN specific data
1364 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1365 if ($search->length > 0) {
1366 foreach ($search as $link) {
1367 //$data["request"] = $search->item(0)->nodeValue;
1369 foreach ($link->attributes as $attribute) {
1370 $attr[$attribute->name] = trim($attribute->value);
1373 $data[substr($attr["rel"], 5)] = $attr["href"];
1377 // Older Friendica versions had used the "uid" field differently than newer versions
1378 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1379 unset($data["guid"]);
1388 * Check for Diaspora contact
1390 * @param array $webfinger Webfinger data
1392 * @return array Diaspora data
1393 * @throws HTTPException\InternalServerErrorException
1395 private static function diaspora($webfinger)
1400 // The array is reversed to take into account the order of preference for same-rel links
1401 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1402 foreach (array_reverse($webfinger["links"]) as $link) {
1403 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1404 $hcard_url = $link["href"];
1405 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1406 $data["baseurl"] = trim($link["href"], '/');
1407 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1408 $data["guid"] = $link["href"];
1409 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1410 $data["url"] = $link["href"];
1411 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && empty($link["type"]) && !empty($link["href"])) {
1412 $profile_url = $link["href"];
1413 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1414 $data["poll"] = $link["href"];
1415 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1416 $data["poco"] = $link["href"];
1417 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1418 $data["notify"] = $link["href"];
1419 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1420 $data["pubkey"] = base64_decode($link["href"]);
1422 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1423 if (strstr($data["pubkey"], 'RSA ')) {
1424 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1429 if (empty($data["url"]) && !empty($profile_url)) {
1430 $data["url"] = $profile_url;
1433 if (empty($data["url"]) || empty($hcard_url)) {
1437 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1438 foreach ($webfinger["aliases"] as $alias) {
1439 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1440 $data["alias"] = $alias;
1441 } elseif (substr($alias, 0, 5) == 'acct:') {
1442 $data["addr"] = substr($alias, 5);
1447 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1448 $data["addr"] = substr($webfinger["subject"], 5);
1451 // Fetch further information from the hcard
1452 $data = self::pollHcard($hcard_url, $data);
1458 if (!empty($data["url"])
1459 && !empty($data["guid"])
1460 && !empty($data["baseurl"])
1461 && !empty($data["pubkey"])
1462 && !empty($hcard_url)
1464 $data["network"] = Protocol::DIASPORA;
1465 $data["manually-approve"] = false;
1467 // The Diaspora handle must always be lowercase
1468 if (!empty($data["addr"])) {
1469 $data["addr"] = strtolower($data["addr"]);
1472 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1473 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1474 $data["batch"] = $data["baseurl"] . "/receive/public";
1483 * Check for OStatus contact
1485 * @param array $webfinger Webfinger data
1486 * @param bool $short Short detection mode
1488 * @return array|bool OStatus data or "false" on error or "true" on short mode
1489 * @throws HTTPException\InternalServerErrorException
1491 private static function ostatus($webfinger, $short = false)
1495 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1496 foreach ($webfinger["aliases"] as $alias) {
1497 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1498 $data["addr"] = str_replace('acct:', '', $alias);
1503 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1504 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1506 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1509 if (!empty($webfinger["links"])) {
1510 // The array is reversed to take into account the order of preference for same-rel links
1511 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1512 foreach (array_reverse($webfinger["links"]) as $link) {
1513 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1514 && (($link["type"] ?? "") == "text/html")
1515 && ($link["href"] != "")
1517 $data["url"] = $data["alias"] = $link["href"];
1518 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1519 $data["notify"] = $link["href"];
1520 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1521 $data["poll"] = $link["href"];
1522 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1523 $pubkey = $link["href"];
1525 if (substr($pubkey, 0, 5) === 'data:') {
1526 if (strstr($pubkey, ',')) {
1527 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1529 $pubkey = substr($pubkey, 5);
1531 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1532 $curlResult = DI::httpClient()->get($pubkey);
1533 if ($curlResult->isTimeout()) {
1534 self::$istimeout = true;
1535 return $short ? false : [];
1537 $pubkey = $curlResult->getBody();
1540 $key = explode(".", $pubkey);
1542 if (sizeof($key) >= 3) {
1543 $m = Strings::base64UrlDecode($key[1]);
1544 $e = Strings::base64UrlDecode($key[2]);
1545 $data["pubkey"] = Crypto::meToPem($m, $e);
1551 if (isset($data["notify"]) && isset($data["pubkey"])
1552 && isset($data["poll"])
1553 && isset($data["url"])
1555 $data["network"] = Protocol::OSTATUS;
1556 $data["manually-approve"] = false;
1558 return $short ? false : [];
1565 // Fetch all additional data from the feed
1566 $curlResult = DI::httpClient()->get($data["poll"]);
1567 if ($curlResult->isTimeout()) {
1568 self::$istimeout = true;
1571 $feed = $curlResult->getBody();
1572 $feed_data = Feed::import($feed);
1577 if (!empty($feed_data["header"]["author-name"])) {
1578 $data["name"] = $feed_data["header"]["author-name"];
1580 if (!empty($feed_data["header"]["author-nick"])) {
1581 $data["nick"] = $feed_data["header"]["author-nick"];
1583 if (!empty($feed_data["header"]["author-avatar"])) {
1584 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1586 if (!empty($feed_data["header"]["author-id"])) {
1587 $data["alias"] = $feed_data["header"]["author-id"];
1589 if (!empty($feed_data["header"]["author-location"])) {
1590 $data["location"] = $feed_data["header"]["author-location"];
1592 if (!empty($feed_data["header"]["author-about"])) {
1593 $data["about"] = $feed_data["header"]["author-about"];
1595 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1596 // So we take the value that we just fetched, although the other one worked as well
1597 if (!empty($feed_data["header"]["author-link"])) {
1598 $data["url"] = $feed_data["header"]["author-link"];
1601 if ($data["url"] == $data["alias"]) {
1602 $data["alias"] = '';
1605 /// @todo Fetch location and "about" from the feed as well
1610 * Fetch data from a pump.io profile page
1612 * @param string $profile_link Link to the profile page
1614 * @return array profile data
1616 private static function pumpioProfileData($profile_link)
1618 $curlResult = DI::httpClient()->get($profile_link);
1619 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
1623 $doc = new DOMDocument();
1624 if (!@$doc->loadHTML($curlResult->getBody())) {
1628 $xpath = new DomXPath($doc);
1632 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1634 if ($data["name"] == '') {
1635 // This is ugly - but pump.io doesn't seem to know a better way for it
1636 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1637 $pos = strpos($data["name"], chr(10));
1639 $data["name"] = trim(substr($data["name"], 0, $pos));
1643 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1645 if ($data["location"] == '') {
1646 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1649 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1651 if ($data["about"] == '') {
1652 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1655 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1657 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1660 foreach ($avatar->attributes as $attribute) {
1661 if ($attribute->name == "src") {
1662 $data["photo"] = trim($attribute->value);
1671 * Check for pump.io contact
1673 * @param array $webfinger Webfinger data
1674 * @param string $addr
1675 * @return array pump.io data
1677 private static function pumpio($webfinger, $addr)
1680 // The array is reversed to take into account the order of preference for same-rel links
1681 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1682 foreach (array_reverse($webfinger["links"]) as $link) {
1683 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1684 && (($link["type"] ?? "") == "text/html")
1685 && ($link["href"] != "")
1687 $data["url"] = $link["href"];
1688 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1689 $data["notify"] = $link["href"];
1690 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1691 $data["poll"] = $link["href"];
1692 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1693 $data["dialback"] = $link["href"];
1696 if (isset($data["poll"]) && isset($data["notify"])
1697 && isset($data["dialback"])
1698 && isset($data["url"])
1700 // by now we use these fields only for the network type detection
1701 // So we unset all data that isn't used at the moment
1702 unset($data["dialback"]);
1704 $data["network"] = Protocol::PUMPIO;
1709 $profile_data = self::pumpioProfileData($data["url"]);
1711 if (!$profile_data) {
1715 $data = array_merge($data, $profile_data);
1717 if (($addr != '') && ($data['name'] != '')) {
1718 $name = trim(str_replace($addr, '', $data['name']));
1720 $data['name'] = $name;
1728 * Checks HTML page for RSS feed link
1730 * @param string $url Page link
1731 * @param string $body Page body string
1732 * @return string|false Feed link or false if body was invalid HTML document
1734 public static function getFeedLink(string $url, string $body)
1740 $doc = new DOMDocument();
1741 if (!@$doc->loadHTML($body)) {
1745 $xpath = new DOMXPath($doc);
1747 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1749 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1755 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1757 * Loosely based on RFC 1808
1759 * @see https://tools.ietf.org/html/rfc1808
1761 * @param string $href The potential relative href found in the HTML document
1762 * @param string $base The HTML document URL
1763 * @param DOMXPath $xpath The HTML document XPath
1766 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath)
1768 if (filter_var($href, FILTER_VALIDATE_URL)) {
1772 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1774 $baseParts = parse_url($base);
1775 if (empty($baseParts['host'])) {
1779 // Naked domain case (scheme://basehost)
1780 $path = $baseParts['path'] ?? '/';
1782 // Remove the filename part of the path if it exists (/base/path/file)
1783 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1785 $hrefParts = parse_url($href);
1787 if (!empty($hrefParts['path'])) {
1788 // Root path case (/path) including relative scheme case (//host/path)
1789 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1790 $path = $hrefParts['path'];
1792 $path = $path . '/' . $hrefParts['path'];
1794 // Resolve arbitrary relative path
1795 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1796 $parts = array_filter(explode('/', $path), 'strlen');
1797 $absolutes = array();
1798 foreach ($parts as $part) {
1799 if ('.' == $part) continue;
1800 if ('..' == $part) {
1801 array_pop($absolutes);
1803 $absolutes[] = $part;
1807 $path = '/' . implode('/', $absolutes);
1811 // Relative scheme case (//host/path)
1812 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1813 $baseParts['path'] = $path;
1814 unset($baseParts['query']);
1815 unset($baseParts['fragment']);
1817 return Network::unparseURL($baseParts);
1821 * Check for feed contact
1823 * @param string $url Profile link
1824 * @param boolean $probe Do a probe if the page contains a feed link
1826 * @return array feed data
1827 * @throws HTTPException\InternalServerErrorException
1829 private static function feed($url, $probe = true)
1831 $curlResult = DI::httpClient()->get($url);
1832 if ($curlResult->isTimeout()) {
1833 self::$istimeout = true;
1836 $feed = $curlResult->getBody();
1837 $feed_data = Feed::import($feed);
1844 $feed_url = self::getFeedLink($url, $feed);
1850 return self::feed($feed_url, false);
1853 if (!empty($feed_data["header"]["author-name"])) {
1854 $data["name"] = $feed_data["header"]["author-name"];
1857 if (!empty($feed_data["header"]["author-nick"])) {
1858 $data["nick"] = $feed_data["header"]["author-nick"];
1861 if (!empty($feed_data["header"]["author-avatar"])) {
1862 $data["photo"] = $feed_data["header"]["author-avatar"];
1865 if (!empty($feed_data["header"]["author-id"])) {
1866 $data["alias"] = $feed_data["header"]["author-id"];
1869 $data["url"] = $url;
1870 $data["poll"] = $url;
1872 $data["network"] = Protocol::FEED;
1878 * Check for mail contact
1880 * @param string $uri Profile link
1881 * @param integer $uid User ID
1883 * @return array mail data
1884 * @throws \Exception
1886 private static function mail($uri, $uid)
1888 if (!Network::isEmailDomainValid($uri)) {
1896 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1898 $condition = ["`uid` = ? AND `server` != ''", $uid];
1899 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1900 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1902 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1906 $mailbox = Email::constructMailboxName($mailacct);
1908 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1909 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1914 $msgs = Email::poll($mbox, $uri);
1915 Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
1917 if (!count($msgs)) {
1921 $phost = substr($uri, strpos($uri, '@') + 1);
1924 $data["addr"] = $uri;
1925 $data["network"] = Protocol::MAIL;
1926 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1927 $data["nick"] = $data["name"];
1928 $data["photo"] = Network::lookupAvatarByEmail($uri);
1929 $data["url"] = 'mailto:'.$uri;
1930 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1931 $data["poll"] = 'email ' . Strings::getRandomHex();
1933 $x = Email::messageMeta($mbox, $msgs[0]);
1934 if (stristr($x[0]->from, $uri)) {
1935 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1936 } elseif (stristr($x[0]->to, $uri)) {
1937 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1940 foreach ($adr as $feadr) {
1941 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1942 &&(strcasecmp($feadr->host, $phost) == 0)
1943 && (strlen($feadr->personal))
1945 $personal = imap_mime_header_decode($feadr->personal);
1947 foreach ($personal as $perspart) {
1948 if ($perspart->charset != "default") {
1949 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1951 $data["name"] .= $perspart->text;
1957 if (!empty($mbox)) {
1964 * Mix two paths together to possibly fix missing parts
1966 * @param string $avatar Path to the avatar
1967 * @param string $base Another path that is hopefully complete
1969 * @return string fixed avatar path
1970 * @throws \Exception
1972 public static function fixAvatar($avatar, $base)
1974 $base_parts = parse_url($base);
1976 // Remove all parts that could create a problem
1977 unset($base_parts['path']);
1978 unset($base_parts['query']);
1979 unset($base_parts['fragment']);
1981 $avatar_parts = parse_url($avatar);
1984 $parts = array_merge($base_parts, $avatar_parts);
1986 // And put them together again
1987 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1988 $host = isset($parts['host']) ? $parts['host'] : '';
1989 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1990 $path = isset($parts['path']) ? $parts['path'] : '';
1991 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1992 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1994 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1996 Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
2002 * Fetch the last date that the contact had posted something (publically)
2004 * @param string $data probing result
2005 * @return string last activity
2007 public static function getLastUpdate(array $data)
2009 $uid = User::getIdForURL($data['url']);
2011 $contact = Contact::selectFirst(['url', 'last-item'], ['self' => true, 'uid' => $uid]);
2012 if (!empty($contact['last-item'])) {
2013 return $contact['last-item'];
2017 if ($lastUpdate = self::updateFromNoScrape($data)) {
2021 if (!empty($data['outbox'])) {
2022 return self::updateFromOutbox($data['outbox'], $data);
2023 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
2024 return self::updateFromOutbox($data['poll'], $data);
2025 } elseif (!empty($data['poll'])) {
2026 return self::updateFromFeed($data);
2033 * Fetch the last activity date from the "noscrape" endpoint
2035 * @param array $data Probing result
2036 * @return string last activity
2038 * @return bool 'true' if update was successful or the server was unreachable
2040 private static function updateFromNoScrape(array $data)
2042 if (empty($data['baseurl'])) {
2046 // Check the 'noscrape' endpoint when it is a Friendica server
2047 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
2048 Strings::normaliseLink($data['baseurl'])]);
2049 if (!DBA::isResult($gserver)) {
2053 $curlResult = DI::httpClient()->get($gserver['noscrape'] . '/' . $data['nick']);
2055 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
2056 $noscrape = json_decode($curlResult->getBody(), true);
2057 if (!empty($noscrape) && !empty($noscrape['updated'])) {
2058 return DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2066 * Fetch the last activity date from an ActivityPub Outbox
2068 * @param string $feed
2069 * @param array $data Probing result
2070 * @return string last activity
2071 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2073 private static function updateFromOutbox(string $feed, array $data)
2075 $outbox = ActivityPub::fetchContent($feed);
2076 if (empty($outbox)) {
2080 if (!empty($outbox['orderedItems'])) {
2081 $items = $outbox['orderedItems'];
2082 } elseif (!empty($outbox['first']['orderedItems'])) {
2083 $items = $outbox['first']['orderedItems'];
2084 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2085 return self::updateFromOutbox($outbox['first']['href'], $data);
2086 } elseif (!empty($outbox['first'])) {
2087 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2088 return self::updateFromOutbox($outbox['first'], $data);
2090 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2098 foreach ($items as $activity) {
2099 if (!empty($activity['published'])) {
2100 $published = DateTimeFormat::utc($activity['published']);
2101 } elseif (!empty($activity['object']['published'])) {
2102 $published = DateTimeFormat::utc($activity['object']['published']);
2107 if ($last_updated < $published) {
2108 $last_updated = $published;
2112 if (!empty($last_updated)) {
2113 return $last_updated;
2120 * Fetch the last activity date from an XML feed
2122 * @param array $data Probing result
2123 * @return string last activity
2125 private static function updateFromFeed(array $data)
2127 // Search for the newest entry in the feed
2128 $curlResult = DI::httpClient()->get($data['poll']);
2129 if (!$curlResult->isSuccess() || !$curlResult->getBody()) {
2133 $doc = new DOMDocument();
2134 @$doc->loadXML($curlResult->getBody());
2136 $xpath = new DOMXPath($doc);
2137 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2139 $entries = $xpath->query('/atom:feed/atom:entry');
2143 foreach ($entries as $entry) {
2144 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2145 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
2146 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2147 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2149 if (empty($published) || empty($updated)) {
2150 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2154 if ($last_updated < $published) {
2155 $last_updated = $published;
2158 if ($last_updated < $updated) {
2159 $last_updated = $updated;
2163 if (!empty($last_updated)) {
2164 return $last_updated;
2171 * Probe data from local profiles without network traffic
2173 * @param string $url
2174 * @return array probed data
2175 * @throws HTTPException\InternalServerErrorException
2176 * @throws HTTPException\NotFoundException
2178 private static function localProbe(string $url): array
2181 $uid = User::getIdForURL($url);
2183 throw new HTTPException\NotFoundException('User not found.');
2186 $owner = User::getOwnerDataById($uid);
2187 $approfile = ActivityPub\Transmitter::getProfile($uid);
2189 if (empty($owner['gsid'])) {
2190 $owner['gsid'] = GServer::getID($approfile['generator']['url']);
2194 'name' => $owner['name'], 'nick' => $owner['nick'], 'guid' => $approfile['diaspora:guid'] ?? '',
2195 'url' => $owner['url'], 'addr' => $owner['addr'], 'alias' => $owner['alias'],
2196 'photo' => User::getAvatarUrl($owner),
2197 'header' => $owner['header'] ? Contact::getHeaderUrlForId($owner['id'], $owner['updated']) : '',
2198 'account-type' => $owner['contact-type'], 'community' => ($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY),
2199 'keywords' => $owner['keywords'], 'location' => $owner['location'], 'about' => $owner['about'],
2200 'xmpp' => $owner['xmpp'], 'matrix' => $owner['matrix'],
2201 'hide' => !$owner['net-publish'], 'batch' => '', 'notify' => $owner['notify'],
2202 'poll' => $owner['poll'], 'request' => $owner['request'], 'confirm' => $owner['confirm'],
2203 'subscribe' => $approfile['generator']['url'] . '/follow?url={uri}', 'poco' => $owner['poco'],
2204 'following' => $approfile['following'], 'followers' => $approfile['followers'],
2205 'inbox' => $approfile['inbox'], 'outbox' => $approfile['outbox'],
2206 'sharedinbox' => $approfile['endpoints']['sharedInbox'], 'network' => Protocol::DFRN,
2207 'pubkey' => $owner['upubkey'], 'baseurl' => $approfile['generator']['url'], 'gsid' => $owner['gsid'],
2208 'manually-approve' => in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])
2210 } catch (Exception $e) {
2211 // Default values for non existing targets
2213 'name' => $url, 'nick' => $url, 'url' => $url, 'network' => Protocol::PHANTOM,
2214 'photo' => DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO
2218 return self::rearrangeData($data);