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
511 * @return array Webfinger array
513 private static function getWebfingerArray(string $uri)
515 $parts = parse_url($uri);
517 if (!empty($parts['scheme']) && !empty($parts['host'])) {
518 $host = $parts['host'];
519 if (!empty($parts['port'])) {
520 $host .= ':'.$parts['port'];
523 $baseurl = $parts['scheme'] . '://' . $host;
528 $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
529 if (!empty($path_parts)) {
530 $nick = ltrim(end($path_parts), '@');
531 // When the last part of the URI is numeric then it is most likely an ID and not a nick name
532 if (!is_numeric($nick)) {
533 $addr = $nick."@".$host;
539 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
540 if (empty($webfinger)) {
541 $lrdd = self::hostMeta($host);
544 if (empty($webfinger) && empty($lrdd)) {
545 while (empty($lrdd) && empty($webfinger) && (sizeof($path_parts) > 1)) {
546 $host .= "/".array_shift($path_parts);
547 $baseurl = $parts['scheme'] . '://' . $host;
550 $addr = $nick."@".$host;
553 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
554 if (empty($webfinger)) {
555 $lrdd = self::hostMeta($host);
559 if (empty($lrdd) && empty($webfinger)) {
563 } elseif (strstr($uri, '@')) {
564 // Remove "acct:" from the URI
565 $uri = str_replace('acct:', '', $uri);
567 $host = substr($uri, strpos($uri, '@') + 1);
568 $nick = substr($uri, 0, strpos($uri, '@'));
571 $webfinger = self::getWebfinger('https://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
572 if (self::$istimeout) {
576 if (empty($webfinger)) {
577 $webfinger = self::getWebfinger('http://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
578 if (self::$istimeout) {
582 $baseurl = 'https://' . $host;
585 if (empty($webfinger)) {
586 $lrdd = self::hostMeta($host);
587 if (self::$istimeout) {
590 $baseurl = self::$baseurl;
592 $baseurl = 'http://' . $host;
595 Logger::info('URI was not detectable', ['uri' => $uri]);
599 if (empty($webfinger)) {
600 foreach ($lrdd as $type => $template) {
605 $webfinger = self::getWebfinger($template, $type, $uri, $addr);
609 if (empty($webfinger)) {
613 if ($webfinger['detected'] == $addr) {
614 $webfinger['nick'] = $nick;
615 $webfinger['addr'] = $addr;
618 $webfinger['baseurl'] = $baseurl;
624 * Perform network request for webfinger data
626 * @param string $template
627 * @param string $type
629 * @param string $addr
630 * @return array webfinger results
632 private static function getWebfinger(string $template, string $type, string $uri, string $addr)
634 if (Network::isUrlBlocked($template)) {
635 Logger::info('Domain is blocked', ['url' => $template]);
639 // First try the address because this is the primary purpose of webfinger
642 $path = str_replace('{uri}', urlencode("acct:" . $addr), $template);
643 $webfinger = self::webfinger($path, $type);
644 if (self::$istimeout) {
650 if (empty($webfinger) && $uri != $addr) {
652 $path = str_replace('{uri}', urlencode($uri), $template);
653 $webfinger = self::webfinger($path, $type);
654 if (self::$istimeout) {
659 if (empty($webfinger)) {
663 return ['webfinger' => $webfinger, 'detected' => $detected];
667 * Fetch information (protocol endpoints and user information) about a given uri
669 * This function is only called by the "uri" function that adds caching and rearranging of data.
671 * @param string $uri Address that should be probed
672 * @param string $network Test for this specific network
673 * @param integer $uid User ID for the probe (only used for mails)
674 * @param array $ap_profile Previously probed AP profile
676 * @return array uri data
677 * @throws HTTPException\InternalServerErrorException
679 private static function detect(string $uri, string $network, int $uid, array $ap_profile)
683 'network' => $network,
688 Hook::callAll('probe_detect', $hookData);
690 if ($hookData['result']) {
691 if (!is_array($hookData['result'])) {
694 return $hookData['result'];
698 $parts = parse_url($uri);
700 if (!empty($parts['scheme']) && !empty($parts['host'])) {
701 if (in_array($parts['host'], ['twitter.com', 'mobile.twitter.com'])) {
702 return self::twitter($uri);
704 } elseif (strstr($uri, '@')) {
705 // If the URI starts with "mailto:" then jump directly to the mail detection
706 if (strpos($uri, 'mailto:') !== false) {
707 $uri = str_replace('mailto:', '', $uri);
708 return self::mail($uri, $uid);
711 if ($network == Protocol::MAIL) {
712 return self::mail($uri, $uid);
715 if (Strings::endsWith($uri, '@twitter.com')
716 || Strings::endsWith($uri, '@mobile.twitter.com')
718 return self::twitter($uri);
721 Logger::info('URI was not detectable', ['uri' => $uri]);
725 Logger::info('Probing start', ['uri' => $uri]);
727 if (!empty($ap_profile['addr']) && ($ap_profile['addr'] != $uri)) {
728 $data = self::getWebfingerArray($ap_profile['addr']);
732 $data = self::getWebfingerArray($uri);
736 if (!empty($parts['scheme'])) {
737 return self::feed($uri);
738 } elseif (!empty($uid)) {
739 return self::mail($uri, $uid);
745 $webfinger = $data['webfinger'];
746 $nick = $data['nick'] ?? '';
747 $addr = $data['addr'] ?? '';
748 $baseurl = $data['baseurl'] ?? '';
752 if (in_array($network, ["", Protocol::DFRN])) {
753 $result = self::dfrn($webfinger);
755 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
756 $result = self::diaspora($webfinger);
758 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
759 $result = self::ostatus($webfinger);
761 if (in_array($network, ['', Protocol::ZOT])) {
762 $result = self::zot($webfinger, $result, $baseurl);
764 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
765 $result = self::pumpio($webfinger, $addr);
767 if (empty($result['network']) && empty($ap_profile['network']) || ($network == Protocol::FEED)) {
768 $result = self::feed($uri);
770 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
771 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
772 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
773 $result["nick"] = $nick;
776 if (empty($result["addr"]) && ($addr != "")) {
777 $result["addr"] = $addr;
781 $result = self::getSubscribeLink($result, $webfinger);
783 if (empty($result["network"])) {
784 $result["network"] = Protocol::PHANTOM;
787 if (empty($result['baseurl']) && !empty($baseurl)) {
788 $result['baseurl'] = $baseurl;
791 if (empty($result["url"])) {
792 $result["url"] = $uri;
795 Logger::info('Probing done', ['uri' => $uri, 'network' => $result["network"]]);
801 * Check for Zot contact
803 * @param array $webfinger Webfinger data
804 * @param array $data previously probed data
806 * @return array Zot data
807 * @throws HTTPException\InternalServerErrorException
809 private static function zot($webfinger, $data, $baseurl)
811 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
812 foreach ($webfinger["aliases"] as $alias) {
813 if (substr($alias, 0, 5) == 'acct:') {
814 $data["addr"] = substr($alias, 5);
819 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
820 $data["addr"] = substr($webfinger["subject"], 5);
824 foreach ($webfinger['links'] as $link) {
825 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
826 $zot_url = $link['href'];
830 if (empty($zot_url) && !empty($data['addr']) && !empty($baseurl)) {
831 $condition = ['nurl' => Strings::normaliseLink($baseurl), 'platform' => ['hubzilla']];
832 if (!DBA::exists('gserver', $condition)) {
835 $zot_url = $baseurl . '/.well-known/zot-info?address=' . $data['addr'];
838 if (empty($zot_url)) {
842 $data = self::pollZot($zot_url, $data);
844 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
845 foreach ($webfinger['aliases'] as $alias) {
846 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
847 $data['alias'] = $alias;
855 public static function pollZot($url, $data)
857 $curlResult = DI::httpClient()->get($url);
858 if ($curlResult->isTimeout()) {
861 $content = $curlResult->getBody();
866 $json = json_decode($content, true);
867 if (!is_array($json)) {
871 if (empty($data['network'])) {
872 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
873 $data['network'] = Protocol::ZOT;
874 } elseif (!isset($json['protocols'])) {
875 $data['network'] = Protocol::ZOT;
879 if (!empty($json['guid']) && empty($data['guid'])) {
880 $data['guid'] = $json['guid'];
882 if (!empty($json['key']) && empty($data['pubkey'])) {
883 $data['pubkey'] = $json['key'];
885 if (!empty($json['name'])) {
886 $data['name'] = $json['name'];
888 if (!empty($json['photo'])) {
889 $data['photo'] = $json['photo'];
890 if (!empty($json['photo_updated'])) {
891 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
894 if (!empty($json['address'])) {
895 $data['addr'] = $json['address'];
897 if (!empty($json['url'])) {
898 $data['url'] = $json['url'];
900 if (!empty($json['connections_url'])) {
901 $data['poco'] = $json['connections_url'];
903 if (isset($json['searchable'])) {
904 $data['hide'] = !$json['searchable'];
906 if (!empty($json['public_forum'])) {
907 $data['community'] = $json['public_forum'];
908 $data['account-type'] = User::PAGE_FLAGS_COMMUNITY;
911 if (!empty($json['profile'])) {
912 $profile = $json['profile'];
913 if (!empty($profile['description'])) {
914 $data['about'] = $profile['description'];
916 if (!empty($profile['keywords'])) {
917 $keywords = implode(', ', $profile['keywords']);
918 if (!empty($keywords)) {
919 $data['keywords'] = $keywords;
924 if (!empty($profile['region'])) {
925 $loc['region'] = $profile['region'];
927 if (!empty($profile['country'])) {
928 $loc['country-name'] = $profile['country'];
930 $location = Profile::formatLocation($loc);
931 if (!empty($location)) {
932 $data['location'] = $location;
940 * Perform a webfinger request.
942 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
944 * @param string $url Address that should be probed
945 * @param string $type type
947 * @return array webfinger data
948 * @throws HTTPException\InternalServerErrorException
950 public static function webfinger($url, $type)
952 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
954 $curlResult = DI::httpClient()->get($url, [HttpClientOptions::TIMEOUT => $xrd_timeout, HttpClientOptions::ACCEPT_CONTENT => [$type]]);
955 if ($curlResult->isTimeout()) {
956 self::$istimeout = true;
959 $data = $curlResult->getBody();
961 $webfinger = json_decode($data, true);
962 if (!empty($webfinger)) {
963 if (!isset($webfinger["links"])) {
964 Logger::info('No json webfinger links', ['url' => $url]);
970 // If it is not JSON, maybe it is XML
971 $xrd = XML::parseString($data, true);
972 if (!is_object($xrd)) {
973 Logger::info('No webfinger data retrievable', ['url' => $url]);
977 $xrd_arr = XML::elementToArray($xrd);
978 if (!isset($xrd_arr["xrd"]["link"])) {
979 Logger::info('No XML webfinger links', ['url' => $url]);
985 if (!empty($xrd_arr["xrd"]["subject"])) {
986 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
989 if (!empty($xrd_arr["xrd"]["alias"])) {
990 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
993 $webfinger["links"] = [];
995 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
996 if (!empty($data["@attributes"])) {
997 $attributes = $data["@attributes"];
998 } elseif ($value == "@attributes") {
1004 $webfinger["links"][] = $attributes;
1010 * Poll the Friendica specific noscrape page.
1012 * "noscrape" is a faster alternative to fetch the data from the hcard.
1013 * This functionality was originally created for the directory.
1015 * @param string $noscrape_url Link to the noscrape page
1016 * @param array $data The already fetched data
1018 * @return array noscrape data
1019 * @throws HTTPException\InternalServerErrorException
1021 private static function pollNoscrape($noscrape_url, $data)
1023 $curlResult = DI::httpClient()->get($noscrape_url);
1024 if ($curlResult->isTimeout()) {
1025 self::$istimeout = true;
1028 $content = $curlResult->getBody();
1030 Logger::info('Empty body', ['url' => $noscrape_url]);
1034 $json = json_decode($content, true);
1035 if (!is_array($json)) {
1036 Logger::info('No json data', ['url' => $noscrape_url]);
1040 if (!empty($json["fn"])) {
1041 $data["name"] = $json["fn"];
1044 if (!empty($json["addr"])) {
1045 $data["addr"] = $json["addr"];
1048 if (!empty($json["nick"])) {
1049 $data["nick"] = $json["nick"];
1052 if (!empty($json["guid"])) {
1053 $data["guid"] = $json["guid"];
1056 if (!empty($json["comm"])) {
1057 $data["community"] = $json["comm"];
1060 if (!empty($json["tags"])) {
1061 $keywords = implode(", ", $json["tags"]);
1062 if ($keywords != "") {
1063 $data["keywords"] = $keywords;
1067 $location = Profile::formatLocation($json);
1069 $data["location"] = $location;
1072 if (!empty($json["about"])) {
1073 $data["about"] = $json["about"];
1076 if (!empty($json["xmpp"])) {
1077 $data["xmpp"] = $json["xmpp"];
1080 if (!empty($json["matrix"])) {
1081 $data["matrix"] = $json["matrix"];
1084 if (!empty($json["key"])) {
1085 $data["pubkey"] = $json["key"];
1088 if (!empty($json["photo"])) {
1089 $data["photo"] = $json["photo"];
1092 if (!empty($json["dfrn-request"])) {
1093 $data["request"] = $json["dfrn-request"];
1096 if (!empty($json["dfrn-confirm"])) {
1097 $data["confirm"] = $json["dfrn-confirm"];
1100 if (!empty($json["dfrn-notify"])) {
1101 $data["notify"] = $json["dfrn-notify"];
1104 if (!empty($json["dfrn-poll"])) {
1105 $data["poll"] = $json["dfrn-poll"];
1108 if (isset($json["hide"])) {
1109 $data["hide"] = (bool)$json["hide"];
1111 $data["hide"] = false;
1118 * Check for valid DFRN data
1120 * @param array $data DFRN data
1122 * @return int Number of errors
1124 public static function validDfrn($data)
1127 if (!isset($data['key'])) {
1130 if (!isset($data['dfrn-request'])) {
1133 if (!isset($data['dfrn-confirm'])) {
1136 if (!isset($data['dfrn-notify'])) {
1139 if (!isset($data['dfrn-poll'])) {
1146 * Fetch data from a DFRN profile page and via "noscrape"
1148 * @param string $profile_link Link to the profile page
1150 * @return array profile data
1151 * @throws HTTPException\InternalServerErrorException
1152 * @throws \ImagickException
1154 public static function profile($profile_link)
1158 Logger::info('Check profile', ['link' => $profile_link]);
1160 // Fetch data via noscrape - this is faster
1161 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1162 $data = self::pollNoscrape($noscrape_url, $data);
1164 if (!isset($data["notify"])
1165 || !isset($data["confirm"])
1166 || !isset($data["request"])
1167 || !isset($data["poll"])
1168 || !isset($data["name"])
1169 || !isset($data["photo"])
1171 $data = self::pollHcard($profile_link, $data, true);
1176 if (empty($data["addr"]) || empty($data["nick"])) {
1177 $probe_data = self::uri($profile_link);
1178 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1179 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1182 $prof_data["addr"] = $data["addr"];
1183 $prof_data["nick"] = $data["nick"];
1184 $prof_data["dfrn-request"] = $data['request'] ?? null;
1185 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1186 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1187 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1188 $prof_data["photo"] = $data['photo'] ?? null;
1189 $prof_data["fn"] = $data['name'] ?? null;
1190 $prof_data["key"] = $data['pubkey'] ?? null;
1192 Logger::debug('Result', ['link' => $profile_link, 'data' => $prof_data]);
1198 * Check for DFRN contact
1200 * @param array $webfinger Webfinger data
1202 * @return array DFRN data
1203 * @throws HTTPException\InternalServerErrorException
1205 private static function dfrn($webfinger)
1209 // The array is reversed to take into account the order of preference for same-rel links
1210 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1211 foreach (array_reverse($webfinger["links"]) as $link) {
1212 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1213 $data["network"] = Protocol::DFRN;
1214 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1215 $data["poll"] = $link["href"];
1216 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1217 $data["url"] = $link["href"];
1218 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1219 $hcard_url = $link["href"];
1220 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1221 $data["poco"] = $link["href"];
1222 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1223 $data["photo"] = $link["href"];
1224 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1225 $data["baseurl"] = trim($link["href"], '/');
1226 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1227 $data["guid"] = $link["href"];
1228 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1229 $data["pubkey"] = base64_decode($link["href"]);
1231 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1232 if (strstr($data["pubkey"], 'RSA ')) {
1233 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1238 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1239 foreach ($webfinger["aliases"] as $alias) {
1240 if (empty($data["url"]) && !strstr($alias, "@")) {
1241 $data["url"] = $alias;
1242 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1243 $data["alias"] = $alias;
1244 } elseif (substr($alias, 0, 5) == 'acct:') {
1245 $data["addr"] = substr($alias, 5);
1250 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1251 $data["addr"] = substr($webfinger["subject"], 5);
1254 if (!isset($data["network"]) || ($hcard_url == "")) {
1258 // Fetch data via noscrape - this is faster
1259 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1260 $data = self::pollNoscrape($noscrape_url, $data);
1262 if (isset($data["notify"])
1263 && isset($data["confirm"])
1264 && isset($data["request"])
1265 && isset($data["poll"])
1266 && isset($data["name"])
1267 && isset($data["photo"])
1272 $data = self::pollHcard($hcard_url, $data, true);
1278 * Poll the hcard page (Diaspora and Friendica specific)
1280 * @param string $hcard_url Link to the hcard page
1281 * @param array $data The already fetched data
1282 * @param boolean $dfrn Poll DFRN specific data
1284 * @return array hcard data
1285 * @throws HTTPException\InternalServerErrorException
1287 private static function pollHcard($hcard_url, $data, $dfrn = false)
1289 $curlResult = DI::httpClient()->get($hcard_url);
1290 if ($curlResult->isTimeout()) {
1291 self::$istimeout = true;
1294 $content = $curlResult->getBody();
1295 if (empty($content)) {
1299 $doc = new DOMDocument();
1300 if (!@$doc->loadHTML($content)) {
1304 $xpath = new DomXPath($doc);
1306 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1307 if (!is_object($vcards)) {
1311 if (!isset($data["baseurl"])) {
1312 $data["baseurl"] = "";
1315 if ($vcards->length > 0) {
1316 $vcard = $vcards->item(0);
1318 // We have to discard the guid from the hcard in favour of the guid from lrdd
1319 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1320 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1321 if (($search->length > 0) && empty($data["guid"])) {
1322 $data["guid"] = $search->item(0)->nodeValue;
1325 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1326 if ($search->length > 0) {
1327 $data["nick"] = $search->item(0)->nodeValue;
1330 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1331 if ($search->length > 0) {
1332 $data["name"] = $search->item(0)->nodeValue;
1335 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1336 if ($search->length > 0) {
1337 $data["searchable"] = $search->item(0)->nodeValue;
1340 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1341 if ($search->length > 0) {
1342 $data["pubkey"] = $search->item(0)->nodeValue;
1343 if (strstr($data["pubkey"], 'RSA ')) {
1344 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1348 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1349 if ($search->length > 0) {
1350 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1355 if (!empty($vcard)) {
1356 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1357 foreach ($photos as $photo) {
1359 foreach ($photo->attributes as $attribute) {
1360 $attr[$attribute->name] = trim($attribute->value);
1363 if (isset($attr["src"]) && isset($attr["width"])) {
1364 $avatar[$attr["width"]] = $attr["src"];
1367 // We don't have a width. So we just take everything that we got.
1368 // This is a Hubzilla workaround which doesn't send a width.
1369 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1370 $avatar[] = $attr["src"];
1375 if (sizeof($avatar)) {
1377 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1381 // Poll DFRN specific data
1382 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1383 if ($search->length > 0) {
1384 foreach ($search as $link) {
1385 //$data["request"] = $search->item(0)->nodeValue;
1387 foreach ($link->attributes as $attribute) {
1388 $attr[$attribute->name] = trim($attribute->value);
1391 $data[substr($attr["rel"], 5)] = $attr["href"];
1395 // Older Friendica versions had used the "uid" field differently than newer versions
1396 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1397 unset($data["guid"]);
1406 * Check for Diaspora contact
1408 * @param array $webfinger Webfinger data
1410 * @return array Diaspora data
1411 * @throws HTTPException\InternalServerErrorException
1413 private static function diaspora($webfinger)
1418 // The array is reversed to take into account the order of preference for same-rel links
1419 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1420 foreach (array_reverse($webfinger["links"]) as $link) {
1421 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1422 $hcard_url = $link["href"];
1423 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1424 $data["baseurl"] = trim($link["href"], '/');
1425 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1426 $data["guid"] = $link["href"];
1427 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1428 $data["url"] = $link["href"];
1429 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && empty($link["type"]) && !empty($link["href"])) {
1430 $profile_url = $link["href"];
1431 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1432 $data["poll"] = $link["href"];
1433 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1434 $data["poco"] = $link["href"];
1435 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1436 $data["notify"] = $link["href"];
1437 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1438 $data["pubkey"] = base64_decode($link["href"]);
1440 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1441 if (strstr($data["pubkey"], 'RSA ')) {
1442 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1447 if (empty($data["url"]) && !empty($profile_url)) {
1448 $data["url"] = $profile_url;
1451 if (empty($data["url"]) || empty($hcard_url)) {
1455 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1456 foreach ($webfinger["aliases"] as $alias) {
1457 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1458 $data["alias"] = $alias;
1459 } elseif (substr($alias, 0, 5) == 'acct:') {
1460 $data["addr"] = substr($alias, 5);
1465 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1466 $data["addr"] = substr($webfinger["subject"], 5);
1469 // Fetch further information from the hcard
1470 $data = self::pollHcard($hcard_url, $data);
1476 if (!empty($data["url"])
1477 && !empty($data["guid"])
1478 && !empty($data["baseurl"])
1479 && !empty($data["pubkey"])
1480 && !empty($hcard_url)
1482 $data["network"] = Protocol::DIASPORA;
1483 $data["manually-approve"] = false;
1485 // The Diaspora handle must always be lowercase
1486 if (!empty($data["addr"])) {
1487 $data["addr"] = strtolower($data["addr"]);
1490 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1491 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1492 $data["batch"] = $data["baseurl"] . "/receive/public";
1501 * Check for OStatus contact
1503 * @param array $webfinger Webfinger data
1504 * @param bool $short Short detection mode
1506 * @return array|bool OStatus data or "false" on error or "true" on short mode
1507 * @throws HTTPException\InternalServerErrorException
1509 private static function ostatus($webfinger, $short = false)
1513 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1514 foreach ($webfinger["aliases"] as $alias) {
1515 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1516 $data["addr"] = str_replace('acct:', '', $alias);
1521 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1522 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1524 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1527 if (!empty($webfinger["links"])) {
1528 // The array is reversed to take into account the order of preference for same-rel links
1529 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1530 foreach (array_reverse($webfinger["links"]) as $link) {
1531 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1532 && (($link["type"] ?? "") == "text/html")
1533 && ($link["href"] != "")
1535 $data["url"] = $data["alias"] = $link["href"];
1536 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1537 $data["notify"] = $link["href"];
1538 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1539 $data["poll"] = $link["href"];
1540 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1541 $pubkey = $link["href"];
1543 if (substr($pubkey, 0, 5) === 'data:') {
1544 if (strstr($pubkey, ',')) {
1545 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1547 $pubkey = substr($pubkey, 5);
1549 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1550 $curlResult = DI::httpClient()->get($pubkey);
1551 if ($curlResult->isTimeout()) {
1552 self::$istimeout = true;
1553 return $short ? false : [];
1555 $pubkey = $curlResult->getBody();
1558 $key = explode(".", $pubkey);
1560 if (sizeof($key) >= 3) {
1561 $m = Strings::base64UrlDecode($key[1]);
1562 $e = Strings::base64UrlDecode($key[2]);
1563 $data["pubkey"] = Crypto::meToPem($m, $e);
1569 if (isset($data["notify"]) && isset($data["pubkey"])
1570 && isset($data["poll"])
1571 && isset($data["url"])
1573 $data["network"] = Protocol::OSTATUS;
1574 $data["manually-approve"] = false;
1576 return $short ? false : [];
1583 // Fetch all additional data from the feed
1584 $curlResult = DI::httpClient()->get($data["poll"]);
1585 if ($curlResult->isTimeout()) {
1586 self::$istimeout = true;
1589 $feed = $curlResult->getBody();
1590 $feed_data = Feed::import($feed);
1595 if (!empty($feed_data["header"]["author-name"])) {
1596 $data["name"] = $feed_data["header"]["author-name"];
1598 if (!empty($feed_data["header"]["author-nick"])) {
1599 $data["nick"] = $feed_data["header"]["author-nick"];
1601 if (!empty($feed_data["header"]["author-avatar"])) {
1602 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1604 if (!empty($feed_data["header"]["author-id"])) {
1605 $data["alias"] = $feed_data["header"]["author-id"];
1607 if (!empty($feed_data["header"]["author-location"])) {
1608 $data["location"] = $feed_data["header"]["author-location"];
1610 if (!empty($feed_data["header"]["author-about"])) {
1611 $data["about"] = $feed_data["header"]["author-about"];
1613 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1614 // So we take the value that we just fetched, although the other one worked as well
1615 if (!empty($feed_data["header"]["author-link"])) {
1616 $data["url"] = $feed_data["header"]["author-link"];
1619 if ($data["url"] == $data["alias"]) {
1620 $data["alias"] = '';
1623 /// @todo Fetch location and "about" from the feed as well
1628 * Fetch data from a pump.io profile page
1630 * @param string $profile_link Link to the profile page
1632 * @return array profile data
1634 private static function pumpioProfileData($profile_link)
1636 $curlResult = DI::httpClient()->get($profile_link);
1637 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
1641 $doc = new DOMDocument();
1642 if (!@$doc->loadHTML($curlResult->getBody())) {
1646 $xpath = new DomXPath($doc);
1650 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1652 if ($data["name"] == '') {
1653 // This is ugly - but pump.io doesn't seem to know a better way for it
1654 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1655 $pos = strpos($data["name"], chr(10));
1657 $data["name"] = trim(substr($data["name"], 0, $pos));
1661 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1663 if ($data["location"] == '') {
1664 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1667 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1669 if ($data["about"] == '') {
1670 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1673 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1675 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1678 foreach ($avatar->attributes as $attribute) {
1679 if ($attribute->name == "src") {
1680 $data["photo"] = trim($attribute->value);
1689 * Check for pump.io contact
1691 * @param array $webfinger Webfinger data
1692 * @param string $addr
1693 * @return array pump.io data
1695 private static function pumpio($webfinger, $addr)
1698 // The array is reversed to take into account the order of preference for same-rel links
1699 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1700 foreach (array_reverse($webfinger["links"]) as $link) {
1701 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1702 && (($link["type"] ?? "") == "text/html")
1703 && ($link["href"] != "")
1705 $data["url"] = $link["href"];
1706 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1707 $data["notify"] = $link["href"];
1708 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1709 $data["poll"] = $link["href"];
1710 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1711 $data["dialback"] = $link["href"];
1714 if (isset($data["poll"]) && isset($data["notify"])
1715 && isset($data["dialback"])
1716 && isset($data["url"])
1718 // by now we use these fields only for the network type detection
1719 // So we unset all data that isn't used at the moment
1720 unset($data["dialback"]);
1722 $data["network"] = Protocol::PUMPIO;
1727 $profile_data = self::pumpioProfileData($data["url"]);
1729 if (!$profile_data) {
1733 $data = array_merge($data, $profile_data);
1735 if (($addr != '') && ($data['name'] != '')) {
1736 $name = trim(str_replace($addr, '', $data['name']));
1738 $data['name'] = $name;
1746 * Check for twitter contact
1748 * @param string $uri
1750 * @return array twitter data
1752 private static function twitter($uri)
1754 if (preg_match('=([^@]+)@(?:mobile\.)?twitter\.com$=i', $uri, $matches)) {
1755 $nick = $matches[1];
1756 } elseif (preg_match('=^https?://(?:mobile\.)?twitter\.com/(.+)=i', $uri, $matches)) {
1757 $nick = $matches[1];
1763 $data['url'] = 'https://twitter.com/' . $nick;
1764 $data['addr'] = $nick . '@twitter.com';
1765 $data['nick'] = $data['name'] = $nick;
1766 $data['network'] = Protocol::TWITTER;
1767 $data['baseurl'] = 'https://twitter.com';
1773 * Checks HTML page for RSS feed link
1775 * @param string $url Page link
1776 * @param string $body Page body string
1777 * @return string|false Feed link or false if body was invalid HTML document
1779 public static function getFeedLink(string $url, string $body)
1785 $doc = new DOMDocument();
1786 if (!@$doc->loadHTML($body)) {
1790 $xpath = new DOMXPath($doc);
1792 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1794 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1800 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1802 * Loosely based on RFC 1808
1804 * @see https://tools.ietf.org/html/rfc1808
1806 * @param string $href The potential relative href found in the HTML document
1807 * @param string $base The HTML document URL
1808 * @param DOMXPath $xpath The HTML document XPath
1811 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath)
1813 if (filter_var($href, FILTER_VALIDATE_URL)) {
1817 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1819 $baseParts = parse_url($base);
1820 if (empty($baseParts['host'])) {
1824 // Naked domain case (scheme://basehost)
1825 $path = $baseParts['path'] ?? '/';
1827 // Remove the filename part of the path if it exists (/base/path/file)
1828 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1830 $hrefParts = parse_url($href);
1832 if (!empty($hrefParts['path'])) {
1833 // Root path case (/path) including relative scheme case (//host/path)
1834 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1835 $path = $hrefParts['path'];
1837 $path = $path . '/' . $hrefParts['path'];
1839 // Resolve arbitrary relative path
1840 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1841 $parts = array_filter(explode('/', $path), 'strlen');
1842 $absolutes = array();
1843 foreach ($parts as $part) {
1844 if ('.' == $part) continue;
1845 if ('..' == $part) {
1846 array_pop($absolutes);
1848 $absolutes[] = $part;
1852 $path = '/' . implode('/', $absolutes);
1856 // Relative scheme case (//host/path)
1857 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1858 $baseParts['path'] = $path;
1859 unset($baseParts['query']);
1860 unset($baseParts['fragment']);
1862 return Network::unparseURL($baseParts);
1866 * Check for feed contact
1868 * @param string $url Profile link
1869 * @param boolean $probe Do a probe if the page contains a feed link
1871 * @return array feed data
1872 * @throws HTTPException\InternalServerErrorException
1874 private static function feed($url, $probe = true)
1876 $curlResult = DI::httpClient()->get($url);
1877 if ($curlResult->isTimeout()) {
1878 self::$istimeout = true;
1881 $feed = $curlResult->getBody();
1882 $feed_data = Feed::import($feed);
1889 $feed_url = self::getFeedLink($url, $feed);
1895 return self::feed($feed_url, false);
1898 if (!empty($feed_data["header"]["author-name"])) {
1899 $data["name"] = $feed_data["header"]["author-name"];
1902 if (!empty($feed_data["header"]["author-nick"])) {
1903 $data["nick"] = $feed_data["header"]["author-nick"];
1906 if (!empty($feed_data["header"]["author-avatar"])) {
1907 $data["photo"] = $feed_data["header"]["author-avatar"];
1910 if (!empty($feed_data["header"]["author-id"])) {
1911 $data["alias"] = $feed_data["header"]["author-id"];
1914 $data["url"] = $url;
1915 $data["poll"] = $url;
1917 $data["network"] = Protocol::FEED;
1923 * Check for mail contact
1925 * @param string $uri Profile link
1926 * @param integer $uid User ID
1928 * @return array mail data
1929 * @throws \Exception
1931 private static function mail($uri, $uid)
1933 if (!Network::isEmailDomainValid($uri)) {
1941 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1943 $condition = ["`uid` = ? AND `server` != ''", $uid];
1944 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1945 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1947 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1951 $mailbox = Email::constructMailboxName($mailacct);
1953 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1954 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1959 $msgs = Email::poll($mbox, $uri);
1960 Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
1962 if (!count($msgs)) {
1966 $phost = substr($uri, strpos($uri, '@') + 1);
1969 $data["addr"] = $uri;
1970 $data["network"] = Protocol::MAIL;
1971 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1972 $data["nick"] = $data["name"];
1973 $data["photo"] = Network::lookupAvatarByEmail($uri);
1974 $data["url"] = 'mailto:'.$uri;
1975 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1976 $data["poll"] = 'email ' . Strings::getRandomHex();
1978 $x = Email::messageMeta($mbox, $msgs[0]);
1979 if (stristr($x[0]->from, $uri)) {
1980 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1981 } elseif (stristr($x[0]->to, $uri)) {
1982 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1985 foreach ($adr as $feadr) {
1986 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1987 &&(strcasecmp($feadr->host, $phost) == 0)
1988 && (strlen($feadr->personal))
1990 $personal = imap_mime_header_decode($feadr->personal);
1992 foreach ($personal as $perspart) {
1993 if ($perspart->charset != "default") {
1994 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1996 $data["name"] .= $perspart->text;
2002 if (!empty($mbox)) {
2009 * Mix two paths together to possibly fix missing parts
2011 * @param string $avatar Path to the avatar
2012 * @param string $base Another path that is hopefully complete
2014 * @return string fixed avatar path
2015 * @throws \Exception
2017 public static function fixAvatar($avatar, $base)
2019 $base_parts = parse_url($base);
2021 // Remove all parts that could create a problem
2022 unset($base_parts['path']);
2023 unset($base_parts['query']);
2024 unset($base_parts['fragment']);
2026 $avatar_parts = parse_url($avatar);
2029 $parts = array_merge($base_parts, $avatar_parts);
2031 // And put them together again
2032 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
2033 $host = isset($parts['host']) ? $parts['host'] : '';
2034 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
2035 $path = isset($parts['path']) ? $parts['path'] : '';
2036 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
2037 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
2039 $fixed = $scheme.$host.$port.$path.$query.$fragment;
2041 Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
2047 * Fetch the last date that the contact had posted something (publically)
2049 * @param string $data probing result
2050 * @return string last activity
2052 public static function getLastUpdate(array $data)
2054 $uid = User::getIdForURL($data['url']);
2056 $contact = Contact::selectFirst(['url', 'last-item'], ['self' => true, 'uid' => $uid]);
2057 if (!empty($contact['last-item'])) {
2058 return $contact['last-item'];
2062 if ($lastUpdate = self::updateFromNoScrape($data)) {
2066 if (!empty($data['outbox'])) {
2067 return self::updateFromOutbox($data['outbox'], $data);
2068 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
2069 return self::updateFromOutbox($data['poll'], $data);
2070 } elseif (!empty($data['poll'])) {
2071 return self::updateFromFeed($data);
2078 * Fetch the last activity date from the "noscrape" endpoint
2080 * @param array $data Probing result
2081 * @return string last activity
2083 * @return bool 'true' if update was successful or the server was unreachable
2085 private static function updateFromNoScrape(array $data)
2087 if (empty($data['baseurl'])) {
2091 // Check the 'noscrape' endpoint when it is a Friendica server
2092 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
2093 Strings::normaliseLink($data['baseurl'])]);
2094 if (!DBA::isResult($gserver)) {
2098 $curlResult = DI::httpClient()->get($gserver['noscrape'] . '/' . $data['nick']);
2100 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
2101 $noscrape = json_decode($curlResult->getBody(), true);
2102 if (!empty($noscrape) && !empty($noscrape['updated'])) {
2103 return DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2111 * Fetch the last activity date from an ActivityPub Outbox
2113 * @param string $feed
2114 * @param array $data Probing result
2115 * @return string last activity
2116 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2118 private static function updateFromOutbox(string $feed, array $data)
2120 $outbox = ActivityPub::fetchContent($feed);
2121 if (empty($outbox)) {
2125 if (!empty($outbox['orderedItems'])) {
2126 $items = $outbox['orderedItems'];
2127 } elseif (!empty($outbox['first']['orderedItems'])) {
2128 $items = $outbox['first']['orderedItems'];
2129 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2130 return self::updateFromOutbox($outbox['first']['href'], $data);
2131 } elseif (!empty($outbox['first'])) {
2132 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2133 return self::updateFromOutbox($outbox['first'], $data);
2135 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2143 foreach ($items as $activity) {
2144 if (!empty($activity['published'])) {
2145 $published = DateTimeFormat::utc($activity['published']);
2146 } elseif (!empty($activity['object']['published'])) {
2147 $published = DateTimeFormat::utc($activity['object']['published']);
2152 if ($last_updated < $published) {
2153 $last_updated = $published;
2157 if (!empty($last_updated)) {
2158 return $last_updated;
2165 * Fetch the last activity date from an XML feed
2167 * @param array $data Probing result
2168 * @return string last activity
2170 private static function updateFromFeed(array $data)
2172 // Search for the newest entry in the feed
2173 $curlResult = DI::httpClient()->get($data['poll']);
2174 if (!$curlResult->isSuccess() || !$curlResult->getBody()) {
2178 $doc = new DOMDocument();
2179 @$doc->loadXML($curlResult->getBody());
2181 $xpath = new DOMXPath($doc);
2182 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2184 $entries = $xpath->query('/atom:feed/atom:entry');
2188 foreach ($entries as $entry) {
2189 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2190 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
2191 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2192 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2194 if (empty($published) || empty($updated)) {
2195 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2199 if ($last_updated < $published) {
2200 $last_updated = $published;
2203 if ($last_updated < $updated) {
2204 $last_updated = $updated;
2208 if (!empty($last_updated)) {
2209 return $last_updated;
2216 * Probe data from local profiles without network traffic
2218 * @param string $url
2219 * @return array probed data
2220 * @throws HTTPException\InternalServerErrorException
2221 * @throws HTTPException\NotFoundException
2223 private static function localProbe(string $url): array
2226 $uid = User::getIdForURL($url);
2228 throw new HTTPException\NotFoundException('User not found.');
2231 $owner = User::getOwnerDataById($uid);
2232 $approfile = ActivityPub\Transmitter::getProfile($uid);
2234 if (empty($owner['gsid'])) {
2235 $owner['gsid'] = GServer::getID($approfile['generator']['url']);
2239 'name' => $owner['name'], 'nick' => $owner['nick'], 'guid' => $approfile['diaspora:guid'] ?? '',
2240 'url' => $owner['url'], 'addr' => $owner['addr'], 'alias' => $owner['alias'],
2241 'photo' => User::getAvatarUrl($owner),
2242 'header' => $owner['header'] ? Contact::getHeaderUrlForId($owner['id'], $owner['updated']) : '',
2243 'account-type' => $owner['contact-type'], 'community' => ($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY),
2244 'keywords' => $owner['keywords'], 'location' => $owner['location'], 'about' => $owner['about'],
2245 'xmpp' => $owner['xmpp'], 'matrix' => $owner['matrix'],
2246 'hide' => !$owner['net-publish'], 'batch' => '', 'notify' => $owner['notify'],
2247 'poll' => $owner['poll'], 'request' => $owner['request'], 'confirm' => $owner['confirm'],
2248 'subscribe' => $approfile['generator']['url'] . '/follow?url={uri}', 'poco' => $owner['poco'],
2249 'following' => $approfile['following'], 'followers' => $approfile['followers'],
2250 'inbox' => $approfile['inbox'], 'outbox' => $approfile['outbox'],
2251 'sharedinbox' => $approfile['endpoints']['sharedInbox'], 'network' => Protocol::DFRN,
2252 'pubkey' => $owner['upubkey'], 'baseurl' => $approfile['generator']['url'], 'gsid' => $owner['gsid'],
2253 'manually-approve' => in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])
2255 } catch (Exception $e) {
2256 // Default values for non existing targets
2258 'name' => $url, 'nick' => $url, 'url' => $url, 'network' => Protocol::PHANTOM,
2259 'photo' => DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO
2263 return self::rearrangeData($data);