3 * @copyright Copyright (C) 2020, Friendica
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;
26 use Friendica\Core\Hook;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\System;
30 use Friendica\Database\DBA;
32 use Friendica\Model\Contact;
33 use Friendica\Model\GServer;
34 use Friendica\Model\Profile;
35 use Friendica\Model\User;
36 use Friendica\Protocol\ActivityNamespace;
37 use Friendica\Protocol\ActivityPub;
38 use Friendica\Protocol\Email;
39 use Friendica\Protocol\Feed;
40 use Friendica\Util\Crypto;
41 use Friendica\Util\DateTimeFormat;
42 use Friendica\Util\Network;
43 use Friendica\Util\Strings;
44 use Friendica\Util\XML;
47 * This class contain functions for probing URL
51 const WEBFINGER = '/.well-known/webfinger?resource={uri}';
53 private static $baseurl;
54 private static $istimeout;
57 * Remove stuff from an URI that doesn't belong there
60 * @return string Cleaned URI
62 public static function cleanURI(string $URI)
64 // At first remove leading and trailing junk
65 $URI = trim($URI, "@#?:/ \t\n\r\0\x0B");
67 $parts = parse_url($URI);
69 if (empty($parts['scheme'])) {
73 // Remove the URL fragment, since these shouldn't be part of any profile URL
74 unset($parts['fragment']);
76 $URI = Network::unparseURL($parts);
82 * Rearrange the array so that it always has the same order
84 * @param array $data Unordered data
86 * @return array Ordered data
88 private static function rearrangeData($data)
90 $fields = ["name", "nick", "guid", "url", "addr", "alias", "photo", "account-type",
91 "community", "keywords", "location", "about", "hide",
92 "batch", "notify", "poll", "request", "confirm", "subscribe", "poco",
93 "following", "followers", "inbox", "outbox", "sharedinbox",
94 "priority", "network", "pubkey", "baseurl", "gsid"];
97 foreach ($fields as $field) {
98 if (isset($data[$field])) {
99 if (in_array($field, ["gsid", "hide", "account-type"])) {
100 $newdata[$field] = (int)$data[$field];
102 $newdata[$field] = $data[$field];
104 } elseif ($field != "gsid") {
105 $newdata[$field] = "";
107 $newdata[$field] = null;
111 // We don't use the "priority" field anymore and replace it with a dummy.
112 $newdata["priority"] = 0;
118 * Check if the hostname belongs to the own server
120 * @param string $host The hostname that is to be checked
122 * @return bool Does the testes hostname belongs to the own server?
124 private static function ownHost($host)
126 $own_host = DI::baseUrl()->getHostname();
128 $parts = parse_url($host);
130 if (!isset($parts['scheme'])) {
131 $parts = parse_url('http://'.$host);
134 if (!isset($parts['host'])) {
137 return $parts['host'] == $own_host;
141 * Probes for webfinger path via "host-meta"
143 * We have to check if the servers in the future still will offer this.
144 * It seems as if it was dropped from the standard.
146 * @param string $host The host part of an url
148 * @return array with template and type of the webfinger template for JSON or XML
149 * @throws HTTPException\InternalServerErrorException
151 private static function hostMeta($host)
153 // Reset the static variable
156 // Handles the case when the hostname contains the scheme
157 if (!parse_url($host, PHP_URL_SCHEME)) {
158 $ssl_url = "https://" . $host . "/.well-known/host-meta";
159 $url = "http://" . $host . "/.well-known/host-meta";
161 $ssl_url = $host . "/.well-known/host-meta";
165 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
167 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
170 $curlResult = DI::httpRequest()->get($ssl_url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
171 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
172 if ($curlResult->isSuccess()) {
173 $xml = $curlResult->getBody();
174 $xrd = XML::parseString($xml, true);
176 $host_url = 'https://' . $host;
180 } elseif ($curlResult->isTimeout()) {
181 Logger::info('Probing timeout', ['url' => $ssl_url]);
182 self::$istimeout = true;
186 if (!is_object($xrd) && !empty($url)) {
187 $curlResult = DI::httpRequest()->get($url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
188 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
189 if ($curlResult->isTimeout()) {
190 Logger::info('Probing timeout', ['url' => $url]);
191 self::$istimeout = true;
193 } elseif ($connection_error && $ssl_connection_error) {
194 self::$istimeout = true;
198 $xml = $curlResult->getBody();
199 $xrd = XML::parseString($xml, true);
200 $host_url = 'http://'.$host;
202 if (!is_object($xrd)) {
203 Logger::info('No xrd object found', ['host' => $host]);
207 $links = XML::elementToArray($xrd);
208 if (!isset($links["xrd"]["link"])) {
209 Logger::info('No xrd data found', ['host' => $host]);
215 foreach ($links["xrd"]["link"] as $value => $link) {
216 if (!empty($link["@attributes"])) {
217 $attributes = $link["@attributes"];
218 } elseif ($value == "@attributes") {
224 if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
225 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
227 $lrdd[$type] = $attributes["template"];
231 self::$baseurl = $host_url;
233 Logger::info('Probing successful', ['host' => $host]);
239 * Perform Webfinger lookup and return DFRN data
241 * Given an email style address, perform webfinger lookup and
242 * return the resulting DFRN profile URL, or if no DFRN profile URL
243 * is located, returns an OStatus subscription template (prefixed
244 * with the string 'stat:' to identify it as on OStatus template).
245 * If this isn't an email style address just return $webbie.
246 * Return an empty string if email-style addresses but webfinger fails,
247 * or if the resultant personal XRD doesn't contain a supported
248 * subscription/friend-request attribute.
250 * amended 7/9/2011 to return an hcard which could save potentially loading
251 * a lengthy content page to scrape dfrn attributes
253 * @param string $webbie Address that should be probed
254 * @param string $hcard_url Link to the hcard - is returned by reference
256 * @return string profile link
257 * @throws HTTPException\InternalServerErrorException
259 public static function webfingerDfrn($webbie, &$hcard_url)
263 $links = self::lrdd($webbie);
264 Logger::debug('Result', ['url' => $webbie, 'links' => $links]);
265 if (!empty($links) && is_array($links)) {
266 foreach ($links as $link) {
267 if ($link['@attributes']['rel'] === ActivityNamespace::DFRN) {
268 $profile_link = $link['@attributes']['href'];
270 if (($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) && ($profile_link == "")) {
271 $profile_link = 'stat:'.$link['@attributes']['template'];
273 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
274 $hcard_url = $link['@attributes']['href'];
278 return $profile_link;
282 * Check an URI for LRDD data
284 * @param string $uri Address that should be probed
286 * @return array uri data
287 * @throws HTTPException\InternalServerErrorException
289 public static function lrdd(string $uri)
291 $data = self::getWebfingerArray($uri);
295 $webfinger = $data['webfinger'];
297 if (empty($webfinger["links"])) {
298 Logger::info('No webfinger links found', ['uri' => $uri]);
304 foreach ($webfinger["links"] as $link) {
305 $data[] = ["@attributes" => $link];
308 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
309 foreach ($webfinger["aliases"] as $alias) {
310 $data[] = ["@attributes" =>
320 * Fetch information (protocol endpoints and user information) about a given uri
322 * @param string $uri Address that should be probed
323 * @param string $network Test for this specific network
324 * @param integer $uid User ID for the probe (only used for mails)
325 * @param boolean $cache Use cached values?
327 * @return array uri data
328 * @throws HTTPException\InternalServerErrorException
329 * @throws \ImagickException
331 public static function uri($uri, $network = '', $uid = -1)
333 // Local profiles aren't probed via network
334 if (empty($network) && strpos($uri, DI::baseUrl()->getHostname())) {
335 $data = self::localProbe($uri);
345 if (empty($network) || ($network == Protocol::ACTIVITYPUB)) {
346 $ap_profile = ActivityPub::probeProfile($uri);
351 self::$istimeout = false;
353 if ($network != Protocol::ACTIVITYPUB) {
354 $data = self::detect($uri, $network, $uid, $ap_profile);
355 if (!is_array($data)) {
358 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
360 } elseif (!empty($ap_profile)) {
361 $ap_profile['batch'] = '';
362 $data = array_merge($ap_profile, $data);
368 if (!isset($data['url'])) {
372 if (empty($data['photo'])) {
373 $data['photo'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
376 if (empty($data['name'])) {
377 if (!empty($data['nick'])) {
378 $data['name'] = $data['nick'];
381 if (empty($data['name'])) {
382 $data['name'] = $data['url'];
386 if (empty($data['nick'])) {
387 $data['nick'] = strtolower($data['name']);
389 if (strpos($data['nick'], ' ')) {
390 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
394 if (!empty($data['baseurl']) && empty($data['gsid'])) {
395 $data['gsid'] = GServer::getID($data['baseurl']);
398 if (empty($data['network'])) {
399 $data['network'] = Protocol::PHANTOM;
402 // Ensure that local connections always are DFRN
403 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
404 $data['network'] = Protocol::DFRN;
407 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
408 $data['hide'] = self::getHideStatus($data['url']);
411 return self::rearrangeData($data);
416 * Fetches the "hide" status from the profile
418 * @param string $url URL of the profile
420 * @return boolean "hide" status
422 private static function getHideStatus($url)
424 $curlResult = DI::httpRequest()->get($url);
425 if (!$curlResult->isSuccess()) {
429 // If the file is too large then exit
430 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
434 // If it isn't a HTML file then exit
435 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
439 $body = $curlResult->getBody();
441 $doc = new DOMDocument();
442 @$doc->loadHTML($body);
444 $xpath = new DOMXPath($doc);
446 $list = $xpath->query('//meta[@name]');
447 foreach ($list as $node) {
449 if ($node->attributes->length) {
450 foreach ($node->attributes as $attribute) {
451 $meta_tag[$attribute->name] = $attribute->value;
455 if (empty($meta_tag['content'])) {
459 $content = strtolower(trim($meta_tag['content']));
461 switch (strtolower(trim($meta_tag['name']))) {
462 case 'dfrn-global-visibility':
463 if ($content == 'false') {
468 if (strpos($content, 'noindex') !== false) {
479 * Fetch the "subscribe" and add it to the result
481 * @param array $result
482 * @param array $webfinger
483 * @return array result
485 private static function getSubscribeLink(array $result, array $webfinger)
487 if (empty($webfinger['links'])) {
491 foreach ($webfinger['links'] as $link) {
492 if (!empty($link['template']) && ($link['rel'] === ActivityNamespace::OSTATUSSUB)) {
493 $result['subscribe'] = $link['template'];
501 * Get webfinger data from a given URI
504 * @return array Webfinger array
506 private static function getWebfingerArray(string $uri)
508 $parts = parse_url($uri);
510 if (!empty($parts['scheme']) && !empty($parts['host'])) {
511 $host = $parts['host'];
512 if (!empty($parts['port'])) {
513 $host .= ':'.$parts['port'];
516 $baseurl = $parts['scheme'] . '://' . $host;
521 $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
522 if (!empty($path_parts)) {
523 $nick = ltrim(end($path_parts), '@');
524 // When the last part of the URI is numeric then it is most likely an ID and not a nick name
525 if (!is_numeric($nick)) {
526 $addr = $nick."@".$host;
532 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
533 if (empty($webfinger)) {
534 $lrdd = self::hostMeta($host);
537 if (empty($webfinger) && empty($lrdd)) {
538 while (empty($lrdd) && empty($webfinger) && (sizeof($path_parts) > 1)) {
539 $host .= "/".array_shift($path_parts);
540 $baseurl = $parts['scheme'] . '://' . $host;
543 $addr = $nick."@".$host;
546 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
547 if (empty($webfinger)) {
548 $lrdd = self::hostMeta($host);
552 if (empty($lrdd) && empty($webfinger)) {
556 } elseif (strstr($uri, '@')) {
557 // Remove "acct:" from the URI
558 $uri = str_replace('acct:', '', $uri);
560 $host = substr($uri, strpos($uri, '@') + 1);
561 $nick = substr($uri, 0, strpos($uri, '@'));
564 $webfinger = self::getWebfinger('https://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
565 if (self::$istimeout) {
569 if (empty($webfinger)) {
570 $webfinger = self::getWebfinger('http://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
571 if (self::$istimeout) {
575 $baseurl = 'https://' . $host;
578 if (empty($webfinger)) {
579 $lrdd = self::hostMeta($host);
580 if (self::$istimeout) {
583 $baseurl = self::$baseurl;
585 $baseurl = 'http://' . $host;
588 Logger::info('URI was not detectable', ['uri' => $uri]);
592 if (empty($webfinger)) {
593 foreach ($lrdd as $type => $template) {
598 $webfinger = self::getWebfinger($template, $type, $uri, $addr);
602 if (empty($webfinger)) {
606 if ($webfinger['detected'] == $addr) {
607 $webfinger['nick'] = $nick;
608 $webfinger['addr'] = $addr;
611 $webfinger['baseurl'] = $baseurl;
617 * Perform network request for webfinger data
619 * @param string $template
620 * @param string $type
622 * @param string $addr
623 * @return array webfinger results
625 private static function getWebfinger(string $template, string $type, string $uri, string $addr)
627 // First try the address because this is the primary purpose of webfinger
630 $path = str_replace('{uri}', urlencode("acct:" . $addr), $template);
631 $webfinger = self::webfinger($path, $type);
632 if (self::$istimeout) {
638 if (empty($webfinger) && $uri != $addr) {
640 $path = str_replace('{uri}', urlencode($uri), $template);
641 $webfinger = self::webfinger($path, $type);
642 if (self::$istimeout) {
647 if (empty($webfinger)) {
651 return ['webfinger' => $webfinger, 'detected' => $detected];
655 * Fetch information (protocol endpoints and user information) about a given uri
657 * This function is only called by the "uri" function that adds caching and rearranging of data.
659 * @param string $uri Address that should be probed
660 * @param string $network Test for this specific network
661 * @param integer $uid User ID for the probe (only used for mails)
662 * @param array $ap_profile Previously probed AP profile
664 * @return array uri data
665 * @throws HTTPException\InternalServerErrorException
667 private static function detect(string $uri, string $network, int $uid, array $ap_profile)
671 'network' => $network,
676 Hook::callAll('probe_detect', $hookData);
678 if ($hookData['result']) {
679 if (!is_array($hookData['result'])) {
682 return $hookData['result'];
686 $parts = parse_url($uri);
688 if (!empty($parts['scheme']) && !empty($parts['host'])) {
689 if (in_array($parts['host'], ['twitter.com', 'mobile.twitter.com'])) {
690 return self::twitter($uri);
692 } elseif (strstr($uri, '@')) {
693 // If the URI starts with "mailto:" then jump directly to the mail detection
694 if (strpos($uri, 'mailto:') !== false) {
695 $uri = str_replace('mailto:', '', $uri);
696 return self::mail($uri, $uid);
699 if ($network == Protocol::MAIL) {
700 return self::mail($uri, $uid);
703 if (Strings::endsWith($uri, '@twitter.com')
704 || Strings::endsWith($uri, '@mobile.twitter.com')
706 return self::twitter($uri);
709 Logger::info('URI was not detectable', ['uri' => $uri]);
713 Logger::info('Probing start', ['uri' => $uri]);
715 $data = self::getWebfingerArray($uri);
717 if (!empty($parts['scheme'])) {
718 return self::feed($uri);
719 } elseif (!empty($uid)) {
720 return self::mail($uri, $uid);
726 $webfinger = $data['webfinger'];
727 $nick = $data['nick'] ?? '';
728 $addr = $data['addr'] ?? '';
729 $baseurl = $data['baseurl'] ?? '';
733 if (in_array($network, ["", Protocol::DFRN])) {
734 $result = self::dfrn($webfinger);
736 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
737 $result = self::diaspora($webfinger);
739 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
740 $result = self::ostatus($webfinger);
742 if (in_array($network, ['', Protocol::ZOT])) {
743 $result = self::zot($webfinger, $result, $baseurl);
745 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
746 $result = self::pumpio($webfinger, $addr);
748 if (empty($result['network']) && empty($ap_profile['network']) || ($network == Protocol::FEED)) {
749 $result = self::feed($uri);
751 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
752 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
753 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
754 $result["nick"] = $nick;
757 if (empty($result["addr"]) && ($addr != "")) {
758 $result["addr"] = $addr;
762 $result = self::getSubscribeLink($result, $webfinger);
764 if (empty($result["network"])) {
765 $result["network"] = Protocol::PHANTOM;
768 if (empty($result['baseurl']) && !empty($baseurl)) {
769 $result['baseurl'] = $baseurl;
772 if (empty($result["url"])) {
773 $result["url"] = $uri;
776 Logger::info('Probing done', ['uri' => $uri, 'network' => $result["network"]]);
782 * Check for Zot contact
784 * @param array $webfinger Webfinger data
785 * @param array $data previously probed data
787 * @return array Zot data
788 * @throws HTTPException\InternalServerErrorException
790 private static function zot($webfinger, $data, $baseurl)
792 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
793 foreach ($webfinger["aliases"] as $alias) {
794 if (substr($alias, 0, 5) == 'acct:') {
795 $data["addr"] = substr($alias, 5);
800 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
801 $data["addr"] = substr($webfinger["subject"], 5);
805 foreach ($webfinger['links'] as $link) {
806 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
807 $zot_url = $link['href'];
811 if (empty($zot_url) && !empty($data['addr']) && !empty($baseurl)) {
812 $condition = ['nurl' => Strings::normaliseLink($baseurl), 'platform' => ['hubzilla']];
813 if (!DBA::exists('gserver', $condition)) {
816 $zot_url = $baseurl . '/.well-known/zot-info?address=' . $data['addr'];
819 if (empty($zot_url)) {
823 $data = self::pollZot($zot_url, $data);
825 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
826 foreach ($webfinger['aliases'] as $alias) {
827 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
828 $data['alias'] = $alias;
836 public static function pollZot($url, $data)
838 $curlResult = DI::httpRequest()->get($url);
839 if ($curlResult->isTimeout()) {
842 $content = $curlResult->getBody();
847 $json = json_decode($content, true);
848 if (!is_array($json)) {
852 if (empty($data['network'])) {
853 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
854 $data['network'] = Protocol::ZOT;
855 } elseif (!isset($json['protocols'])) {
856 $data['network'] = Protocol::ZOT;
860 if (!empty($json['guid']) && empty($data['guid'])) {
861 $data['guid'] = $json['guid'];
863 if (!empty($json['key']) && empty($data['pubkey'])) {
864 $data['pubkey'] = $json['key'];
866 if (!empty($json['name'])) {
867 $data['name'] = $json['name'];
869 if (!empty($json['photo'])) {
870 $data['photo'] = $json['photo'];
871 if (!empty($json['photo_updated'])) {
872 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
875 if (!empty($json['address'])) {
876 $data['addr'] = $json['address'];
878 if (!empty($json['url'])) {
879 $data['url'] = $json['url'];
881 if (!empty($json['connections_url'])) {
882 $data['poco'] = $json['connections_url'];
884 if (isset($json['searchable'])) {
885 $data['hide'] = !$json['searchable'];
887 if (!empty($json['public_forum'])) {
888 $data['community'] = $json['public_forum'];
889 $data['account-type'] = User::PAGE_FLAGS_COMMUNITY;
892 if (!empty($json['profile'])) {
893 $profile = $json['profile'];
894 if (!empty($profile['description'])) {
895 $data['about'] = $profile['description'];
897 if (!empty($profile['keywords'])) {
898 $keywords = implode(', ', $profile['keywords']);
899 if (!empty($keywords)) {
900 $data['keywords'] = $keywords;
905 if (!empty($profile['region'])) {
906 $loc['region'] = $profile['region'];
908 if (!empty($profile['country'])) {
909 $loc['country-name'] = $profile['country'];
911 $location = Profile::formatLocation($loc);
912 if (!empty($location)) {
913 $data['location'] = $location;
921 * Perform a webfinger request.
923 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
925 * @param string $url Address that should be probed
926 * @param string $type type
928 * @return array webfinger data
929 * @throws HTTPException\InternalServerErrorException
931 public static function webfinger($url, $type)
933 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
935 $curlResult = DI::httpRequest()->get($url, false, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
936 if ($curlResult->isTimeout()) {
937 self::$istimeout = true;
940 $data = $curlResult->getBody();
942 $webfinger = json_decode($data, true);
943 if (!empty($webfinger)) {
944 if (!isset($webfinger["links"])) {
945 Logger::info('No json webfinger links', ['url' => $url]);
951 // If it is not JSON, maybe it is XML
952 $xrd = XML::parseString($data, true);
953 if (!is_object($xrd)) {
954 Logger::info('No webfinger data retrievable', ['url' => $url]);
958 $xrd_arr = XML::elementToArray($xrd);
959 if (!isset($xrd_arr["xrd"]["link"])) {
960 Logger::info('No XML webfinger links', ['url' => $url]);
966 if (!empty($xrd_arr["xrd"]["subject"])) {
967 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
970 if (!empty($xrd_arr["xrd"]["alias"])) {
971 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
974 $webfinger["links"] = [];
976 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
977 if (!empty($data["@attributes"])) {
978 $attributes = $data["@attributes"];
979 } elseif ($value == "@attributes") {
985 $webfinger["links"][] = $attributes;
991 * Poll the Friendica specific noscrape page.
993 * "noscrape" is a faster alternative to fetch the data from the hcard.
994 * This functionality was originally created for the directory.
996 * @param string $noscrape_url Link to the noscrape page
997 * @param array $data The already fetched data
999 * @return array noscrape data
1000 * @throws HTTPException\InternalServerErrorException
1002 private static function pollNoscrape($noscrape_url, $data)
1004 $curlResult = DI::httpRequest()->get($noscrape_url);
1005 if ($curlResult->isTimeout()) {
1006 self::$istimeout = true;
1009 $content = $curlResult->getBody();
1011 Logger::info('Empty body', ['url' => $noscrape_url]);
1015 $json = json_decode($content, true);
1016 if (!is_array($json)) {
1017 Logger::info('No json data', ['url' => $noscrape_url]);
1021 if (!empty($json["fn"])) {
1022 $data["name"] = $json["fn"];
1025 if (!empty($json["addr"])) {
1026 $data["addr"] = $json["addr"];
1029 if (!empty($json["nick"])) {
1030 $data["nick"] = $json["nick"];
1033 if (!empty($json["guid"])) {
1034 $data["guid"] = $json["guid"];
1037 if (!empty($json["comm"])) {
1038 $data["community"] = $json["comm"];
1041 if (!empty($json["tags"])) {
1042 $keywords = implode(", ", $json["tags"]);
1043 if ($keywords != "") {
1044 $data["keywords"] = $keywords;
1048 $location = Profile::formatLocation($json);
1050 $data["location"] = $location;
1053 if (!empty($json["about"])) {
1054 $data["about"] = $json["about"];
1057 if (!empty($json["key"])) {
1058 $data["pubkey"] = $json["key"];
1061 if (!empty($json["photo"])) {
1062 $data["photo"] = $json["photo"];
1065 if (!empty($json["dfrn-request"])) {
1066 $data["request"] = $json["dfrn-request"];
1069 if (!empty($json["dfrn-confirm"])) {
1070 $data["confirm"] = $json["dfrn-confirm"];
1073 if (!empty($json["dfrn-notify"])) {
1074 $data["notify"] = $json["dfrn-notify"];
1077 if (!empty($json["dfrn-poll"])) {
1078 $data["poll"] = $json["dfrn-poll"];
1081 if (isset($json["hide"])) {
1082 $data["hide"] = (bool)$json["hide"];
1084 $data["hide"] = false;
1091 * Check for valid DFRN data
1093 * @param array $data DFRN data
1095 * @return int Number of errors
1097 public static function validDfrn($data)
1100 if (!isset($data['key'])) {
1103 if (!isset($data['dfrn-request'])) {
1106 if (!isset($data['dfrn-confirm'])) {
1109 if (!isset($data['dfrn-notify'])) {
1112 if (!isset($data['dfrn-poll'])) {
1119 * Fetch data from a DFRN profile page and via "noscrape"
1121 * @param string $profile_link Link to the profile page
1123 * @return array profile data
1124 * @throws HTTPException\InternalServerErrorException
1125 * @throws \ImagickException
1127 public static function profile($profile_link)
1131 Logger::info('Check profile', ['link' => $profile_link]);
1133 // Fetch data via noscrape - this is faster
1134 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1135 $data = self::pollNoscrape($noscrape_url, $data);
1137 if (!isset($data["notify"])
1138 || !isset($data["confirm"])
1139 || !isset($data["request"])
1140 || !isset($data["poll"])
1141 || !isset($data["name"])
1142 || !isset($data["photo"])
1144 $data = self::pollHcard($profile_link, $data, true);
1149 if (empty($data["addr"]) || empty($data["nick"])) {
1150 $probe_data = self::uri($profile_link);
1151 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1152 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1155 $prof_data["addr"] = $data["addr"];
1156 $prof_data["nick"] = $data["nick"];
1157 $prof_data["dfrn-request"] = $data['request'] ?? null;
1158 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1159 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1160 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1161 $prof_data["photo"] = $data['photo'] ?? null;
1162 $prof_data["fn"] = $data['name'] ?? null;
1163 $prof_data["key"] = $data['pubkey'] ?? null;
1165 Logger::debug('Result', ['link' => $profile_link, 'data' => $prof_data]);
1171 * Check for DFRN contact
1173 * @param array $webfinger Webfinger data
1175 * @return array DFRN data
1176 * @throws HTTPException\InternalServerErrorException
1178 private static function dfrn($webfinger)
1182 // The array is reversed to take into account the order of preference for same-rel links
1183 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1184 foreach (array_reverse($webfinger["links"]) as $link) {
1185 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1186 $data["network"] = Protocol::DFRN;
1187 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1188 $data["poll"] = $link["href"];
1189 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1190 $data["url"] = $link["href"];
1191 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1192 $hcard_url = $link["href"];
1193 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1194 $data["poco"] = $link["href"];
1195 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1196 $data["photo"] = $link["href"];
1197 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1198 $data["baseurl"] = trim($link["href"], '/');
1199 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1200 $data["guid"] = $link["href"];
1201 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1202 $data["pubkey"] = base64_decode($link["href"]);
1204 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1205 if (strstr($data["pubkey"], 'RSA ')) {
1206 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1211 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1212 foreach ($webfinger["aliases"] as $alias) {
1213 if (empty($data["url"]) && !strstr($alias, "@")) {
1214 $data["url"] = $alias;
1215 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1216 $data["alias"] = $alias;
1217 } elseif (substr($alias, 0, 5) == 'acct:') {
1218 $data["addr"] = substr($alias, 5);
1223 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1224 $data["addr"] = substr($webfinger["subject"], 5);
1227 if (!isset($data["network"]) || ($hcard_url == "")) {
1231 // Fetch data via noscrape - this is faster
1232 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1233 $data = self::pollNoscrape($noscrape_url, $data);
1235 if (isset($data["notify"])
1236 && isset($data["confirm"])
1237 && isset($data["request"])
1238 && isset($data["poll"])
1239 && isset($data["name"])
1240 && isset($data["photo"])
1245 $data = self::pollHcard($hcard_url, $data, true);
1251 * Poll the hcard page (Diaspora and Friendica specific)
1253 * @param string $hcard_url Link to the hcard page
1254 * @param array $data The already fetched data
1255 * @param boolean $dfrn Poll DFRN specific data
1257 * @return array hcard data
1258 * @throws HTTPException\InternalServerErrorException
1260 private static function pollHcard($hcard_url, $data, $dfrn = false)
1262 $curlResult = DI::httpRequest()->get($hcard_url);
1263 if ($curlResult->isTimeout()) {
1264 self::$istimeout = true;
1267 $content = $curlResult->getBody();
1272 $doc = new DOMDocument();
1273 if (!@$doc->loadHTML($content)) {
1277 $xpath = new DomXPath($doc);
1279 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1280 if (!is_object($vcards)) {
1284 if (!isset($data["baseurl"])) {
1285 $data["baseurl"] = "";
1288 if ($vcards->length > 0) {
1289 $vcard = $vcards->item(0);
1291 // We have to discard the guid from the hcard in favour of the guid from lrdd
1292 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1293 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1294 if (($search->length > 0) && empty($data["guid"])) {
1295 $data["guid"] = $search->item(0)->nodeValue;
1298 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1299 if ($search->length > 0) {
1300 $data["nick"] = $search->item(0)->nodeValue;
1303 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1304 if ($search->length > 0) {
1305 $data["name"] = $search->item(0)->nodeValue;
1308 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1309 if ($search->length > 0) {
1310 $data["searchable"] = $search->item(0)->nodeValue;
1313 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1314 if ($search->length > 0) {
1315 $data["pubkey"] = $search->item(0)->nodeValue;
1316 if (strstr($data["pubkey"], 'RSA ')) {
1317 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1321 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1322 if ($search->length > 0) {
1323 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1328 if (!empty($vcard)) {
1329 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1330 foreach ($photos as $photo) {
1332 foreach ($photo->attributes as $attribute) {
1333 $attr[$attribute->name] = trim($attribute->value);
1336 if (isset($attr["src"]) && isset($attr["width"])) {
1337 $avatar[$attr["width"]] = $attr["src"];
1340 // We don't have a width. So we just take everything that we got.
1341 // This is a Hubzilla workaround which doesn't send a width.
1342 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1343 $avatar[] = $attr["src"];
1348 if (sizeof($avatar)) {
1350 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1354 // Poll DFRN specific data
1355 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1356 if ($search->length > 0) {
1357 foreach ($search as $link) {
1358 //$data["request"] = $search->item(0)->nodeValue;
1360 foreach ($link->attributes as $attribute) {
1361 $attr[$attribute->name] = trim($attribute->value);
1364 $data[substr($attr["rel"], 5)] = $attr["href"];
1368 // Older Friendica versions had used the "uid" field differently than newer versions
1369 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1370 unset($data["guid"]);
1379 * Check for Diaspora contact
1381 * @param array $webfinger Webfinger data
1383 * @return array Diaspora data
1384 * @throws HTTPException\InternalServerErrorException
1386 private static function diaspora($webfinger)
1391 // The array is reversed to take into account the order of preference for same-rel links
1392 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1393 foreach (array_reverse($webfinger["links"]) as $link) {
1394 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1395 $hcard_url = $link["href"];
1396 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1397 $data["baseurl"] = trim($link["href"], '/');
1398 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1399 $data["guid"] = $link["href"];
1400 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1401 $data["url"] = $link["href"];
1402 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1403 $data["poll"] = $link["href"];
1404 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1405 $data["poco"] = $link["href"];
1406 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1407 $data["notify"] = $link["href"];
1408 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1409 $data["pubkey"] = base64_decode($link["href"]);
1411 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1412 if (strstr($data["pubkey"], 'RSA ')) {
1413 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1418 if (empty($data["url"]) || empty($hcard_url)) {
1422 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1423 foreach ($webfinger["aliases"] as $alias) {
1424 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1425 $data["alias"] = $alias;
1426 } elseif (substr($alias, 0, 5) == 'acct:') {
1427 $data["addr"] = substr($alias, 5);
1432 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1433 $data["addr"] = substr($webfinger["subject"], 5);
1436 // Fetch further information from the hcard
1437 $data = self::pollHcard($hcard_url, $data);
1443 if (!empty($data["url"])
1444 && !empty($data["guid"])
1445 && !empty($data["baseurl"])
1446 && !empty($data["pubkey"])
1447 && !empty($hcard_url)
1449 $data["network"] = Protocol::DIASPORA;
1451 // The Diaspora handle must always be lowercase
1452 if (!empty($data["addr"])) {
1453 $data["addr"] = strtolower($data["addr"]);
1456 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1457 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1458 $data["batch"] = $data["baseurl"] . "/receive/public";
1467 * Check for OStatus contact
1469 * @param array $webfinger Webfinger data
1470 * @param bool $short Short detection mode
1472 * @return array|bool OStatus data or "false" on error or "true" on short mode
1473 * @throws HTTPException\InternalServerErrorException
1475 private static function ostatus($webfinger, $short = false)
1479 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1480 foreach ($webfinger["aliases"] as $alias) {
1481 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1482 $data["addr"] = str_replace('acct:', '', $alias);
1487 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1488 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1490 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1493 if (!empty($webfinger["links"])) {
1494 // The array is reversed to take into account the order of preference for same-rel links
1495 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1496 foreach (array_reverse($webfinger["links"]) as $link) {
1497 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1498 && (($link["type"] ?? "") == "text/html")
1499 && ($link["href"] != "")
1501 $data["url"] = $data["alias"] = $link["href"];
1502 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1503 $data["notify"] = $link["href"];
1504 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1505 $data["poll"] = $link["href"];
1506 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1507 $pubkey = $link["href"];
1509 if (substr($pubkey, 0, 5) === 'data:') {
1510 if (strstr($pubkey, ',')) {
1511 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1513 $pubkey = substr($pubkey, 5);
1515 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1516 $curlResult = DI::httpRequest()->get($pubkey);
1517 if ($curlResult->isTimeout()) {
1518 self::$istimeout = true;
1519 return $short ? false : [];
1521 $pubkey = $curlResult->getBody();
1524 $key = explode(".", $pubkey);
1526 if (sizeof($key) >= 3) {
1527 $m = Strings::base64UrlDecode($key[1]);
1528 $e = Strings::base64UrlDecode($key[2]);
1529 $data["pubkey"] = Crypto::meToPem($m, $e);
1535 if (isset($data["notify"]) && isset($data["pubkey"])
1536 && isset($data["poll"])
1537 && isset($data["url"])
1539 $data["network"] = Protocol::OSTATUS;
1541 return $short ? false : [];
1548 // Fetch all additional data from the feed
1549 $curlResult = DI::httpRequest()->get($data["poll"]);
1550 if ($curlResult->isTimeout()) {
1551 self::$istimeout = true;
1554 $feed = $curlResult->getBody();
1555 $feed_data = Feed::import($feed);
1560 if (!empty($feed_data["header"]["author-name"])) {
1561 $data["name"] = $feed_data["header"]["author-name"];
1563 if (!empty($feed_data["header"]["author-nick"])) {
1564 $data["nick"] = $feed_data["header"]["author-nick"];
1566 if (!empty($feed_data["header"]["author-avatar"])) {
1567 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1569 if (!empty($feed_data["header"]["author-id"])) {
1570 $data["alias"] = $feed_data["header"]["author-id"];
1572 if (!empty($feed_data["header"]["author-location"])) {
1573 $data["location"] = $feed_data["header"]["author-location"];
1575 if (!empty($feed_data["header"]["author-about"])) {
1576 $data["about"] = $feed_data["header"]["author-about"];
1578 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1579 // So we take the value that we just fetched, although the other one worked as well
1580 if (!empty($feed_data["header"]["author-link"])) {
1581 $data["url"] = $feed_data["header"]["author-link"];
1584 if ($data["url"] == $data["alias"]) {
1585 $data["alias"] = '';
1588 /// @todo Fetch location and "about" from the feed as well
1593 * Fetch data from a pump.io profile page
1595 * @param string $profile_link Link to the profile page
1597 * @return array profile data
1599 private static function pumpioProfileData($profile_link)
1601 $curlResult = DI::httpRequest()->get($profile_link);
1602 if (!$curlResult->isSuccess()) {
1606 $doc = new DOMDocument();
1607 if (!@$doc->loadHTML($curlResult->getBody())) {
1611 $xpath = new DomXPath($doc);
1615 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1617 if ($data["name"] == '') {
1618 // This is ugly - but pump.io doesn't seem to know a better way for it
1619 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1620 $pos = strpos($data["name"], chr(10));
1622 $data["name"] = trim(substr($data["name"], 0, $pos));
1626 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1628 if ($data["location"] == '') {
1629 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1632 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1634 if ($data["about"] == '') {
1635 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1638 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1640 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1643 foreach ($avatar->attributes as $attribute) {
1644 if ($attribute->name == "src") {
1645 $data["photo"] = trim($attribute->value);
1654 * Check for pump.io contact
1656 * @param array $webfinger Webfinger data
1657 * @param string $addr
1658 * @return array pump.io data
1660 private static function pumpio($webfinger, $addr)
1663 // The array is reversed to take into account the order of preference for same-rel links
1664 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1665 foreach (array_reverse($webfinger["links"]) as $link) {
1666 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1667 && (($link["type"] ?? "") == "text/html")
1668 && ($link["href"] != "")
1670 $data["url"] = $link["href"];
1671 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1672 $data["notify"] = $link["href"];
1673 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1674 $data["poll"] = $link["href"];
1675 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1676 $data["dialback"] = $link["href"];
1679 if (isset($data["poll"]) && isset($data["notify"])
1680 && isset($data["dialback"])
1681 && isset($data["url"])
1683 // by now we use these fields only for the network type detection
1684 // So we unset all data that isn't used at the moment
1685 unset($data["dialback"]);
1687 $data["network"] = Protocol::PUMPIO;
1692 $profile_data = self::pumpioProfileData($data["url"]);
1694 if (!$profile_data) {
1698 $data = array_merge($data, $profile_data);
1700 if (($addr != '') && ($data['name'] != '')) {
1701 $name = trim(str_replace($addr, '', $data['name']));
1703 $data['name'] = $name;
1711 * Check for twitter contact
1713 * @param string $uri
1715 * @return array twitter data
1717 private static function twitter($uri)
1719 if (preg_match('=([^@]+)@(?:mobile\.)?twitter\.com$=i', $uri, $matches)) {
1720 $nick = $matches[1];
1721 } elseif (preg_match('=^https?://(?:mobile\.)?twitter\.com/(.+)=i', $uri, $matches)) {
1722 $nick = $matches[1];
1728 $data['url'] = 'https://twitter.com/' . $nick;
1729 $data['addr'] = $nick . '@twitter.com';
1730 $data['nick'] = $data['name'] = $nick;
1731 $data['network'] = Protocol::TWITTER;
1732 $data['baseurl'] = 'https://twitter.com';
1738 * Checks HTML page for RSS feed link
1740 * @param string $url Page link
1741 * @param string $body Page body string
1742 * @return string|false Feed link or false if body was invalid HTML document
1744 public static function getFeedLink(string $url, string $body)
1746 $doc = new DOMDocument();
1747 if (!@$doc->loadHTML($body)) {
1751 $xpath = new DOMXPath($doc);
1753 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1755 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1761 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1763 * Loosely based on RFC 1808
1765 * @see https://tools.ietf.org/html/rfc1808
1767 * @param string $href The potential relative href found in the HTML document
1768 * @param string $base The HTML document URL
1769 * @param DOMXPath $xpath The HTML document XPath
1772 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath)
1774 if (filter_var($href, FILTER_VALIDATE_URL)) {
1778 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1780 $baseParts = parse_url($base);
1781 if (empty($baseParts['host'])) {
1785 // Naked domain case (scheme://basehost)
1786 $path = $baseParts['path'] ?? '/';
1788 // Remove the filename part of the path if it exists (/base/path/file)
1789 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1791 $hrefParts = parse_url($href);
1793 // Root path case (/path) including relative scheme case (//host/path)
1794 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1795 $path = $hrefParts['path'];
1797 $path = $path . '/' . $hrefParts['path'];
1799 // Resolve arbitrary relative path
1800 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1801 $parts = array_filter(explode('/', $path), 'strlen');
1802 $absolutes = array();
1803 foreach ($parts as $part) {
1804 if ('.' == $part) continue;
1805 if ('..' == $part) {
1806 array_pop($absolutes);
1808 $absolutes[] = $part;
1812 $path = '/' . implode('/', $absolutes);
1815 // Relative scheme case (//host/path)
1816 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1817 $baseParts['path'] = $path;
1818 unset($baseParts['query']);
1819 unset($baseParts['fragment']);
1821 return Network::unparseURL($baseParts);
1825 * Check for feed contact
1827 * @param string $url Profile link
1828 * @param boolean $probe Do a probe if the page contains a feed link
1830 * @return array feed data
1831 * @throws HTTPException\InternalServerErrorException
1833 private static function feed($url, $probe = true)
1835 $curlResult = DI::httpRequest()->get($url);
1836 if ($curlResult->isTimeout()) {
1837 self::$istimeout = true;
1840 $feed = $curlResult->getBody();
1841 $feed_data = Feed::import($feed);
1848 $feed_url = self::getFeedLink($url, $feed);
1854 return self::feed($feed_url, false);
1857 if (!empty($feed_data["header"]["author-name"])) {
1858 $data["name"] = $feed_data["header"]["author-name"];
1861 if (!empty($feed_data["header"]["author-nick"])) {
1862 $data["nick"] = $feed_data["header"]["author-nick"];
1865 if (!empty($feed_data["header"]["author-avatar"])) {
1866 $data["photo"] = $feed_data["header"]["author-avatar"];
1869 if (!empty($feed_data["header"]["author-id"])) {
1870 $data["alias"] = $feed_data["header"]["author-id"];
1873 $data["url"] = $url;
1874 $data["poll"] = $url;
1876 $data["network"] = Protocol::FEED;
1882 * Check for mail contact
1884 * @param string $uri Profile link
1885 * @param integer $uid User ID
1887 * @return array mail data
1888 * @throws \Exception
1890 private static function mail($uri, $uid)
1892 if (!Network::isEmailDomainValid($uri)) {
1900 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1902 $condition = ["`uid` = ? AND `server` != ''", $uid];
1903 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1904 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1906 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1910 $mailbox = Email::constructMailboxName($mailacct);
1912 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1913 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1918 $msgs = Email::poll($mbox, $uri);
1919 Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
1921 if (!count($msgs)) {
1925 $phost = substr($uri, strpos($uri, '@') + 1);
1928 $data["addr"] = $uri;
1929 $data["network"] = Protocol::MAIL;
1930 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1931 $data["nick"] = $data["name"];
1932 $data["photo"] = Network::lookupAvatarByEmail($uri);
1933 $data["url"] = 'mailto:'.$uri;
1934 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1935 $data["poll"] = 'email ' . Strings::getRandomHex();
1937 $x = Email::messageMeta($mbox, $msgs[0]);
1938 if (stristr($x[0]->from, $uri)) {
1939 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1940 } elseif (stristr($x[0]->to, $uri)) {
1941 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1944 foreach ($adr as $feadr) {
1945 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1946 &&(strcasecmp($feadr->host, $phost) == 0)
1947 && (strlen($feadr->personal))
1949 $personal = imap_mime_header_decode($feadr->personal);
1951 foreach ($personal as $perspart) {
1952 if ($perspart->charset != "default") {
1953 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1955 $data["name"] .= $perspart->text;
1959 $data["name"] = Strings::escapeTags($data["name"]);
1963 if (!empty($mbox)) {
1970 * Mix two paths together to possibly fix missing parts
1972 * @param string $avatar Path to the avatar
1973 * @param string $base Another path that is hopefully complete
1975 * @return string fixed avatar path
1976 * @throws \Exception
1978 public static function fixAvatar($avatar, $base)
1980 $base_parts = parse_url($base);
1982 // Remove all parts that could create a problem
1983 unset($base_parts['path']);
1984 unset($base_parts['query']);
1985 unset($base_parts['fragment']);
1987 $avatar_parts = parse_url($avatar);
1990 $parts = array_merge($base_parts, $avatar_parts);
1992 // And put them together again
1993 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1994 $host = isset($parts['host']) ? $parts['host'] : '';
1995 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1996 $path = isset($parts['path']) ? $parts['path'] : '';
1997 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1998 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
2000 $fixed = $scheme.$host.$port.$path.$query.$fragment;
2002 Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
2008 * Fetch the last date that the contact had posted something (publically)
2010 * @param string $data probing result
2011 * @return string last activity
2013 public static function getLastUpdate(array $data)
2015 if ($lastUpdate = self::updateFromNoScrape($data)) {
2019 if (!empty($data['outbox'])) {
2020 return self::updateFromOutbox($data['outbox'], $data);
2021 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
2022 return self::updateFromOutbox($data['poll'], $data);
2023 } elseif (!empty($data['poll'])) {
2024 return self::updateFromFeed($data);
2031 * Fetch the last activity date from the "noscrape" endpoint
2033 * @param array $data Probing result
2034 * @return string last activity
2036 * @return bool 'true' if update was successful or the server was unreachable
2038 private static function updateFromNoScrape(array $data)
2040 if (empty($data['baseurl'])) {
2044 // Check the 'noscrape' endpoint when it is a Friendica server
2045 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
2046 Strings::normaliseLink($data['baseurl'])]);
2047 if (!DBA::isResult($gserver)) {
2051 $curlResult = DI::httpRequest()->get($gserver['noscrape'] . '/' . $data['nick']);
2053 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
2054 $noscrape = json_decode($curlResult->getBody(), true);
2055 if (!empty($noscrape) && !empty($noscrape['updated'])) {
2056 return DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2064 * Fetch the last activity date from an ActivityPub Outbox
2066 * @param string $feed
2067 * @param array $data Probing result
2068 * @return string last activity
2069 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2071 private static function updateFromOutbox(string $feed, array $data)
2073 $outbox = ActivityPub::fetchContent($feed);
2074 if (empty($outbox)) {
2078 if (!empty($outbox['orderedItems'])) {
2079 $items = $outbox['orderedItems'];
2080 } elseif (!empty($outbox['first']['orderedItems'])) {
2081 $items = $outbox['first']['orderedItems'];
2082 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2083 return self::updateFromOutbox($outbox['first']['href'], $data);
2084 } elseif (!empty($outbox['first'])) {
2085 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2086 return self::updateFromOutbox($outbox['first'], $data);
2088 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2096 foreach ($items as $activity) {
2097 if (!empty($activity['published'])) {
2098 $published = DateTimeFormat::utc($activity['published']);
2099 } elseif (!empty($activity['object']['published'])) {
2100 $published = DateTimeFormat::utc($activity['object']['published']);
2105 if ($last_updated < $published) {
2106 $last_updated = $published;
2110 if (!empty($last_updated)) {
2111 return $last_updated;
2118 * Fetch the last activity date from an XML feed
2120 * @param array $data Probing result
2121 * @return string last activity
2123 private static function updateFromFeed(array $data)
2125 // Search for the newest entry in the feed
2126 $curlResult = DI::httpRequest()->get($data['poll']);
2127 if (!$curlResult->isSuccess()) {
2131 $doc = new DOMDocument();
2132 @$doc->loadXML($curlResult->getBody());
2134 $xpath = new DOMXPath($doc);
2135 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2137 $entries = $xpath->query('/atom:feed/atom:entry');
2141 foreach ($entries as $entry) {
2142 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2143 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
2144 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2145 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2147 if (empty($published) || empty($updated)) {
2148 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2152 if ($last_updated < $published) {
2153 $last_updated = $published;
2156 if ($last_updated < $updated) {
2157 $last_updated = $updated;
2161 if (!empty($last_updated)) {
2162 return $last_updated;
2169 * Probe data from local profiles without network traffic
2171 * @param string $url
2172 * @return array probed data
2174 private static function localProbe(string $url)
2176 $uid = User::getIdForURL($url);
2181 $profile = User::getOwnerDataById($uid);
2182 if (empty($profile)) {
2186 $approfile = ActivityPub\Transmitter::getProfile($uid);
2187 if (empty($approfile)) {
2191 if (empty($profile['gsid'])) {
2192 $profile['gsid'] = GServer::getID($approfile['generator']['url']);
2195 $data = ['name' => $profile['name'], 'nick' => $profile['nick'], 'guid' => $approfile['diaspora:guid'],
2196 'url' => $profile['url'], 'addr' => $profile['addr'], 'alias' => $profile['alias'],
2197 'photo' => $profile['photo'], 'account-type' => $profile['contact-type'],
2198 'community' => ($profile['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY),
2199 'keywords' => $profile['keywords'], 'location' => $profile['location'], 'about' => $profile['about'],
2200 'hide' => !$profile['net-publish'], 'batch' => '', 'notify' => $profile['notify'],
2201 'poll' => $profile['poll'], 'request' => $profile['request'], 'confirm' => $profile['confirm'],
2202 'subscribe' => $approfile['generator']['url'] . '/follow?url={uri}', 'poco' => $profile['poco'],
2203 'following' => $approfile['following'], 'followers' => $approfile['followers'],
2204 'inbox' => $approfile['inbox'], 'outbox' => $approfile['outbox'],
2205 'sharedinbox' => $approfile['endpoints']['sharedInbox'], 'network' => Protocol::DFRN,
2206 'pubkey' => $profile['upubkey'], 'baseurl' => $approfile['generator']['url'], 'gsid' => $profile['gsid']];
2207 return self::rearrangeData($data);