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", "hide",
93 "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);
428 if (!$curlResult->isSuccess()) {
432 // If the file is too large then exit
433 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
437 // If it isn't a HTML file then exit
438 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
442 $body = $curlResult->getBody();
447 $doc = new DOMDocument();
448 @$doc->loadHTML($body);
450 $xpath = new DOMXPath($doc);
452 $list = $xpath->query('//meta[@name]');
453 foreach ($list as $node) {
455 if ($node->attributes->length) {
456 foreach ($node->attributes as $attribute) {
457 $meta_tag[$attribute->name] = $attribute->value;
461 if (empty($meta_tag['content'])) {
465 $content = strtolower(trim($meta_tag['content']));
467 switch (strtolower(trim($meta_tag['name']))) {
468 case 'dfrn-global-visibility':
469 if ($content == 'false') {
474 if (strpos($content, 'noindex') !== false) {
485 * Fetch the "subscribe" and add it to the result
487 * @param array $result
488 * @param array $webfinger
489 * @return array result
491 private static function getSubscribeLink(array $result, array $webfinger)
493 if (empty($webfinger['links'])) {
497 foreach ($webfinger['links'] as $link) {
498 if (!empty($link['template']) && ($link['rel'] === ActivityNamespace::OSTATUSSUB)) {
499 $result['subscribe'] = $link['template'];
507 * Get webfinger data from a given URI
510 * @return array Webfinger array
512 private static function getWebfingerArray(string $uri)
514 $parts = parse_url($uri);
516 if (!empty($parts['scheme']) && !empty($parts['host'])) {
517 $host = $parts['host'];
518 if (!empty($parts['port'])) {
519 $host .= ':'.$parts['port'];
522 $baseurl = $parts['scheme'] . '://' . $host;
527 $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
528 if (!empty($path_parts)) {
529 $nick = ltrim(end($path_parts), '@');
530 // When the last part of the URI is numeric then it is most likely an ID and not a nick name
531 if (!is_numeric($nick)) {
532 $addr = $nick."@".$host;
538 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
539 if (empty($webfinger)) {
540 $lrdd = self::hostMeta($host);
543 if (empty($webfinger) && empty($lrdd)) {
544 while (empty($lrdd) && empty($webfinger) && (sizeof($path_parts) > 1)) {
545 $host .= "/".array_shift($path_parts);
546 $baseurl = $parts['scheme'] . '://' . $host;
549 $addr = $nick."@".$host;
552 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
553 if (empty($webfinger)) {
554 $lrdd = self::hostMeta($host);
558 if (empty($lrdd) && empty($webfinger)) {
562 } elseif (strstr($uri, '@')) {
563 // Remove "acct:" from the URI
564 $uri = str_replace('acct:', '', $uri);
566 $host = substr($uri, strpos($uri, '@') + 1);
567 $nick = substr($uri, 0, strpos($uri, '@'));
570 $webfinger = self::getWebfinger('https://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
571 if (self::$istimeout) {
575 if (empty($webfinger)) {
576 $webfinger = self::getWebfinger('http://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
577 if (self::$istimeout) {
581 $baseurl = 'https://' . $host;
584 if (empty($webfinger)) {
585 $lrdd = self::hostMeta($host);
586 if (self::$istimeout) {
589 $baseurl = self::$baseurl;
591 $baseurl = 'http://' . $host;
594 Logger::info('URI was not detectable', ['uri' => $uri]);
598 if (empty($webfinger)) {
599 foreach ($lrdd as $type => $template) {
604 $webfinger = self::getWebfinger($template, $type, $uri, $addr);
608 if (empty($webfinger)) {
612 if ($webfinger['detected'] == $addr) {
613 $webfinger['nick'] = $nick;
614 $webfinger['addr'] = $addr;
617 $webfinger['baseurl'] = $baseurl;
623 * Perform network request for webfinger data
625 * @param string $template
626 * @param string $type
628 * @param string $addr
629 * @return array webfinger results
631 private static function getWebfinger(string $template, string $type, string $uri, string $addr)
633 // First try the address because this is the primary purpose of webfinger
636 $path = str_replace('{uri}', urlencode("acct:" . $addr), $template);
637 $webfinger = self::webfinger($path, $type);
638 if (self::$istimeout) {
644 if (empty($webfinger) && $uri != $addr) {
646 $path = str_replace('{uri}', urlencode($uri), $template);
647 $webfinger = self::webfinger($path, $type);
648 if (self::$istimeout) {
653 if (empty($webfinger)) {
657 return ['webfinger' => $webfinger, 'detected' => $detected];
661 * Fetch information (protocol endpoints and user information) about a given uri
663 * This function is only called by the "uri" function that adds caching and rearranging of data.
665 * @param string $uri Address that should be probed
666 * @param string $network Test for this specific network
667 * @param integer $uid User ID for the probe (only used for mails)
668 * @param array $ap_profile Previously probed AP profile
670 * @return array uri data
671 * @throws HTTPException\InternalServerErrorException
673 private static function detect(string $uri, string $network, int $uid, array $ap_profile)
677 'network' => $network,
682 Hook::callAll('probe_detect', $hookData);
684 if ($hookData['result']) {
685 if (!is_array($hookData['result'])) {
688 return $hookData['result'];
692 $parts = parse_url($uri);
694 if (!empty($parts['scheme']) && !empty($parts['host'])) {
695 if (in_array($parts['host'], ['twitter.com', 'mobile.twitter.com'])) {
696 return self::twitter($uri);
698 } elseif (strstr($uri, '@')) {
699 // If the URI starts with "mailto:" then jump directly to the mail detection
700 if (strpos($uri, 'mailto:') !== false) {
701 $uri = str_replace('mailto:', '', $uri);
702 return self::mail($uri, $uid);
705 if ($network == Protocol::MAIL) {
706 return self::mail($uri, $uid);
709 if (Strings::endsWith($uri, '@twitter.com')
710 || Strings::endsWith($uri, '@mobile.twitter.com')
712 return self::twitter($uri);
715 Logger::info('URI was not detectable', ['uri' => $uri]);
719 Logger::info('Probing start', ['uri' => $uri]);
721 if (!empty($ap_profile['addr']) && ($ap_profile['addr'] != $uri)) {
722 $data = self::getWebfingerArray($ap_profile['addr']);
726 $data = self::getWebfingerArray($uri);
730 if (!empty($parts['scheme'])) {
731 return self::feed($uri);
732 } elseif (!empty($uid)) {
733 return self::mail($uri, $uid);
739 $webfinger = $data['webfinger'];
740 $nick = $data['nick'] ?? '';
741 $addr = $data['addr'] ?? '';
742 $baseurl = $data['baseurl'] ?? '';
746 if (in_array($network, ["", Protocol::DFRN])) {
747 $result = self::dfrn($webfinger);
749 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
750 $result = self::diaspora($webfinger);
752 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
753 $result = self::ostatus($webfinger);
755 if (in_array($network, ['', Protocol::ZOT])) {
756 $result = self::zot($webfinger, $result, $baseurl);
758 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
759 $result = self::pumpio($webfinger, $addr);
761 if (empty($result['network']) && empty($ap_profile['network']) || ($network == Protocol::FEED)) {
762 $result = self::feed($uri);
764 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
765 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
766 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
767 $result["nick"] = $nick;
770 if (empty($result["addr"]) && ($addr != "")) {
771 $result["addr"] = $addr;
775 $result = self::getSubscribeLink($result, $webfinger);
777 if (empty($result["network"])) {
778 $result["network"] = Protocol::PHANTOM;
781 if (empty($result['baseurl']) && !empty($baseurl)) {
782 $result['baseurl'] = $baseurl;
785 if (empty($result["url"])) {
786 $result["url"] = $uri;
789 Logger::info('Probing done', ['uri' => $uri, 'network' => $result["network"]]);
795 * Check for Zot contact
797 * @param array $webfinger Webfinger data
798 * @param array $data previously probed data
800 * @return array Zot data
801 * @throws HTTPException\InternalServerErrorException
803 private static function zot($webfinger, $data, $baseurl)
805 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
806 foreach ($webfinger["aliases"] as $alias) {
807 if (substr($alias, 0, 5) == 'acct:') {
808 $data["addr"] = substr($alias, 5);
813 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
814 $data["addr"] = substr($webfinger["subject"], 5);
818 foreach ($webfinger['links'] as $link) {
819 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
820 $zot_url = $link['href'];
824 if (empty($zot_url) && !empty($data['addr']) && !empty($baseurl)) {
825 $condition = ['nurl' => Strings::normaliseLink($baseurl), 'platform' => ['hubzilla']];
826 if (!DBA::exists('gserver', $condition)) {
829 $zot_url = $baseurl . '/.well-known/zot-info?address=' . $data['addr'];
832 if (empty($zot_url)) {
836 $data = self::pollZot($zot_url, $data);
838 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
839 foreach ($webfinger['aliases'] as $alias) {
840 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
841 $data['alias'] = $alias;
849 public static function pollZot($url, $data)
851 $curlResult = DI::httpRequest()->get($url);
852 if ($curlResult->isTimeout()) {
855 $content = $curlResult->getBody();
860 $json = json_decode($content, true);
861 if (!is_array($json)) {
865 if (empty($data['network'])) {
866 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
867 $data['network'] = Protocol::ZOT;
868 } elseif (!isset($json['protocols'])) {
869 $data['network'] = Protocol::ZOT;
873 if (!empty($json['guid']) && empty($data['guid'])) {
874 $data['guid'] = $json['guid'];
876 if (!empty($json['key']) && empty($data['pubkey'])) {
877 $data['pubkey'] = $json['key'];
879 if (!empty($json['name'])) {
880 $data['name'] = $json['name'];
882 if (!empty($json['photo'])) {
883 $data['photo'] = $json['photo'];
884 if (!empty($json['photo_updated'])) {
885 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
888 if (!empty($json['address'])) {
889 $data['addr'] = $json['address'];
891 if (!empty($json['url'])) {
892 $data['url'] = $json['url'];
894 if (!empty($json['connections_url'])) {
895 $data['poco'] = $json['connections_url'];
897 if (isset($json['searchable'])) {
898 $data['hide'] = !$json['searchable'];
900 if (!empty($json['public_forum'])) {
901 $data['community'] = $json['public_forum'];
902 $data['account-type'] = User::PAGE_FLAGS_COMMUNITY;
905 if (!empty($json['profile'])) {
906 $profile = $json['profile'];
907 if (!empty($profile['description'])) {
908 $data['about'] = $profile['description'];
910 if (!empty($profile['keywords'])) {
911 $keywords = implode(', ', $profile['keywords']);
912 if (!empty($keywords)) {
913 $data['keywords'] = $keywords;
918 if (!empty($profile['region'])) {
919 $loc['region'] = $profile['region'];
921 if (!empty($profile['country'])) {
922 $loc['country-name'] = $profile['country'];
924 $location = Profile::formatLocation($loc);
925 if (!empty($location)) {
926 $data['location'] = $location;
934 * Perform a webfinger request.
936 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
938 * @param string $url Address that should be probed
939 * @param string $type type
941 * @return array webfinger data
942 * @throws HTTPException\InternalServerErrorException
944 public static function webfinger($url, $type)
946 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
948 $curlResult = DI::httpRequest()->get($url, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
949 if ($curlResult->isTimeout()) {
950 self::$istimeout = true;
953 $data = $curlResult->getBody();
955 $webfinger = json_decode($data, true);
956 if (!empty($webfinger)) {
957 if (!isset($webfinger["links"])) {
958 Logger::info('No json webfinger links', ['url' => $url]);
964 // If it is not JSON, maybe it is XML
965 $xrd = XML::parseString($data, true);
966 if (!is_object($xrd)) {
967 Logger::info('No webfinger data retrievable', ['url' => $url]);
971 $xrd_arr = XML::elementToArray($xrd);
972 if (!isset($xrd_arr["xrd"]["link"])) {
973 Logger::info('No XML webfinger links', ['url' => $url]);
979 if (!empty($xrd_arr["xrd"]["subject"])) {
980 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
983 if (!empty($xrd_arr["xrd"]["alias"])) {
984 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
987 $webfinger["links"] = [];
989 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
990 if (!empty($data["@attributes"])) {
991 $attributes = $data["@attributes"];
992 } elseif ($value == "@attributes") {
998 $webfinger["links"][] = $attributes;
1004 * Poll the Friendica specific noscrape page.
1006 * "noscrape" is a faster alternative to fetch the data from the hcard.
1007 * This functionality was originally created for the directory.
1009 * @param string $noscrape_url Link to the noscrape page
1010 * @param array $data The already fetched data
1012 * @return array noscrape data
1013 * @throws HTTPException\InternalServerErrorException
1015 private static function pollNoscrape($noscrape_url, $data)
1017 $curlResult = DI::httpRequest()->get($noscrape_url);
1018 if ($curlResult->isTimeout()) {
1019 self::$istimeout = true;
1022 $content = $curlResult->getBody();
1024 Logger::info('Empty body', ['url' => $noscrape_url]);
1028 $json = json_decode($content, true);
1029 if (!is_array($json)) {
1030 Logger::info('No json data', ['url' => $noscrape_url]);
1034 if (!empty($json["fn"])) {
1035 $data["name"] = $json["fn"];
1038 if (!empty($json["addr"])) {
1039 $data["addr"] = $json["addr"];
1042 if (!empty($json["nick"])) {
1043 $data["nick"] = $json["nick"];
1046 if (!empty($json["guid"])) {
1047 $data["guid"] = $json["guid"];
1050 if (!empty($json["comm"])) {
1051 $data["community"] = $json["comm"];
1054 if (!empty($json["tags"])) {
1055 $keywords = implode(", ", $json["tags"]);
1056 if ($keywords != "") {
1057 $data["keywords"] = $keywords;
1061 $location = Profile::formatLocation($json);
1063 $data["location"] = $location;
1066 if (!empty($json["about"])) {
1067 $data["about"] = $json["about"];
1070 if (!empty($json["key"])) {
1071 $data["pubkey"] = $json["key"];
1074 if (!empty($json["photo"])) {
1075 $data["photo"] = $json["photo"];
1078 if (!empty($json["dfrn-request"])) {
1079 $data["request"] = $json["dfrn-request"];
1082 if (!empty($json["dfrn-confirm"])) {
1083 $data["confirm"] = $json["dfrn-confirm"];
1086 if (!empty($json["dfrn-notify"])) {
1087 $data["notify"] = $json["dfrn-notify"];
1090 if (!empty($json["dfrn-poll"])) {
1091 $data["poll"] = $json["dfrn-poll"];
1094 if (isset($json["hide"])) {
1095 $data["hide"] = (bool)$json["hide"];
1097 $data["hide"] = false;
1104 * Check for valid DFRN data
1106 * @param array $data DFRN data
1108 * @return int Number of errors
1110 public static function validDfrn($data)
1113 if (!isset($data['key'])) {
1116 if (!isset($data['dfrn-request'])) {
1119 if (!isset($data['dfrn-confirm'])) {
1122 if (!isset($data['dfrn-notify'])) {
1125 if (!isset($data['dfrn-poll'])) {
1132 * Fetch data from a DFRN profile page and via "noscrape"
1134 * @param string $profile_link Link to the profile page
1136 * @return array profile data
1137 * @throws HTTPException\InternalServerErrorException
1138 * @throws \ImagickException
1140 public static function profile($profile_link)
1144 Logger::info('Check profile', ['link' => $profile_link]);
1146 // Fetch data via noscrape - this is faster
1147 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1148 $data = self::pollNoscrape($noscrape_url, $data);
1150 if (!isset($data["notify"])
1151 || !isset($data["confirm"])
1152 || !isset($data["request"])
1153 || !isset($data["poll"])
1154 || !isset($data["name"])
1155 || !isset($data["photo"])
1157 $data = self::pollHcard($profile_link, $data, true);
1162 if (empty($data["addr"]) || empty($data["nick"])) {
1163 $probe_data = self::uri($profile_link);
1164 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1165 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1168 $prof_data["addr"] = $data["addr"];
1169 $prof_data["nick"] = $data["nick"];
1170 $prof_data["dfrn-request"] = $data['request'] ?? null;
1171 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1172 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1173 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1174 $prof_data["photo"] = $data['photo'] ?? null;
1175 $prof_data["fn"] = $data['name'] ?? null;
1176 $prof_data["key"] = $data['pubkey'] ?? null;
1178 Logger::debug('Result', ['link' => $profile_link, 'data' => $prof_data]);
1184 * Check for DFRN contact
1186 * @param array $webfinger Webfinger data
1188 * @return array DFRN data
1189 * @throws HTTPException\InternalServerErrorException
1191 private static function dfrn($webfinger)
1195 // The array is reversed to take into account the order of preference for same-rel links
1196 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1197 foreach (array_reverse($webfinger["links"]) as $link) {
1198 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1199 $data["network"] = Protocol::DFRN;
1200 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1201 $data["poll"] = $link["href"];
1202 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1203 $data["url"] = $link["href"];
1204 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1205 $hcard_url = $link["href"];
1206 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1207 $data["poco"] = $link["href"];
1208 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1209 $data["photo"] = $link["href"];
1210 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1211 $data["baseurl"] = trim($link["href"], '/');
1212 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1213 $data["guid"] = $link["href"];
1214 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1215 $data["pubkey"] = base64_decode($link["href"]);
1217 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1218 if (strstr($data["pubkey"], 'RSA ')) {
1219 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1224 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1225 foreach ($webfinger["aliases"] as $alias) {
1226 if (empty($data["url"]) && !strstr($alias, "@")) {
1227 $data["url"] = $alias;
1228 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1229 $data["alias"] = $alias;
1230 } elseif (substr($alias, 0, 5) == 'acct:') {
1231 $data["addr"] = substr($alias, 5);
1236 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1237 $data["addr"] = substr($webfinger["subject"], 5);
1240 if (!isset($data["network"]) || ($hcard_url == "")) {
1244 // Fetch data via noscrape - this is faster
1245 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1246 $data = self::pollNoscrape($noscrape_url, $data);
1248 if (isset($data["notify"])
1249 && isset($data["confirm"])
1250 && isset($data["request"])
1251 && isset($data["poll"])
1252 && isset($data["name"])
1253 && isset($data["photo"])
1258 $data = self::pollHcard($hcard_url, $data, true);
1264 * Poll the hcard page (Diaspora and Friendica specific)
1266 * @param string $hcard_url Link to the hcard page
1267 * @param array $data The already fetched data
1268 * @param boolean $dfrn Poll DFRN specific data
1270 * @return array hcard data
1271 * @throws HTTPException\InternalServerErrorException
1273 private static function pollHcard($hcard_url, $data, $dfrn = false)
1275 $curlResult = DI::httpRequest()->get($hcard_url);
1276 if ($curlResult->isTimeout()) {
1277 self::$istimeout = true;
1280 $content = $curlResult->getBody();
1281 if (empty($content)) {
1285 $doc = new DOMDocument();
1286 if (!@$doc->loadHTML($content)) {
1290 $xpath = new DomXPath($doc);
1292 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1293 if (!is_object($vcards)) {
1297 if (!isset($data["baseurl"])) {
1298 $data["baseurl"] = "";
1301 if ($vcards->length > 0) {
1302 $vcard = $vcards->item(0);
1304 // We have to discard the guid from the hcard in favour of the guid from lrdd
1305 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1306 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1307 if (($search->length > 0) && empty($data["guid"])) {
1308 $data["guid"] = $search->item(0)->nodeValue;
1311 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1312 if ($search->length > 0) {
1313 $data["nick"] = $search->item(0)->nodeValue;
1316 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1317 if ($search->length > 0) {
1318 $data["name"] = $search->item(0)->nodeValue;
1321 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1322 if ($search->length > 0) {
1323 $data["searchable"] = $search->item(0)->nodeValue;
1326 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1327 if ($search->length > 0) {
1328 $data["pubkey"] = $search->item(0)->nodeValue;
1329 if (strstr($data["pubkey"], 'RSA ')) {
1330 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1334 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1335 if ($search->length > 0) {
1336 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1341 if (!empty($vcard)) {
1342 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1343 foreach ($photos as $photo) {
1345 foreach ($photo->attributes as $attribute) {
1346 $attr[$attribute->name] = trim($attribute->value);
1349 if (isset($attr["src"]) && isset($attr["width"])) {
1350 $avatar[$attr["width"]] = $attr["src"];
1353 // We don't have a width. So we just take everything that we got.
1354 // This is a Hubzilla workaround which doesn't send a width.
1355 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1356 $avatar[] = $attr["src"];
1361 if (sizeof($avatar)) {
1363 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1367 // Poll DFRN specific data
1368 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1369 if ($search->length > 0) {
1370 foreach ($search as $link) {
1371 //$data["request"] = $search->item(0)->nodeValue;
1373 foreach ($link->attributes as $attribute) {
1374 $attr[$attribute->name] = trim($attribute->value);
1377 $data[substr($attr["rel"], 5)] = $attr["href"];
1381 // Older Friendica versions had used the "uid" field differently than newer versions
1382 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1383 unset($data["guid"]);
1392 * Check for Diaspora contact
1394 * @param array $webfinger Webfinger data
1396 * @return array Diaspora data
1397 * @throws HTTPException\InternalServerErrorException
1399 private static function diaspora($webfinger)
1404 // The array is reversed to take into account the order of preference for same-rel links
1405 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1406 foreach (array_reverse($webfinger["links"]) as $link) {
1407 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1408 $hcard_url = $link["href"];
1409 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1410 $data["baseurl"] = trim($link["href"], '/');
1411 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1412 $data["guid"] = $link["href"];
1413 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1414 $data["url"] = $link["href"];
1415 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1416 $data["poll"] = $link["href"];
1417 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1418 $data["poco"] = $link["href"];
1419 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1420 $data["notify"] = $link["href"];
1421 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1422 $data["pubkey"] = base64_decode($link["href"]);
1424 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1425 if (strstr($data["pubkey"], 'RSA ')) {
1426 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1431 if (empty($data["url"]) || empty($hcard_url)) {
1435 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1436 foreach ($webfinger["aliases"] as $alias) {
1437 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1438 $data["alias"] = $alias;
1439 } elseif (substr($alias, 0, 5) == 'acct:') {
1440 $data["addr"] = substr($alias, 5);
1445 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1446 $data["addr"] = substr($webfinger["subject"], 5);
1449 // Fetch further information from the hcard
1450 $data = self::pollHcard($hcard_url, $data);
1456 if (!empty($data["url"])
1457 && !empty($data["guid"])
1458 && !empty($data["baseurl"])
1459 && !empty($data["pubkey"])
1460 && !empty($hcard_url)
1462 $data["network"] = Protocol::DIASPORA;
1463 $data["manually-approve"] = false;
1465 // The Diaspora handle must always be lowercase
1466 if (!empty($data["addr"])) {
1467 $data["addr"] = strtolower($data["addr"]);
1470 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1471 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1472 $data["batch"] = $data["baseurl"] . "/receive/public";
1481 * Check for OStatus contact
1483 * @param array $webfinger Webfinger data
1484 * @param bool $short Short detection mode
1486 * @return array|bool OStatus data or "false" on error or "true" on short mode
1487 * @throws HTTPException\InternalServerErrorException
1489 private static function ostatus($webfinger, $short = false)
1493 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1494 foreach ($webfinger["aliases"] as $alias) {
1495 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1496 $data["addr"] = str_replace('acct:', '', $alias);
1501 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1502 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1504 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1507 if (!empty($webfinger["links"])) {
1508 // The array is reversed to take into account the order of preference for same-rel links
1509 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1510 foreach (array_reverse($webfinger["links"]) as $link) {
1511 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1512 && (($link["type"] ?? "") == "text/html")
1513 && ($link["href"] != "")
1515 $data["url"] = $data["alias"] = $link["href"];
1516 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1517 $data["notify"] = $link["href"];
1518 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1519 $data["poll"] = $link["href"];
1520 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1521 $pubkey = $link["href"];
1523 if (substr($pubkey, 0, 5) === 'data:') {
1524 if (strstr($pubkey, ',')) {
1525 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1527 $pubkey = substr($pubkey, 5);
1529 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1530 $curlResult = DI::httpRequest()->get($pubkey);
1531 if ($curlResult->isTimeout()) {
1532 self::$istimeout = true;
1533 return $short ? false : [];
1535 $pubkey = $curlResult->getBody();
1538 $key = explode(".", $pubkey);
1540 if (sizeof($key) >= 3) {
1541 $m = Strings::base64UrlDecode($key[1]);
1542 $e = Strings::base64UrlDecode($key[2]);
1543 $data["pubkey"] = Crypto::meToPem($m, $e);
1549 if (isset($data["notify"]) && isset($data["pubkey"])
1550 && isset($data["poll"])
1551 && isset($data["url"])
1553 $data["network"] = Protocol::OSTATUS;
1554 $data["manually-approve"] = false;
1556 return $short ? false : [];
1563 // Fetch all additional data from the feed
1564 $curlResult = DI::httpRequest()->get($data["poll"]);
1565 if ($curlResult->isTimeout()) {
1566 self::$istimeout = true;
1569 $feed = $curlResult->getBody();
1570 $feed_data = Feed::import($feed);
1575 if (!empty($feed_data["header"]["author-name"])) {
1576 $data["name"] = $feed_data["header"]["author-name"];
1578 if (!empty($feed_data["header"]["author-nick"])) {
1579 $data["nick"] = $feed_data["header"]["author-nick"];
1581 if (!empty($feed_data["header"]["author-avatar"])) {
1582 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1584 if (!empty($feed_data["header"]["author-id"])) {
1585 $data["alias"] = $feed_data["header"]["author-id"];
1587 if (!empty($feed_data["header"]["author-location"])) {
1588 $data["location"] = $feed_data["header"]["author-location"];
1590 if (!empty($feed_data["header"]["author-about"])) {
1591 $data["about"] = $feed_data["header"]["author-about"];
1593 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1594 // So we take the value that we just fetched, although the other one worked as well
1595 if (!empty($feed_data["header"]["author-link"])) {
1596 $data["url"] = $feed_data["header"]["author-link"];
1599 if ($data["url"] == $data["alias"]) {
1600 $data["alias"] = '';
1603 /// @todo Fetch location and "about" from the feed as well
1608 * Fetch data from a pump.io profile page
1610 * @param string $profile_link Link to the profile page
1612 * @return array profile data
1614 private static function pumpioProfileData($profile_link)
1616 $curlResult = DI::httpRequest()->get($profile_link);
1617 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
1621 $doc = new DOMDocument();
1622 if (!@$doc->loadHTML($curlResult->getBody())) {
1626 $xpath = new DomXPath($doc);
1630 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1632 if ($data["name"] == '') {
1633 // This is ugly - but pump.io doesn't seem to know a better way for it
1634 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1635 $pos = strpos($data["name"], chr(10));
1637 $data["name"] = trim(substr($data["name"], 0, $pos));
1641 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1643 if ($data["location"] == '') {
1644 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1647 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1649 if ($data["about"] == '') {
1650 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1653 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1655 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1658 foreach ($avatar->attributes as $attribute) {
1659 if ($attribute->name == "src") {
1660 $data["photo"] = trim($attribute->value);
1669 * Check for pump.io contact
1671 * @param array $webfinger Webfinger data
1672 * @param string $addr
1673 * @return array pump.io data
1675 private static function pumpio($webfinger, $addr)
1678 // The array is reversed to take into account the order of preference for same-rel links
1679 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1680 foreach (array_reverse($webfinger["links"]) as $link) {
1681 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1682 && (($link["type"] ?? "") == "text/html")
1683 && ($link["href"] != "")
1685 $data["url"] = $link["href"];
1686 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1687 $data["notify"] = $link["href"];
1688 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1689 $data["poll"] = $link["href"];
1690 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1691 $data["dialback"] = $link["href"];
1694 if (isset($data["poll"]) && isset($data["notify"])
1695 && isset($data["dialback"])
1696 && isset($data["url"])
1698 // by now we use these fields only for the network type detection
1699 // So we unset all data that isn't used at the moment
1700 unset($data["dialback"]);
1702 $data["network"] = Protocol::PUMPIO;
1707 $profile_data = self::pumpioProfileData($data["url"]);
1709 if (!$profile_data) {
1713 $data = array_merge($data, $profile_data);
1715 if (($addr != '') && ($data['name'] != '')) {
1716 $name = trim(str_replace($addr, '', $data['name']));
1718 $data['name'] = $name;
1726 * Check for twitter contact
1728 * @param string $uri
1730 * @return array twitter data
1732 private static function twitter($uri)
1734 if (preg_match('=([^@]+)@(?:mobile\.)?twitter\.com$=i', $uri, $matches)) {
1735 $nick = $matches[1];
1736 } elseif (preg_match('=^https?://(?:mobile\.)?twitter\.com/(.+)=i', $uri, $matches)) {
1737 $nick = $matches[1];
1743 $data['url'] = 'https://twitter.com/' . $nick;
1744 $data['addr'] = $nick . '@twitter.com';
1745 $data['nick'] = $data['name'] = $nick;
1746 $data['network'] = Protocol::TWITTER;
1747 $data['baseurl'] = 'https://twitter.com';
1753 * Checks HTML page for RSS feed link
1755 * @param string $url Page link
1756 * @param string $body Page body string
1757 * @return string|false Feed link or false if body was invalid HTML document
1759 public static function getFeedLink(string $url, string $body)
1765 $doc = new DOMDocument();
1766 if (!@$doc->loadHTML($body)) {
1770 $xpath = new DOMXPath($doc);
1772 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1774 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1780 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1782 * Loosely based on RFC 1808
1784 * @see https://tools.ietf.org/html/rfc1808
1786 * @param string $href The potential relative href found in the HTML document
1787 * @param string $base The HTML document URL
1788 * @param DOMXPath $xpath The HTML document XPath
1791 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath)
1793 if (filter_var($href, FILTER_VALIDATE_URL)) {
1797 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1799 $baseParts = parse_url($base);
1800 if (empty($baseParts['host'])) {
1804 // Naked domain case (scheme://basehost)
1805 $path = $baseParts['path'] ?? '/';
1807 // Remove the filename part of the path if it exists (/base/path/file)
1808 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1810 $hrefParts = parse_url($href);
1812 if (!empty($hrefParts['path'])) {
1813 // Root path case (/path) including relative scheme case (//host/path)
1814 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1815 $path = $hrefParts['path'];
1817 $path = $path . '/' . $hrefParts['path'];
1819 // Resolve arbitrary relative path
1820 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1821 $parts = array_filter(explode('/', $path), 'strlen');
1822 $absolutes = array();
1823 foreach ($parts as $part) {
1824 if ('.' == $part) continue;
1825 if ('..' == $part) {
1826 array_pop($absolutes);
1828 $absolutes[] = $part;
1832 $path = '/' . implode('/', $absolutes);
1836 // Relative scheme case (//host/path)
1837 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1838 $baseParts['path'] = $path;
1839 unset($baseParts['query']);
1840 unset($baseParts['fragment']);
1842 return Network::unparseURL($baseParts);
1846 * Check for feed contact
1848 * @param string $url Profile link
1849 * @param boolean $probe Do a probe if the page contains a feed link
1851 * @return array feed data
1852 * @throws HTTPException\InternalServerErrorException
1854 private static function feed($url, $probe = true)
1856 $curlResult = DI::httpRequest()->get($url);
1857 if ($curlResult->isTimeout()) {
1858 self::$istimeout = true;
1861 $feed = $curlResult->getBody();
1862 $feed_data = Feed::import($feed);
1869 $feed_url = self::getFeedLink($url, $feed);
1875 return self::feed($feed_url, false);
1878 if (!empty($feed_data["header"]["author-name"])) {
1879 $data["name"] = $feed_data["header"]["author-name"];
1882 if (!empty($feed_data["header"]["author-nick"])) {
1883 $data["nick"] = $feed_data["header"]["author-nick"];
1886 if (!empty($feed_data["header"]["author-avatar"])) {
1887 $data["photo"] = $feed_data["header"]["author-avatar"];
1890 if (!empty($feed_data["header"]["author-id"])) {
1891 $data["alias"] = $feed_data["header"]["author-id"];
1894 $data["url"] = $url;
1895 $data["poll"] = $url;
1897 $data["network"] = Protocol::FEED;
1903 * Check for mail contact
1905 * @param string $uri Profile link
1906 * @param integer $uid User ID
1908 * @return array mail data
1909 * @throws \Exception
1911 private static function mail($uri, $uid)
1913 if (!Network::isEmailDomainValid($uri)) {
1921 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1923 $condition = ["`uid` = ? AND `server` != ''", $uid];
1924 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1925 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1927 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1931 $mailbox = Email::constructMailboxName($mailacct);
1933 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1934 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1939 $msgs = Email::poll($mbox, $uri);
1940 Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
1942 if (!count($msgs)) {
1946 $phost = substr($uri, strpos($uri, '@') + 1);
1949 $data["addr"] = $uri;
1950 $data["network"] = Protocol::MAIL;
1951 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1952 $data["nick"] = $data["name"];
1953 $data["photo"] = Network::lookupAvatarByEmail($uri);
1954 $data["url"] = 'mailto:'.$uri;
1955 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1956 $data["poll"] = 'email ' . Strings::getRandomHex();
1958 $x = Email::messageMeta($mbox, $msgs[0]);
1959 if (stristr($x[0]->from, $uri)) {
1960 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1961 } elseif (stristr($x[0]->to, $uri)) {
1962 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1965 foreach ($adr as $feadr) {
1966 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1967 &&(strcasecmp($feadr->host, $phost) == 0)
1968 && (strlen($feadr->personal))
1970 $personal = imap_mime_header_decode($feadr->personal);
1972 foreach ($personal as $perspart) {
1973 if ($perspart->charset != "default") {
1974 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1976 $data["name"] .= $perspart->text;
1980 $data["name"] = Strings::escapeTags($data["name"]);
1984 if (!empty($mbox)) {
1991 * Mix two paths together to possibly fix missing parts
1993 * @param string $avatar Path to the avatar
1994 * @param string $base Another path that is hopefully complete
1996 * @return string fixed avatar path
1997 * @throws \Exception
1999 public static function fixAvatar($avatar, $base)
2001 $base_parts = parse_url($base);
2003 // Remove all parts that could create a problem
2004 unset($base_parts['path']);
2005 unset($base_parts['query']);
2006 unset($base_parts['fragment']);
2008 $avatar_parts = parse_url($avatar);
2011 $parts = array_merge($base_parts, $avatar_parts);
2013 // And put them together again
2014 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
2015 $host = isset($parts['host']) ? $parts['host'] : '';
2016 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
2017 $path = isset($parts['path']) ? $parts['path'] : '';
2018 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
2019 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
2021 $fixed = $scheme.$host.$port.$path.$query.$fragment;
2023 Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
2029 * Fetch the last date that the contact had posted something (publically)
2031 * @param string $data probing result
2032 * @return string last activity
2034 public static function getLastUpdate(array $data)
2036 $uid = User::getIdForURL($data['url']);
2038 $contact = Contact::selectFirst(['url', 'last-item'], ['self' => true, 'uid' => $uid]);
2039 if (!empty($contact['last-item'])) {
2040 return $contact['last-item'];
2044 if ($lastUpdate = self::updateFromNoScrape($data)) {
2048 if (!empty($data['outbox'])) {
2049 return self::updateFromOutbox($data['outbox'], $data);
2050 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
2051 return self::updateFromOutbox($data['poll'], $data);
2052 } elseif (!empty($data['poll'])) {
2053 return self::updateFromFeed($data);
2060 * Fetch the last activity date from the "noscrape" endpoint
2062 * @param array $data Probing result
2063 * @return string last activity
2065 * @return bool 'true' if update was successful or the server was unreachable
2067 private static function updateFromNoScrape(array $data)
2069 if (empty($data['baseurl'])) {
2073 // Check the 'noscrape' endpoint when it is a Friendica server
2074 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
2075 Strings::normaliseLink($data['baseurl'])]);
2076 if (!DBA::isResult($gserver)) {
2080 $curlResult = DI::httpRequest()->get($gserver['noscrape'] . '/' . $data['nick']);
2082 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
2083 $noscrape = json_decode($curlResult->getBody(), true);
2084 if (!empty($noscrape) && !empty($noscrape['updated'])) {
2085 return DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2093 * Fetch the last activity date from an ActivityPub Outbox
2095 * @param string $feed
2096 * @param array $data Probing result
2097 * @return string last activity
2098 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2100 private static function updateFromOutbox(string $feed, array $data)
2102 $outbox = ActivityPub::fetchContent($feed);
2103 if (empty($outbox)) {
2107 if (!empty($outbox['orderedItems'])) {
2108 $items = $outbox['orderedItems'];
2109 } elseif (!empty($outbox['first']['orderedItems'])) {
2110 $items = $outbox['first']['orderedItems'];
2111 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2112 return self::updateFromOutbox($outbox['first']['href'], $data);
2113 } elseif (!empty($outbox['first'])) {
2114 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2115 return self::updateFromOutbox($outbox['first'], $data);
2117 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2125 foreach ($items as $activity) {
2126 if (!empty($activity['published'])) {
2127 $published = DateTimeFormat::utc($activity['published']);
2128 } elseif (!empty($activity['object']['published'])) {
2129 $published = DateTimeFormat::utc($activity['object']['published']);
2134 if ($last_updated < $published) {
2135 $last_updated = $published;
2139 if (!empty($last_updated)) {
2140 return $last_updated;
2147 * Fetch the last activity date from an XML feed
2149 * @param array $data Probing result
2150 * @return string last activity
2152 private static function updateFromFeed(array $data)
2154 // Search for the newest entry in the feed
2155 $curlResult = DI::httpRequest()->get($data['poll']);
2156 if (!$curlResult->isSuccess()) {
2160 $doc = new DOMDocument();
2161 @$doc->loadXML($curlResult->getBody());
2163 $xpath = new DOMXPath($doc);
2164 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2166 $entries = $xpath->query('/atom:feed/atom:entry');
2170 foreach ($entries as $entry) {
2171 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2172 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
2173 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2174 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2176 if (empty($published) || empty($updated)) {
2177 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2181 if ($last_updated < $published) {
2182 $last_updated = $published;
2185 if ($last_updated < $updated) {
2186 $last_updated = $updated;
2190 if (!empty($last_updated)) {
2191 return $last_updated;
2198 * Probe data from local profiles without network traffic
2200 * @param string $url
2201 * @return array probed data
2202 * @throws HTTPException\InternalServerErrorException
2203 * @throws HTTPException\NotFoundException
2205 private static function localProbe(string $url): array
2208 $uid = User::getIdForURL($url);
2210 throw new HTTPException\NotFoundException('User not found.');
2213 $profile = User::getOwnerDataById($uid);
2214 $approfile = ActivityPub\Transmitter::getProfile($uid);
2216 if (empty($profile['gsid'])) {
2217 $profile['gsid'] = GServer::getID($approfile['generator']['url']);
2221 'name' => $profile['name'], 'nick' => $profile['nick'], 'guid' => $approfile['diaspora:guid'] ?? '',
2222 'url' => $profile['url'], 'addr' => $profile['addr'], 'alias' => $profile['alias'],
2223 'photo' => Contact::getAvatarUrlForId($profile['id'], '', $profile['updated']),
2224 'header' => $profile['header'] ? Contact::getHeaderUrlForId($profile['id'], $profile['updated']) : '',
2225 'account-type' => $profile['contact-type'], 'community' => ($profile['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY),
2226 'keywords' => $profile['keywords'], 'location' => $profile['location'], 'about' => $profile['about'],
2227 'hide' => !$profile['net-publish'], 'batch' => '', 'notify' => $profile['notify'],
2228 'poll' => $profile['poll'], 'request' => $profile['request'], 'confirm' => $profile['confirm'],
2229 'subscribe' => $approfile['generator']['url'] . '/follow?url={uri}', 'poco' => $profile['poco'],
2230 'following' => $approfile['following'], 'followers' => $approfile['followers'],
2231 'inbox' => $approfile['inbox'], 'outbox' => $approfile['outbox'],
2232 'sharedinbox' => $approfile['endpoints']['sharedInbox'], 'network' => Protocol::DFRN,
2233 'pubkey' => $profile['upubkey'], 'baseurl' => $approfile['generator']['url'], 'gsid' => $profile['gsid'],
2234 'manually-approve' => in_array($profile['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])
2236 } catch (Exception $e) {
2237 // Default values for non existing targets
2239 'name' => $url, 'nick' => $url, 'url' => $url, 'network' => Protocol::PHANTOM,
2240 'photo' => DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO
2244 return self::rearrangeData($data);