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\Protocol\ActivityNamespace;
38 use Friendica\Protocol\ActivityPub;
39 use Friendica\Protocol\Email;
40 use Friendica\Protocol\Feed;
41 use Friendica\Util\Crypto;
42 use Friendica\Util\DateTimeFormat;
43 use Friendica\Util\Network;
44 use Friendica\Util\Strings;
45 use Friendica\Util\XML;
48 * This class contain functions for probing URL
52 const WEBFINGER = '/.well-known/webfinger?resource={uri}';
54 private static $baseurl;
55 private static $istimeout;
58 * Remove stuff from an URI that doesn't belong there
61 * @return string Cleaned URI
63 public static function cleanURI(string $URI)
65 // At first remove leading and trailing junk
66 $URI = trim($URI, "@#?:/ \t\n\r\0\x0B");
68 $parts = parse_url($URI);
70 if (empty($parts['scheme'])) {
74 // Remove the URL fragment, since these shouldn't be part of any profile URL
75 unset($parts['fragment']);
77 $URI = Network::unparseURL($parts);
83 * Rearrange the array so that it always has the same order
85 * @param array $data Unordered data
87 * @return array Ordered data
89 private static function rearrangeData($data)
91 $fields = ["name", "nick", "guid", "url", "addr", "alias", "photo", "header",
92 "account-type", "community", "keywords", "location", "about", "xmpp", "matrix",
93 "hide", "batch", "notify", "poll", "request", "confirm", "subscribe", "poco",
94 "following", "followers", "inbox", "outbox", "sharedinbox",
95 "priority", "network", "pubkey", "manually-approve", "baseurl", "gsid"];
97 $numeric_fields = ["gsid", "hide", "account-type", "manually-approve"];
100 foreach ($fields as $field) {
101 if (isset($data[$field])) {
102 if (in_array($field, $numeric_fields)) {
103 $newdata[$field] = (int)$data[$field];
105 $newdata[$field] = $data[$field];
107 } elseif (!in_array($field, $numeric_fields)) {
108 $newdata[$field] = "";
110 $newdata[$field] = null;
114 // We don't use the "priority" field anymore and replace it with a dummy.
115 $newdata["priority"] = 0;
121 * Check if the hostname belongs to the own server
123 * @param string $host The hostname that is to be checked
125 * @return bool Does the testes hostname belongs to the own server?
127 private static function ownHost($host)
129 $own_host = DI::baseUrl()->getHostname();
131 $parts = parse_url($host);
133 if (!isset($parts['scheme'])) {
134 $parts = parse_url('http://'.$host);
137 if (!isset($parts['host'])) {
140 return $parts['host'] == $own_host;
144 * Probes for webfinger path via "host-meta"
146 * We have to check if the servers in the future still will offer this.
147 * It seems as if it was dropped from the standard.
149 * @param string $host The host part of an url
151 * @return array with template and type of the webfinger template for JSON or XML
152 * @throws HTTPException\InternalServerErrorException
154 private static function hostMeta($host)
156 // Reset the static variable
159 // Handles the case when the hostname contains the scheme
160 if (!parse_url($host, PHP_URL_SCHEME)) {
161 $ssl_url = "https://" . $host . "/.well-known/host-meta";
162 $url = "http://" . $host . "/.well-known/host-meta";
164 $ssl_url = $host . "/.well-known/host-meta";
168 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
170 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
173 $curlResult = DI::httpRequest()->get($ssl_url, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
174 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
175 if ($curlResult->isSuccess()) {
176 $xml = $curlResult->getBody();
177 $xrd = XML::parseString($xml, true);
179 $host_url = 'https://' . $host;
183 } elseif ($curlResult->isTimeout()) {
184 Logger::info('Probing timeout', ['url' => $ssl_url]);
185 self::$istimeout = true;
189 if (!is_object($xrd) && !empty($url)) {
190 $curlResult = DI::httpRequest()->get($url, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
191 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
192 if ($curlResult->isTimeout()) {
193 Logger::info('Probing timeout', ['url' => $url]);
194 self::$istimeout = true;
196 } elseif ($connection_error && $ssl_connection_error) {
197 self::$istimeout = true;
201 $xml = $curlResult->getBody();
202 $xrd = XML::parseString($xml, true);
203 $host_url = 'http://'.$host;
205 if (!is_object($xrd)) {
206 Logger::info('No xrd object found', ['host' => $host]);
210 $links = XML::elementToArray($xrd);
211 if (!isset($links["xrd"]["link"])) {
212 Logger::info('No xrd data found', ['host' => $host]);
218 foreach ($links["xrd"]["link"] as $value => $link) {
219 if (!empty($link["@attributes"])) {
220 $attributes = $link["@attributes"];
221 } elseif ($value == "@attributes") {
227 if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
228 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
230 $lrdd[$type] = $attributes["template"];
234 self::$baseurl = $host_url;
236 Logger::info('Probing successful', ['host' => $host]);
242 * Perform Webfinger lookup and return DFRN data
244 * Given an email style address, perform webfinger lookup and
245 * return the resulting DFRN profile URL, or if no DFRN profile URL
246 * is located, returns an OStatus subscription template (prefixed
247 * with the string 'stat:' to identify it as on OStatus template).
248 * If this isn't an email style address just return $webbie.
249 * Return an empty string if email-style addresses but webfinger fails,
250 * or if the resultant personal XRD doesn't contain a supported
251 * subscription/friend-request attribute.
253 * amended 7/9/2011 to return an hcard which could save potentially loading
254 * a lengthy content page to scrape dfrn attributes
256 * @param string $webbie Address that should be probed
257 * @param string $hcard_url Link to the hcard - is returned by reference
259 * @return string profile link
260 * @throws HTTPException\InternalServerErrorException
262 public static function webfingerDfrn(string $webbie, string &$hcard_url)
266 $links = self::lrdd($webbie);
267 Logger::debug('Result', ['url' => $webbie, 'links' => $links]);
268 if (!empty($links) && is_array($links)) {
269 foreach ($links as $link) {
270 if ($link['@attributes']['rel'] === ActivityNamespace::DFRN) {
271 $profile_link = $link['@attributes']['href'];
273 if (($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) && ($profile_link == "")) {
274 $profile_link = 'stat:'.$link['@attributes']['template'];
276 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
277 $hcard_url = $link['@attributes']['href'];
281 return $profile_link;
285 * Check an URI for LRDD data
287 * @param string $uri Address that should be probed
289 * @return array uri data
290 * @throws HTTPException\InternalServerErrorException
292 public static function lrdd(string $uri)
294 $data = self::getWebfingerArray($uri);
298 $webfinger = $data['webfinger'];
300 if (empty($webfinger["links"])) {
301 Logger::info('No webfinger links found', ['uri' => $uri]);
307 foreach ($webfinger["links"] as $link) {
308 $data[] = ["@attributes" => $link];
311 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
312 foreach ($webfinger["aliases"] as $alias) {
313 $data[] = ["@attributes" =>
323 * Fetch information (protocol endpoints and user information) about a given uri
325 * @param string $uri Address that should be probed
326 * @param string $network Test for this specific network
327 * @param integer $uid User ID for the probe (only used for mails)
328 * @param boolean $cache Use cached values?
330 * @return array uri data
331 * @throws HTTPException\InternalServerErrorException
332 * @throws \ImagickException
334 public static function uri($uri, $network = '', $uid = -1)
336 // Local profiles aren't probed via network
337 if (empty($network) && Contact::isLocal($uri)) {
338 $data = self::localProbe($uri);
348 if (empty($network) || ($network == Protocol::ACTIVITYPUB)) {
349 $ap_profile = ActivityPub::probeProfile($uri);
354 self::$istimeout = false;
356 if ($network != Protocol::ACTIVITYPUB) {
357 $data = self::detect($uri, $network, $uid, $ap_profile);
358 if (!is_array($data)) {
361 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
363 } elseif (!empty($ap_profile)) {
364 $ap_profile['batch'] = '';
365 $data = array_merge($ap_profile, $data);
371 if (!isset($data['url'])) {
375 if (empty($data['photo'])) {
376 $data['photo'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
379 if (empty($data['name'])) {
380 if (!empty($data['nick'])) {
381 $data['name'] = $data['nick'];
384 if (empty($data['name'])) {
385 $data['name'] = $data['url'];
389 if (empty($data['nick'])) {
390 $data['nick'] = strtolower($data['name']);
392 if (strpos($data['nick'], ' ')) {
393 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
397 if (!empty($data['baseurl']) && empty($data['gsid'])) {
398 $data['gsid'] = GServer::getID($data['baseurl']);
401 if (empty($data['network'])) {
402 $data['network'] = Protocol::PHANTOM;
405 // Ensure that local connections always are DFRN
406 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
407 $data['network'] = Protocol::DFRN;
410 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
411 $data['hide'] = self::getHideStatus($data['url']);
414 return self::rearrangeData($data);
419 * Fetches the "hide" status from the profile
421 * @param string $url URL of the profile
423 * @return boolean "hide" status
425 private static function getHideStatus($url)
427 $curlResult = DI::httpRequest()->get($url, false, ['content_length' => 1000000]);
428 if (!$curlResult->isSuccess()) {
432 // If it isn't a HTML file then exit
433 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
437 $body = $curlResult->getBody();
442 $doc = new DOMDocument();
443 @$doc->loadHTML($body);
445 $xpath = new DOMXPath($doc);
447 $list = $xpath->query('//meta[@name]');
448 foreach ($list as $node) {
450 if ($node->attributes->length) {
451 foreach ($node->attributes as $attribute) {
452 $meta_tag[$attribute->name] = $attribute->value;
456 if (empty($meta_tag['content'])) {
460 $content = strtolower(trim($meta_tag['content']));
462 switch (strtolower(trim($meta_tag['name']))) {
463 case 'dfrn-global-visibility':
464 if ($content == 'false') {
469 if (strpos($content, 'noindex') !== false) {
480 * Fetch the "subscribe" and add it to the result
482 * @param array $result
483 * @param array $webfinger
484 * @return array result
486 private static function getSubscribeLink(array $result, array $webfinger)
488 if (empty($webfinger['links'])) {
492 foreach ($webfinger['links'] as $link) {
493 if (!empty($link['template']) && ($link['rel'] === ActivityNamespace::OSTATUSSUB)) {
494 $result['subscribe'] = $link['template'];
502 * Get webfinger data from a given URI
505 * @return array Webfinger array
507 private static function getWebfingerArray(string $uri)
509 $parts = parse_url($uri);
511 if (!empty($parts['scheme']) && !empty($parts['host'])) {
512 $host = $parts['host'];
513 if (!empty($parts['port'])) {
514 $host .= ':'.$parts['port'];
517 $baseurl = $parts['scheme'] . '://' . $host;
522 $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
523 if (!empty($path_parts)) {
524 $nick = ltrim(end($path_parts), '@');
525 // When the last part of the URI is numeric then it is most likely an ID and not a nick name
526 if (!is_numeric($nick)) {
527 $addr = $nick."@".$host;
533 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
534 if (empty($webfinger)) {
535 $lrdd = self::hostMeta($host);
538 if (empty($webfinger) && empty($lrdd)) {
539 while (empty($lrdd) && empty($webfinger) && (sizeof($path_parts) > 1)) {
540 $host .= "/".array_shift($path_parts);
541 $baseurl = $parts['scheme'] . '://' . $host;
544 $addr = $nick."@".$host;
547 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
548 if (empty($webfinger)) {
549 $lrdd = self::hostMeta($host);
553 if (empty($lrdd) && empty($webfinger)) {
557 } elseif (strstr($uri, '@')) {
558 // Remove "acct:" from the URI
559 $uri = str_replace('acct:', '', $uri);
561 $host = substr($uri, strpos($uri, '@') + 1);
562 $nick = substr($uri, 0, strpos($uri, '@'));
565 $webfinger = self::getWebfinger('https://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
566 if (self::$istimeout) {
570 if (empty($webfinger)) {
571 $webfinger = self::getWebfinger('http://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
572 if (self::$istimeout) {
576 $baseurl = 'https://' . $host;
579 if (empty($webfinger)) {
580 $lrdd = self::hostMeta($host);
581 if (self::$istimeout) {
584 $baseurl = self::$baseurl;
586 $baseurl = 'http://' . $host;
589 Logger::info('URI was not detectable', ['uri' => $uri]);
593 if (empty($webfinger)) {
594 foreach ($lrdd as $type => $template) {
599 $webfinger = self::getWebfinger($template, $type, $uri, $addr);
603 if (empty($webfinger)) {
607 if ($webfinger['detected'] == $addr) {
608 $webfinger['nick'] = $nick;
609 $webfinger['addr'] = $addr;
612 $webfinger['baseurl'] = $baseurl;
618 * Perform network request for webfinger data
620 * @param string $template
621 * @param string $type
623 * @param string $addr
624 * @return array webfinger results
626 private static function getWebfinger(string $template, string $type, string $uri, string $addr)
628 // First try the address because this is the primary purpose of webfinger
631 $path = str_replace('{uri}', urlencode("acct:" . $addr), $template);
632 $webfinger = self::webfinger($path, $type);
633 if (self::$istimeout) {
639 if (empty($webfinger) && $uri != $addr) {
641 $path = str_replace('{uri}', urlencode($uri), $template);
642 $webfinger = self::webfinger($path, $type);
643 if (self::$istimeout) {
648 if (empty($webfinger)) {
652 return ['webfinger' => $webfinger, 'detected' => $detected];
656 * Fetch information (protocol endpoints and user information) about a given uri
658 * This function is only called by the "uri" function that adds caching and rearranging of data.
660 * @param string $uri Address that should be probed
661 * @param string $network Test for this specific network
662 * @param integer $uid User ID for the probe (only used for mails)
663 * @param array $ap_profile Previously probed AP profile
665 * @return array uri data
666 * @throws HTTPException\InternalServerErrorException
668 private static function detect(string $uri, string $network, int $uid, array $ap_profile)
672 'network' => $network,
677 Hook::callAll('probe_detect', $hookData);
679 if ($hookData['result']) {
680 if (!is_array($hookData['result'])) {
683 return $hookData['result'];
687 $parts = parse_url($uri);
689 if (!empty($parts['scheme']) && !empty($parts['host'])) {
690 if (in_array($parts['host'], ['twitter.com', 'mobile.twitter.com'])) {
691 return self::twitter($uri);
693 } elseif (strstr($uri, '@')) {
694 // If the URI starts with "mailto:" then jump directly to the mail detection
695 if (strpos($uri, 'mailto:') !== false) {
696 $uri = str_replace('mailto:', '', $uri);
697 return self::mail($uri, $uid);
700 if ($network == Protocol::MAIL) {
701 return self::mail($uri, $uid);
704 if (Strings::endsWith($uri, '@twitter.com')
705 || Strings::endsWith($uri, '@mobile.twitter.com')
707 return self::twitter($uri);
710 Logger::info('URI was not detectable', ['uri' => $uri]);
714 Logger::info('Probing start', ['uri' => $uri]);
716 if (!empty($ap_profile['addr']) && ($ap_profile['addr'] != $uri)) {
717 $data = self::getWebfingerArray($ap_profile['addr']);
721 $data = self::getWebfingerArray($uri);
725 if (!empty($parts['scheme'])) {
726 return self::feed($uri);
727 } elseif (!empty($uid)) {
728 return self::mail($uri, $uid);
734 $webfinger = $data['webfinger'];
735 $nick = $data['nick'] ?? '';
736 $addr = $data['addr'] ?? '';
737 $baseurl = $data['baseurl'] ?? '';
741 if (in_array($network, ["", Protocol::DFRN])) {
742 $result = self::dfrn($webfinger);
744 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
745 $result = self::diaspora($webfinger);
747 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
748 $result = self::ostatus($webfinger);
750 if (in_array($network, ['', Protocol::ZOT])) {
751 $result = self::zot($webfinger, $result, $baseurl);
753 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
754 $result = self::pumpio($webfinger, $addr);
756 if (empty($result['network']) && empty($ap_profile['network']) || ($network == Protocol::FEED)) {
757 $result = self::feed($uri);
759 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
760 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
761 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
762 $result["nick"] = $nick;
765 if (empty($result["addr"]) && ($addr != "")) {
766 $result["addr"] = $addr;
770 $result = self::getSubscribeLink($result, $webfinger);
772 if (empty($result["network"])) {
773 $result["network"] = Protocol::PHANTOM;
776 if (empty($result['baseurl']) && !empty($baseurl)) {
777 $result['baseurl'] = $baseurl;
780 if (empty($result["url"])) {
781 $result["url"] = $uri;
784 Logger::info('Probing done', ['uri' => $uri, 'network' => $result["network"]]);
790 * Check for Zot contact
792 * @param array $webfinger Webfinger data
793 * @param array $data previously probed data
795 * @return array Zot data
796 * @throws HTTPException\InternalServerErrorException
798 private static function zot($webfinger, $data, $baseurl)
800 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
801 foreach ($webfinger["aliases"] as $alias) {
802 if (substr($alias, 0, 5) == 'acct:') {
803 $data["addr"] = substr($alias, 5);
808 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
809 $data["addr"] = substr($webfinger["subject"], 5);
813 foreach ($webfinger['links'] as $link) {
814 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
815 $zot_url = $link['href'];
819 if (empty($zot_url) && !empty($data['addr']) && !empty($baseurl)) {
820 $condition = ['nurl' => Strings::normaliseLink($baseurl), 'platform' => ['hubzilla']];
821 if (!DBA::exists('gserver', $condition)) {
824 $zot_url = $baseurl . '/.well-known/zot-info?address=' . $data['addr'];
827 if (empty($zot_url)) {
831 $data = self::pollZot($zot_url, $data);
833 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
834 foreach ($webfinger['aliases'] as $alias) {
835 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
836 $data['alias'] = $alias;
844 public static function pollZot($url, $data)
846 $curlResult = DI::httpRequest()->get($url);
847 if ($curlResult->isTimeout()) {
850 $content = $curlResult->getBody();
855 $json = json_decode($content, true);
856 if (!is_array($json)) {
860 if (empty($data['network'])) {
861 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
862 $data['network'] = Protocol::ZOT;
863 } elseif (!isset($json['protocols'])) {
864 $data['network'] = Protocol::ZOT;
868 if (!empty($json['guid']) && empty($data['guid'])) {
869 $data['guid'] = $json['guid'];
871 if (!empty($json['key']) && empty($data['pubkey'])) {
872 $data['pubkey'] = $json['key'];
874 if (!empty($json['name'])) {
875 $data['name'] = $json['name'];
877 if (!empty($json['photo'])) {
878 $data['photo'] = $json['photo'];
879 if (!empty($json['photo_updated'])) {
880 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
883 if (!empty($json['address'])) {
884 $data['addr'] = $json['address'];
886 if (!empty($json['url'])) {
887 $data['url'] = $json['url'];
889 if (!empty($json['connections_url'])) {
890 $data['poco'] = $json['connections_url'];
892 if (isset($json['searchable'])) {
893 $data['hide'] = !$json['searchable'];
895 if (!empty($json['public_forum'])) {
896 $data['community'] = $json['public_forum'];
897 $data['account-type'] = User::PAGE_FLAGS_COMMUNITY;
900 if (!empty($json['profile'])) {
901 $profile = $json['profile'];
902 if (!empty($profile['description'])) {
903 $data['about'] = $profile['description'];
905 if (!empty($profile['keywords'])) {
906 $keywords = implode(', ', $profile['keywords']);
907 if (!empty($keywords)) {
908 $data['keywords'] = $keywords;
913 if (!empty($profile['region'])) {
914 $loc['region'] = $profile['region'];
916 if (!empty($profile['country'])) {
917 $loc['country-name'] = $profile['country'];
919 $location = Profile::formatLocation($loc);
920 if (!empty($location)) {
921 $data['location'] = $location;
929 * Perform a webfinger request.
931 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
933 * @param string $url Address that should be probed
934 * @param string $type type
936 * @return array webfinger data
937 * @throws HTTPException\InternalServerErrorException
939 public static function webfinger($url, $type)
941 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
943 $curlResult = DI::httpRequest()->get($url, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
944 if ($curlResult->isTimeout()) {
945 self::$istimeout = true;
948 $data = $curlResult->getBody();
950 $webfinger = json_decode($data, true);
951 if (!empty($webfinger)) {
952 if (!isset($webfinger["links"])) {
953 Logger::info('No json webfinger links', ['url' => $url]);
959 // If it is not JSON, maybe it is XML
960 $xrd = XML::parseString($data, true);
961 if (!is_object($xrd)) {
962 Logger::info('No webfinger data retrievable', ['url' => $url]);
966 $xrd_arr = XML::elementToArray($xrd);
967 if (!isset($xrd_arr["xrd"]["link"])) {
968 Logger::info('No XML webfinger links', ['url' => $url]);
974 if (!empty($xrd_arr["xrd"]["subject"])) {
975 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
978 if (!empty($xrd_arr["xrd"]["alias"])) {
979 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
982 $webfinger["links"] = [];
984 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
985 if (!empty($data["@attributes"])) {
986 $attributes = $data["@attributes"];
987 } elseif ($value == "@attributes") {
993 $webfinger["links"][] = $attributes;
999 * Poll the Friendica specific noscrape page.
1001 * "noscrape" is a faster alternative to fetch the data from the hcard.
1002 * This functionality was originally created for the directory.
1004 * @param string $noscrape_url Link to the noscrape page
1005 * @param array $data The already fetched data
1007 * @return array noscrape data
1008 * @throws HTTPException\InternalServerErrorException
1010 private static function pollNoscrape($noscrape_url, $data)
1012 $curlResult = DI::httpRequest()->get($noscrape_url);
1013 if ($curlResult->isTimeout()) {
1014 self::$istimeout = true;
1017 $content = $curlResult->getBody();
1019 Logger::info('Empty body', ['url' => $noscrape_url]);
1023 $json = json_decode($content, true);
1024 if (!is_array($json)) {
1025 Logger::info('No json data', ['url' => $noscrape_url]);
1029 if (!empty($json["fn"])) {
1030 $data["name"] = $json["fn"];
1033 if (!empty($json["addr"])) {
1034 $data["addr"] = $json["addr"];
1037 if (!empty($json["nick"])) {
1038 $data["nick"] = $json["nick"];
1041 if (!empty($json["guid"])) {
1042 $data["guid"] = $json["guid"];
1045 if (!empty($json["comm"])) {
1046 $data["community"] = $json["comm"];
1049 if (!empty($json["tags"])) {
1050 $keywords = implode(", ", $json["tags"]);
1051 if ($keywords != "") {
1052 $data["keywords"] = $keywords;
1056 $location = Profile::formatLocation($json);
1058 $data["location"] = $location;
1061 if (!empty($json["about"])) {
1062 $data["about"] = $json["about"];
1065 if (!empty($json["xmpp"])) {
1066 $data["xmpp"] = $json["xmpp"];
1069 if (!empty($json["matrix"])) {
1070 $data["matrix"] = $json["matrix"];
1073 if (!empty($json["key"])) {
1074 $data["pubkey"] = $json["key"];
1077 if (!empty($json["photo"])) {
1078 $data["photo"] = $json["photo"];
1081 if (!empty($json["dfrn-request"])) {
1082 $data["request"] = $json["dfrn-request"];
1085 if (!empty($json["dfrn-confirm"])) {
1086 $data["confirm"] = $json["dfrn-confirm"];
1089 if (!empty($json["dfrn-notify"])) {
1090 $data["notify"] = $json["dfrn-notify"];
1093 if (!empty($json["dfrn-poll"])) {
1094 $data["poll"] = $json["dfrn-poll"];
1097 if (isset($json["hide"])) {
1098 $data["hide"] = (bool)$json["hide"];
1100 $data["hide"] = false;
1107 * Check for valid DFRN data
1109 * @param array $data DFRN data
1111 * @return int Number of errors
1113 public static function validDfrn($data)
1116 if (!isset($data['key'])) {
1119 if (!isset($data['dfrn-request'])) {
1122 if (!isset($data['dfrn-confirm'])) {
1125 if (!isset($data['dfrn-notify'])) {
1128 if (!isset($data['dfrn-poll'])) {
1135 * Fetch data from a DFRN profile page and via "noscrape"
1137 * @param string $profile_link Link to the profile page
1139 * @return array profile data
1140 * @throws HTTPException\InternalServerErrorException
1141 * @throws \ImagickException
1143 public static function profile($profile_link)
1147 Logger::info('Check profile', ['link' => $profile_link]);
1149 // Fetch data via noscrape - this is faster
1150 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1151 $data = self::pollNoscrape($noscrape_url, $data);
1153 if (!isset($data["notify"])
1154 || !isset($data["confirm"])
1155 || !isset($data["request"])
1156 || !isset($data["poll"])
1157 || !isset($data["name"])
1158 || !isset($data["photo"])
1160 $data = self::pollHcard($profile_link, $data, true);
1165 if (empty($data["addr"]) || empty($data["nick"])) {
1166 $probe_data = self::uri($profile_link);
1167 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1168 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1171 $prof_data["addr"] = $data["addr"];
1172 $prof_data["nick"] = $data["nick"];
1173 $prof_data["dfrn-request"] = $data['request'] ?? null;
1174 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1175 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1176 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1177 $prof_data["photo"] = $data['photo'] ?? null;
1178 $prof_data["fn"] = $data['name'] ?? null;
1179 $prof_data["key"] = $data['pubkey'] ?? null;
1181 Logger::debug('Result', ['link' => $profile_link, 'data' => $prof_data]);
1187 * Check for DFRN contact
1189 * @param array $webfinger Webfinger data
1191 * @return array DFRN data
1192 * @throws HTTPException\InternalServerErrorException
1194 private static function dfrn($webfinger)
1198 // The array is reversed to take into account the order of preference for same-rel links
1199 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1200 foreach (array_reverse($webfinger["links"]) as $link) {
1201 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1202 $data["network"] = Protocol::DFRN;
1203 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1204 $data["poll"] = $link["href"];
1205 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1206 $data["url"] = $link["href"];
1207 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1208 $hcard_url = $link["href"];
1209 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1210 $data["poco"] = $link["href"];
1211 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1212 $data["photo"] = $link["href"];
1213 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1214 $data["baseurl"] = trim($link["href"], '/');
1215 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1216 $data["guid"] = $link["href"];
1217 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1218 $data["pubkey"] = base64_decode($link["href"]);
1220 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1221 if (strstr($data["pubkey"], 'RSA ')) {
1222 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1227 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1228 foreach ($webfinger["aliases"] as $alias) {
1229 if (empty($data["url"]) && !strstr($alias, "@")) {
1230 $data["url"] = $alias;
1231 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1232 $data["alias"] = $alias;
1233 } elseif (substr($alias, 0, 5) == 'acct:') {
1234 $data["addr"] = substr($alias, 5);
1239 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1240 $data["addr"] = substr($webfinger["subject"], 5);
1243 if (!isset($data["network"]) || ($hcard_url == "")) {
1247 // Fetch data via noscrape - this is faster
1248 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1249 $data = self::pollNoscrape($noscrape_url, $data);
1251 if (isset($data["notify"])
1252 && isset($data["confirm"])
1253 && isset($data["request"])
1254 && isset($data["poll"])
1255 && isset($data["name"])
1256 && isset($data["photo"])
1261 $data = self::pollHcard($hcard_url, $data, true);
1267 * Poll the hcard page (Diaspora and Friendica specific)
1269 * @param string $hcard_url Link to the hcard page
1270 * @param array $data The already fetched data
1271 * @param boolean $dfrn Poll DFRN specific data
1273 * @return array hcard data
1274 * @throws HTTPException\InternalServerErrorException
1276 private static function pollHcard($hcard_url, $data, $dfrn = false)
1278 $curlResult = DI::httpRequest()->get($hcard_url);
1279 if ($curlResult->isTimeout()) {
1280 self::$istimeout = true;
1283 $content = $curlResult->getBody();
1284 if (empty($content)) {
1288 $doc = new DOMDocument();
1289 if (!@$doc->loadHTML($content)) {
1293 $xpath = new DomXPath($doc);
1295 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1296 if (!is_object($vcards)) {
1300 if (!isset($data["baseurl"])) {
1301 $data["baseurl"] = "";
1304 if ($vcards->length > 0) {
1305 $vcard = $vcards->item(0);
1307 // We have to discard the guid from the hcard in favour of the guid from lrdd
1308 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1309 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1310 if (($search->length > 0) && empty($data["guid"])) {
1311 $data["guid"] = $search->item(0)->nodeValue;
1314 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1315 if ($search->length > 0) {
1316 $data["nick"] = $search->item(0)->nodeValue;
1319 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1320 if ($search->length > 0) {
1321 $data["name"] = $search->item(0)->nodeValue;
1324 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1325 if ($search->length > 0) {
1326 $data["searchable"] = $search->item(0)->nodeValue;
1329 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1330 if ($search->length > 0) {
1331 $data["pubkey"] = $search->item(0)->nodeValue;
1332 if (strstr($data["pubkey"], 'RSA ')) {
1333 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1337 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1338 if ($search->length > 0) {
1339 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1344 if (!empty($vcard)) {
1345 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1346 foreach ($photos as $photo) {
1348 foreach ($photo->attributes as $attribute) {
1349 $attr[$attribute->name] = trim($attribute->value);
1352 if (isset($attr["src"]) && isset($attr["width"])) {
1353 $avatar[$attr["width"]] = $attr["src"];
1356 // We don't have a width. So we just take everything that we got.
1357 // This is a Hubzilla workaround which doesn't send a width.
1358 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1359 $avatar[] = $attr["src"];
1364 if (sizeof($avatar)) {
1366 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1370 // Poll DFRN specific data
1371 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1372 if ($search->length > 0) {
1373 foreach ($search as $link) {
1374 //$data["request"] = $search->item(0)->nodeValue;
1376 foreach ($link->attributes as $attribute) {
1377 $attr[$attribute->name] = trim($attribute->value);
1380 $data[substr($attr["rel"], 5)] = $attr["href"];
1384 // Older Friendica versions had used the "uid" field differently than newer versions
1385 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1386 unset($data["guid"]);
1395 * Check for Diaspora contact
1397 * @param array $webfinger Webfinger data
1399 * @return array Diaspora data
1400 * @throws HTTPException\InternalServerErrorException
1402 private static function diaspora($webfinger)
1407 // The array is reversed to take into account the order of preference for same-rel links
1408 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1409 foreach (array_reverse($webfinger["links"]) as $link) {
1410 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1411 $hcard_url = $link["href"];
1412 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1413 $data["baseurl"] = trim($link["href"], '/');
1414 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1415 $data["guid"] = $link["href"];
1416 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1417 $data["url"] = $link["href"];
1418 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && empty($link["type"]) && !empty($link["href"])) {
1419 $profile_url = $link["href"];
1420 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1421 $data["poll"] = $link["href"];
1422 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1423 $data["poco"] = $link["href"];
1424 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1425 $data["notify"] = $link["href"];
1426 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1427 $data["pubkey"] = base64_decode($link["href"]);
1429 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1430 if (strstr($data["pubkey"], 'RSA ')) {
1431 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1436 if (empty($data["url"]) && !empty($profile_url)) {
1437 $data["url"] = $profile_url;
1440 if (empty($data["url"]) || empty($hcard_url)) {
1444 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1445 foreach ($webfinger["aliases"] as $alias) {
1446 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1447 $data["alias"] = $alias;
1448 } elseif (substr($alias, 0, 5) == 'acct:') {
1449 $data["addr"] = substr($alias, 5);
1454 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1455 $data["addr"] = substr($webfinger["subject"], 5);
1458 // Fetch further information from the hcard
1459 $data = self::pollHcard($hcard_url, $data);
1465 if (!empty($data["url"])
1466 && !empty($data["guid"])
1467 && !empty($data["baseurl"])
1468 && !empty($data["pubkey"])
1469 && !empty($hcard_url)
1471 $data["network"] = Protocol::DIASPORA;
1472 $data["manually-approve"] = false;
1474 // The Diaspora handle must always be lowercase
1475 if (!empty($data["addr"])) {
1476 $data["addr"] = strtolower($data["addr"]);
1479 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1480 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1481 $data["batch"] = $data["baseurl"] . "/receive/public";
1490 * Check for OStatus contact
1492 * @param array $webfinger Webfinger data
1493 * @param bool $short Short detection mode
1495 * @return array|bool OStatus data or "false" on error or "true" on short mode
1496 * @throws HTTPException\InternalServerErrorException
1498 private static function ostatus($webfinger, $short = false)
1502 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1503 foreach ($webfinger["aliases"] as $alias) {
1504 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1505 $data["addr"] = str_replace('acct:', '', $alias);
1510 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1511 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1513 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1516 if (!empty($webfinger["links"])) {
1517 // The array is reversed to take into account the order of preference for same-rel links
1518 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1519 foreach (array_reverse($webfinger["links"]) as $link) {
1520 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1521 && (($link["type"] ?? "") == "text/html")
1522 && ($link["href"] != "")
1524 $data["url"] = $data["alias"] = $link["href"];
1525 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1526 $data["notify"] = $link["href"];
1527 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1528 $data["poll"] = $link["href"];
1529 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1530 $pubkey = $link["href"];
1532 if (substr($pubkey, 0, 5) === 'data:') {
1533 if (strstr($pubkey, ',')) {
1534 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1536 $pubkey = substr($pubkey, 5);
1538 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1539 $curlResult = DI::httpRequest()->get($pubkey);
1540 if ($curlResult->isTimeout()) {
1541 self::$istimeout = true;
1542 return $short ? false : [];
1544 $pubkey = $curlResult->getBody();
1547 $key = explode(".", $pubkey);
1549 if (sizeof($key) >= 3) {
1550 $m = Strings::base64UrlDecode($key[1]);
1551 $e = Strings::base64UrlDecode($key[2]);
1552 $data["pubkey"] = Crypto::meToPem($m, $e);
1558 if (isset($data["notify"]) && isset($data["pubkey"])
1559 && isset($data["poll"])
1560 && isset($data["url"])
1562 $data["network"] = Protocol::OSTATUS;
1563 $data["manually-approve"] = false;
1565 return $short ? false : [];
1572 // Fetch all additional data from the feed
1573 $curlResult = DI::httpRequest()->get($data["poll"]);
1574 if ($curlResult->isTimeout()) {
1575 self::$istimeout = true;
1578 $feed = $curlResult->getBody();
1579 $feed_data = Feed::import($feed);
1584 if (!empty($feed_data["header"]["author-name"])) {
1585 $data["name"] = $feed_data["header"]["author-name"];
1587 if (!empty($feed_data["header"]["author-nick"])) {
1588 $data["nick"] = $feed_data["header"]["author-nick"];
1590 if (!empty($feed_data["header"]["author-avatar"])) {
1591 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1593 if (!empty($feed_data["header"]["author-id"])) {
1594 $data["alias"] = $feed_data["header"]["author-id"];
1596 if (!empty($feed_data["header"]["author-location"])) {
1597 $data["location"] = $feed_data["header"]["author-location"];
1599 if (!empty($feed_data["header"]["author-about"])) {
1600 $data["about"] = $feed_data["header"]["author-about"];
1602 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1603 // So we take the value that we just fetched, although the other one worked as well
1604 if (!empty($feed_data["header"]["author-link"])) {
1605 $data["url"] = $feed_data["header"]["author-link"];
1608 if ($data["url"] == $data["alias"]) {
1609 $data["alias"] = '';
1612 /// @todo Fetch location and "about" from the feed as well
1617 * Fetch data from a pump.io profile page
1619 * @param string $profile_link Link to the profile page
1621 * @return array profile data
1623 private static function pumpioProfileData($profile_link)
1625 $curlResult = DI::httpRequest()->get($profile_link);
1626 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
1630 $doc = new DOMDocument();
1631 if (!@$doc->loadHTML($curlResult->getBody())) {
1635 $xpath = new DomXPath($doc);
1639 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1641 if ($data["name"] == '') {
1642 // This is ugly - but pump.io doesn't seem to know a better way for it
1643 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1644 $pos = strpos($data["name"], chr(10));
1646 $data["name"] = trim(substr($data["name"], 0, $pos));
1650 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1652 if ($data["location"] == '') {
1653 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1656 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1658 if ($data["about"] == '') {
1659 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1662 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1664 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1667 foreach ($avatar->attributes as $attribute) {
1668 if ($attribute->name == "src") {
1669 $data["photo"] = trim($attribute->value);
1678 * Check for pump.io contact
1680 * @param array $webfinger Webfinger data
1681 * @param string $addr
1682 * @return array pump.io data
1684 private static function pumpio($webfinger, $addr)
1687 // The array is reversed to take into account the order of preference for same-rel links
1688 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1689 foreach (array_reverse($webfinger["links"]) as $link) {
1690 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1691 && (($link["type"] ?? "") == "text/html")
1692 && ($link["href"] != "")
1694 $data["url"] = $link["href"];
1695 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1696 $data["notify"] = $link["href"];
1697 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1698 $data["poll"] = $link["href"];
1699 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1700 $data["dialback"] = $link["href"];
1703 if (isset($data["poll"]) && isset($data["notify"])
1704 && isset($data["dialback"])
1705 && isset($data["url"])
1707 // by now we use these fields only for the network type detection
1708 // So we unset all data that isn't used at the moment
1709 unset($data["dialback"]);
1711 $data["network"] = Protocol::PUMPIO;
1716 $profile_data = self::pumpioProfileData($data["url"]);
1718 if (!$profile_data) {
1722 $data = array_merge($data, $profile_data);
1724 if (($addr != '') && ($data['name'] != '')) {
1725 $name = trim(str_replace($addr, '', $data['name']));
1727 $data['name'] = $name;
1735 * Check for twitter contact
1737 * @param string $uri
1739 * @return array twitter data
1741 private static function twitter($uri)
1743 if (preg_match('=([^@]+)@(?:mobile\.)?twitter\.com$=i', $uri, $matches)) {
1744 $nick = $matches[1];
1745 } elseif (preg_match('=^https?://(?:mobile\.)?twitter\.com/(.+)=i', $uri, $matches)) {
1746 $nick = $matches[1];
1752 $data['url'] = 'https://twitter.com/' . $nick;
1753 $data['addr'] = $nick . '@twitter.com';
1754 $data['nick'] = $data['name'] = $nick;
1755 $data['network'] = Protocol::TWITTER;
1756 $data['baseurl'] = 'https://twitter.com';
1762 * Checks HTML page for RSS feed link
1764 * @param string $url Page link
1765 * @param string $body Page body string
1766 * @return string|false Feed link or false if body was invalid HTML document
1768 public static function getFeedLink(string $url, string $body)
1774 $doc = new DOMDocument();
1775 if (!@$doc->loadHTML($body)) {
1779 $xpath = new DOMXPath($doc);
1781 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1783 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1789 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1791 * Loosely based on RFC 1808
1793 * @see https://tools.ietf.org/html/rfc1808
1795 * @param string $href The potential relative href found in the HTML document
1796 * @param string $base The HTML document URL
1797 * @param DOMXPath $xpath The HTML document XPath
1800 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath)
1802 if (filter_var($href, FILTER_VALIDATE_URL)) {
1806 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1808 $baseParts = parse_url($base);
1809 if (empty($baseParts['host'])) {
1813 // Naked domain case (scheme://basehost)
1814 $path = $baseParts['path'] ?? '/';
1816 // Remove the filename part of the path if it exists (/base/path/file)
1817 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1819 $hrefParts = parse_url($href);
1821 if (!empty($hrefParts['path'])) {
1822 // Root path case (/path) including relative scheme case (//host/path)
1823 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1824 $path = $hrefParts['path'];
1826 $path = $path . '/' . $hrefParts['path'];
1828 // Resolve arbitrary relative path
1829 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1830 $parts = array_filter(explode('/', $path), 'strlen');
1831 $absolutes = array();
1832 foreach ($parts as $part) {
1833 if ('.' == $part) continue;
1834 if ('..' == $part) {
1835 array_pop($absolutes);
1837 $absolutes[] = $part;
1841 $path = '/' . implode('/', $absolutes);
1845 // Relative scheme case (//host/path)
1846 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1847 $baseParts['path'] = $path;
1848 unset($baseParts['query']);
1849 unset($baseParts['fragment']);
1851 return Network::unparseURL($baseParts);
1855 * Check for feed contact
1857 * @param string $url Profile link
1858 * @param boolean $probe Do a probe if the page contains a feed link
1860 * @return array feed data
1861 * @throws HTTPException\InternalServerErrorException
1863 private static function feed($url, $probe = true)
1865 $curlResult = DI::httpRequest()->get($url);
1866 if ($curlResult->isTimeout()) {
1867 self::$istimeout = true;
1870 $feed = $curlResult->getBody();
1871 $feed_data = Feed::import($feed);
1878 $feed_url = self::getFeedLink($url, $feed);
1884 return self::feed($feed_url, false);
1887 if (!empty($feed_data["header"]["author-name"])) {
1888 $data["name"] = $feed_data["header"]["author-name"];
1891 if (!empty($feed_data["header"]["author-nick"])) {
1892 $data["nick"] = $feed_data["header"]["author-nick"];
1895 if (!empty($feed_data["header"]["author-avatar"])) {
1896 $data["photo"] = $feed_data["header"]["author-avatar"];
1899 if (!empty($feed_data["header"]["author-id"])) {
1900 $data["alias"] = $feed_data["header"]["author-id"];
1903 $data["url"] = $url;
1904 $data["poll"] = $url;
1906 $data["network"] = Protocol::FEED;
1912 * Check for mail contact
1914 * @param string $uri Profile link
1915 * @param integer $uid User ID
1917 * @return array mail data
1918 * @throws \Exception
1920 private static function mail($uri, $uid)
1922 if (!Network::isEmailDomainValid($uri)) {
1930 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1932 $condition = ["`uid` = ? AND `server` != ''", $uid];
1933 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1934 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1936 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1940 $mailbox = Email::constructMailboxName($mailacct);
1942 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1943 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1948 $msgs = Email::poll($mbox, $uri);
1949 Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
1951 if (!count($msgs)) {
1955 $phost = substr($uri, strpos($uri, '@') + 1);
1958 $data["addr"] = $uri;
1959 $data["network"] = Protocol::MAIL;
1960 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1961 $data["nick"] = $data["name"];
1962 $data["photo"] = Network::lookupAvatarByEmail($uri);
1963 $data["url"] = 'mailto:'.$uri;
1964 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1965 $data["poll"] = 'email ' . Strings::getRandomHex();
1967 $x = Email::messageMeta($mbox, $msgs[0]);
1968 if (stristr($x[0]->from, $uri)) {
1969 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1970 } elseif (stristr($x[0]->to, $uri)) {
1971 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1974 foreach ($adr as $feadr) {
1975 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1976 &&(strcasecmp($feadr->host, $phost) == 0)
1977 && (strlen($feadr->personal))
1979 $personal = imap_mime_header_decode($feadr->personal);
1981 foreach ($personal as $perspart) {
1982 if ($perspart->charset != "default") {
1983 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1985 $data["name"] .= $perspart->text;
1989 $data["name"] = Strings::escapeTags($data["name"]);
1993 if (!empty($mbox)) {
2000 * Mix two paths together to possibly fix missing parts
2002 * @param string $avatar Path to the avatar
2003 * @param string $base Another path that is hopefully complete
2005 * @return string fixed avatar path
2006 * @throws \Exception
2008 public static function fixAvatar($avatar, $base)
2010 $base_parts = parse_url($base);
2012 // Remove all parts that could create a problem
2013 unset($base_parts['path']);
2014 unset($base_parts['query']);
2015 unset($base_parts['fragment']);
2017 $avatar_parts = parse_url($avatar);
2020 $parts = array_merge($base_parts, $avatar_parts);
2022 // And put them together again
2023 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
2024 $host = isset($parts['host']) ? $parts['host'] : '';
2025 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
2026 $path = isset($parts['path']) ? $parts['path'] : '';
2027 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
2028 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
2030 $fixed = $scheme.$host.$port.$path.$query.$fragment;
2032 Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
2038 * Fetch the last date that the contact had posted something (publically)
2040 * @param string $data probing result
2041 * @return string last activity
2043 public static function getLastUpdate(array $data)
2045 $uid = User::getIdForURL($data['url']);
2047 $contact = Contact::selectFirst(['url', 'last-item'], ['self' => true, 'uid' => $uid]);
2048 if (!empty($contact['last-item'])) {
2049 return $contact['last-item'];
2053 if ($lastUpdate = self::updateFromNoScrape($data)) {
2057 if (!empty($data['outbox'])) {
2058 return self::updateFromOutbox($data['outbox'], $data);
2059 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
2060 return self::updateFromOutbox($data['poll'], $data);
2061 } elseif (!empty($data['poll'])) {
2062 return self::updateFromFeed($data);
2069 * Fetch the last activity date from the "noscrape" endpoint
2071 * @param array $data Probing result
2072 * @return string last activity
2074 * @return bool 'true' if update was successful or the server was unreachable
2076 private static function updateFromNoScrape(array $data)
2078 if (empty($data['baseurl'])) {
2082 // Check the 'noscrape' endpoint when it is a Friendica server
2083 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
2084 Strings::normaliseLink($data['baseurl'])]);
2085 if (!DBA::isResult($gserver)) {
2089 $curlResult = DI::httpRequest()->get($gserver['noscrape'] . '/' . $data['nick']);
2091 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
2092 $noscrape = json_decode($curlResult->getBody(), true);
2093 if (!empty($noscrape) && !empty($noscrape['updated'])) {
2094 return DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2102 * Fetch the last activity date from an ActivityPub Outbox
2104 * @param string $feed
2105 * @param array $data Probing result
2106 * @return string last activity
2107 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2109 private static function updateFromOutbox(string $feed, array $data)
2111 $outbox = ActivityPub::fetchContent($feed);
2112 if (empty($outbox)) {
2116 if (!empty($outbox['orderedItems'])) {
2117 $items = $outbox['orderedItems'];
2118 } elseif (!empty($outbox['first']['orderedItems'])) {
2119 $items = $outbox['first']['orderedItems'];
2120 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2121 return self::updateFromOutbox($outbox['first']['href'], $data);
2122 } elseif (!empty($outbox['first'])) {
2123 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2124 return self::updateFromOutbox($outbox['first'], $data);
2126 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2134 foreach ($items as $activity) {
2135 if (!empty($activity['published'])) {
2136 $published = DateTimeFormat::utc($activity['published']);
2137 } elseif (!empty($activity['object']['published'])) {
2138 $published = DateTimeFormat::utc($activity['object']['published']);
2143 if ($last_updated < $published) {
2144 $last_updated = $published;
2148 if (!empty($last_updated)) {
2149 return $last_updated;
2156 * Fetch the last activity date from an XML feed
2158 * @param array $data Probing result
2159 * @return string last activity
2161 private static function updateFromFeed(array $data)
2163 // Search for the newest entry in the feed
2164 $curlResult = DI::httpRequest()->get($data['poll']);
2165 if (!$curlResult->isSuccess() || !$curlResult->getBody()) {
2169 $doc = new DOMDocument();
2170 @$doc->loadXML($curlResult->getBody());
2172 $xpath = new DOMXPath($doc);
2173 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2175 $entries = $xpath->query('/atom:feed/atom:entry');
2179 foreach ($entries as $entry) {
2180 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2181 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
2182 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2183 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2185 if (empty($published) || empty($updated)) {
2186 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2190 if ($last_updated < $published) {
2191 $last_updated = $published;
2194 if ($last_updated < $updated) {
2195 $last_updated = $updated;
2199 if (!empty($last_updated)) {
2200 return $last_updated;
2207 * Probe data from local profiles without network traffic
2209 * @param string $url
2210 * @return array probed data
2211 * @throws HTTPException\InternalServerErrorException
2212 * @throws HTTPException\NotFoundException
2214 private static function localProbe(string $url): array
2217 $uid = User::getIdForURL($url);
2219 throw new HTTPException\NotFoundException('User not found.');
2222 $profile = User::getOwnerDataById($uid);
2223 $approfile = ActivityPub\Transmitter::getProfile($uid);
2225 if (empty($profile['gsid'])) {
2226 $profile['gsid'] = GServer::getID($approfile['generator']['url']);
2230 'name' => $profile['name'], 'nick' => $profile['nick'], 'guid' => $approfile['diaspora:guid'] ?? '',
2231 'url' => $profile['url'], 'addr' => $profile['addr'], 'alias' => $profile['alias'],
2232 'photo' => Contact::getAvatarUrlForId($profile['id'], '', $profile['updated']),
2233 'header' => $profile['header'] ? Contact::getHeaderUrlForId($profile['id'], $profile['updated']) : '',
2234 'account-type' => $profile['contact-type'], 'community' => ($profile['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY),
2235 'keywords' => $profile['keywords'], 'location' => $profile['location'], 'about' => $profile['about'],
2236 'xmpp' => $profile['xmpp'], 'matrix' => $profile['matrix'],
2237 'hide' => !$profile['net-publish'], 'batch' => '', 'notify' => $profile['notify'],
2238 'poll' => $profile['poll'], 'request' => $profile['request'], 'confirm' => $profile['confirm'],
2239 'subscribe' => $approfile['generator']['url'] . '/follow?url={uri}', 'poco' => $profile['poco'],
2240 'following' => $approfile['following'], 'followers' => $approfile['followers'],
2241 'inbox' => $approfile['inbox'], 'outbox' => $approfile['outbox'],
2242 'sharedinbox' => $approfile['endpoints']['sharedInbox'], 'network' => Protocol::DFRN,
2243 'pubkey' => $profile['upubkey'], 'baseurl' => $approfile['generator']['url'], 'gsid' => $profile['gsid'],
2244 'manually-approve' => in_array($profile['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])
2246 } catch (Exception $e) {
2247 // Default values for non existing targets
2249 'name' => $url, 'nick' => $url, 'url' => $url, 'network' => Protocol::PHANTOM,
2250 'photo' => DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO
2254 return self::rearrangeData($data);