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\Cache\Duration;
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\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, $cache = true)
333 $cachekey = 'Probe::uri:' . $network . ':' . $uri;
335 $result = DI::cache()->get($cachekey);
336 if (!is_null($result)) {
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() . '/images/person-300.jpg';
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 $data = self::rearrangeData($data);
413 // Only store into the cache if the value seems to be valid
414 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
415 DI::cache()->set($cachekey, $data, Duration::DAY);
423 * Fetches the "hide" status from the profile
425 * @param string $url URL of the profile
427 * @return boolean "hide" status
429 private static function getHideStatus($url)
431 $curlResult = DI::httpRequest()->get($url);
432 if (!$curlResult->isSuccess()) {
436 // If the file is too large then exit
437 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
441 // If it isn't a HTML file then exit
442 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
446 $body = $curlResult->getBody();
448 $doc = new DOMDocument();
449 @$doc->loadHTML($body);
451 $xpath = new DOMXPath($doc);
453 $list = $xpath->query('//meta[@name]');
454 foreach ($list as $node) {
456 if ($node->attributes->length) {
457 foreach ($node->attributes as $attribute) {
458 $meta_tag[$attribute->name] = $attribute->value;
462 if (empty($meta_tag['content'])) {
466 $content = strtolower(trim($meta_tag['content']));
468 switch (strtolower(trim($meta_tag['name']))) {
469 case 'dfrn-global-visibility':
470 if ($content == 'false') {
475 if (strpos($content, 'noindex') !== false) {
486 * Fetch the "subscribe" and add it to the result
488 * @param array $result
489 * @param array $webfinger
490 * @return array result
492 private static function getSubscribeLink(array $result, array $webfinger)
494 if (empty($webfinger['links'])) {
498 foreach ($webfinger['links'] as $link) {
499 if (!empty($link['template']) && ($link['rel'] === ActivityNamespace::OSTATUSSUB)) {
500 $result['subscribe'] = $link['template'];
508 * Get webfinger data from a given URI
511 * @return array Webfinger array
513 private static function getWebfingerArray(string $uri)
515 $parts = parse_url($uri);
517 if (!empty($parts['scheme']) && !empty($parts['host'])) {
518 $host = $parts['host'];
519 if (!empty($parts['port'])) {
520 $host .= ':'.$parts['port'];
523 $baseurl = $parts['scheme'] . '://' . $host;
528 $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
529 if (!empty($path_parts)) {
530 $nick = ltrim(end($path_parts), '@');
531 // When the last part of the URI is numeric then it is most likely an ID and not a nick name
532 if (!is_numeric($nick)) {
533 $addr = $nick."@".$host;
539 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
540 if (empty($webfinger)) {
541 $lrdd = self::hostMeta($host);
544 if (empty($webfinger) && empty($lrdd)) {
545 while (empty($lrdd) && empty($webfinger) && (sizeof($path_parts) > 1)) {
546 $host .= "/".array_shift($path_parts);
547 $baseurl = $parts['scheme'] . '://' . $host;
550 $addr = $nick."@".$host;
553 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
554 if (empty($webfinger)) {
555 $lrdd = self::hostMeta($host);
559 if (empty($lrdd) && empty($webfinger)) {
563 } elseif (strstr($uri, '@')) {
564 // Remove "acct:" from the URI
565 $uri = str_replace('acct:', '', $uri);
567 $host = substr($uri, strpos($uri, '@') + 1);
568 $nick = substr($uri, 0, strpos($uri, '@'));
571 $webfinger = self::getWebfinger('https://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
572 if (self::$istimeout) {
576 if (empty($webfinger)) {
577 $webfinger = self::getWebfinger('http://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
578 if (self::$istimeout) {
582 $baseurl = 'https://' . $host;
585 if (empty($webfinger)) {
586 $lrdd = self::hostMeta($host);
587 if (self::$istimeout) {
590 $baseurl = self::$baseurl;
592 $baseurl = 'http://' . $host;
595 Logger::info('URI was not detectable', ['uri' => $uri]);
599 if (empty($webfinger)) {
600 foreach ($lrdd as $type => $template) {
605 $webfinger = self::getWebfinger($template, $type, $uri, $addr);
609 if (empty($webfinger)) {
613 if ($webfinger['detected'] == $addr) {
614 $webfinger['nick'] = $nick;
615 $webfinger['addr'] = $addr;
618 $webfinger['baseurl'] = $baseurl;
624 * Perform network request for webfinger data
626 * @param string $template
627 * @param string $type
629 * @param string $addr
630 * @return array webfinger results
632 private static function getWebfinger(string $template, string $type, string $uri, string $addr)
634 // First try the address because this is the primary purpose of webfinger
637 $path = str_replace('{uri}', urlencode("acct:" . $addr), $template);
638 $webfinger = self::webfinger($path, $type);
639 if (self::$istimeout) {
645 if (empty($webfinger) && $uri != $addr) {
647 $path = str_replace('{uri}', urlencode($uri), $template);
648 $webfinger = self::webfinger($path, $type);
649 if (self::$istimeout) {
654 if (empty($webfinger)) {
658 return ['webfinger' => $webfinger, 'detected' => $detected];
662 * Fetch information (protocol endpoints and user information) about a given uri
664 * This function is only called by the "uri" function that adds caching and rearranging of data.
666 * @param string $uri Address that should be probed
667 * @param string $network Test for this specific network
668 * @param integer $uid User ID for the probe (only used for mails)
669 * @param array $ap_profile Previously probed AP profile
671 * @return array uri data
672 * @throws HTTPException\InternalServerErrorException
674 private static function detect(string $uri, string $network, int $uid, array $ap_profile)
678 'network' => $network,
683 Hook::callAll('probe_detect', $hookData);
685 if ($hookData['result']) {
686 if (!is_array($hookData['result'])) {
689 return $hookData['result'];
693 $parts = parse_url($uri);
695 if (!empty($parts['scheme']) && !empty($parts['host'])) {
696 if (in_array($parts['host'], ['twitter.com', 'mobile.twitter.com'])) {
697 return self::twitter($uri);
699 } elseif (strstr($uri, '@')) {
700 // If the URI starts with "mailto:" then jump directly to the mail detection
701 if (strpos($uri, 'mailto:') !== false) {
702 $uri = str_replace('mailto:', '', $uri);
703 return self::mail($uri, $uid);
706 if ($network == Protocol::MAIL) {
707 return self::mail($uri, $uid);
710 if (Strings::endsWith($uri, '@twitter.com')
711 || Strings::endsWith($uri, '@mobile.twitter.com')
713 return self::twitter($uri);
716 Logger::info('URI was not detectable', ['uri' => $uri]);
720 Logger::info('Probing start', ['uri' => $uri]);
722 $data = self::getWebfingerArray($uri);
724 if (!empty($parts['scheme'])) {
725 return self::feed($uri);
726 } elseif (!empty($uid)) {
727 return self::mail($uri, $uid);
733 $webfinger = $data['webfinger'];
734 $nick = $data['nick'] ?? '';
735 $addr = $data['addr'] ?? '';
736 $baseurl = $data['baseurl'] ?? '';
740 if (in_array($network, ["", Protocol::DFRN])) {
741 $result = self::dfrn($webfinger);
743 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
744 $result = self::diaspora($webfinger);
746 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
747 $result = self::ostatus($webfinger);
749 if (in_array($network, ['', Protocol::ZOT])) {
750 $result = self::zot($webfinger, $result, $baseurl);
752 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
753 $result = self::pumpio($webfinger, $addr);
755 if (empty($result['network']) && empty($ap_profile['network']) || ($network == Protocol::FEED)) {
756 $result = self::feed($uri);
758 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
759 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
760 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
761 $result["nick"] = $nick;
764 if (empty($result["addr"]) && ($addr != "")) {
765 $result["addr"] = $addr;
769 $result = self::getSubscribeLink($result, $webfinger);
771 if (empty($result["network"])) {
772 $result["network"] = Protocol::PHANTOM;
775 if (empty($result['baseurl']) && !empty($baseurl)) {
776 $result['baseurl'] = $baseurl;
779 if (empty($result["url"])) {
780 $result["url"] = $uri;
783 Logger::info('Probing done', ['uri' => $uri, 'network' => $result["network"]]);
789 * Check for Zot contact
791 * @param array $webfinger Webfinger data
792 * @param array $data previously probed data
794 * @return array Zot data
795 * @throws HTTPException\InternalServerErrorException
797 private static function zot($webfinger, $data, $baseurl)
799 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
800 foreach ($webfinger["aliases"] as $alias) {
801 if (substr($alias, 0, 5) == 'acct:') {
802 $data["addr"] = substr($alias, 5);
807 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
808 $data["addr"] = substr($webfinger["subject"], 5);
812 foreach ($webfinger['links'] as $link) {
813 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
814 $zot_url = $link['href'];
818 if (empty($zot_url) && !empty($data['addr']) && !empty($baseurl)) {
819 $condition = ['nurl' => Strings::normaliseLink($baseurl), 'platform' => ['hubzilla']];
820 if (!DBA::exists('gserver', $condition)) {
823 $zot_url = $baseurl . '/.well-known/zot-info?address=' . $data['addr'];
826 if (empty($zot_url)) {
830 $data = self::pollZot($zot_url, $data);
832 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
833 foreach ($webfinger['aliases'] as $alias) {
834 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
835 $data['alias'] = $alias;
843 public static function pollZot($url, $data)
845 $curlResult = DI::httpRequest()->get($url);
846 if ($curlResult->isTimeout()) {
849 $content = $curlResult->getBody();
854 $json = json_decode($content, true);
855 if (!is_array($json)) {
859 if (empty($data['network'])) {
860 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
861 $data['network'] = Protocol::ZOT;
862 } elseif (!isset($json['protocols'])) {
863 $data['network'] = Protocol::ZOT;
867 if (!empty($json['guid']) && empty($data['guid'])) {
868 $data['guid'] = $json['guid'];
870 if (!empty($json['key']) && empty($data['pubkey'])) {
871 $data['pubkey'] = $json['key'];
873 if (!empty($json['name'])) {
874 $data['name'] = $json['name'];
876 if (!empty($json['photo'])) {
877 $data['photo'] = $json['photo'];
878 if (!empty($json['photo_updated'])) {
879 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
882 if (!empty($json['address'])) {
883 $data['addr'] = $json['address'];
885 if (!empty($json['url'])) {
886 $data['url'] = $json['url'];
888 if (!empty($json['connections_url'])) {
889 $data['poco'] = $json['connections_url'];
891 if (isset($json['searchable'])) {
892 $data['hide'] = !$json['searchable'];
894 if (!empty($json['public_forum'])) {
895 $data['community'] = $json['public_forum'];
896 $data['account-type'] = User::PAGE_FLAGS_COMMUNITY;
899 if (!empty($json['profile'])) {
900 $profile = $json['profile'];
901 if (!empty($profile['description'])) {
902 $data['about'] = $profile['description'];
904 if (!empty($profile['keywords'])) {
905 $keywords = implode(', ', $profile['keywords']);
906 if (!empty($keywords)) {
907 $data['keywords'] = $keywords;
912 if (!empty($profile['region'])) {
913 $loc['region'] = $profile['region'];
915 if (!empty($profile['country'])) {
916 $loc['country-name'] = $profile['country'];
918 $location = Profile::formatLocation($loc);
919 if (!empty($location)) {
920 $data['location'] = $location;
928 * Perform a webfinger request.
930 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
932 * @param string $url Address that should be probed
933 * @param string $type type
935 * @return array webfinger data
936 * @throws HTTPException\InternalServerErrorException
938 public static function webfinger($url, $type)
940 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
942 $curlResult = DI::httpRequest()->get($url, false, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
943 if ($curlResult->isTimeout()) {
944 self::$istimeout = true;
947 $data = $curlResult->getBody();
949 $webfinger = json_decode($data, true);
950 if (!empty($webfinger)) {
951 if (!isset($webfinger["links"])) {
952 Logger::info('No json webfinger links', ['url' => $url]);
958 // If it is not JSON, maybe it is XML
959 $xrd = XML::parseString($data, true);
960 if (!is_object($xrd)) {
961 Logger::info('No webfinger data retrievable', ['url' => $url]);
965 $xrd_arr = XML::elementToArray($xrd);
966 if (!isset($xrd_arr["xrd"]["link"])) {
967 Logger::info('No XML webfinger links', ['url' => $url]);
973 if (!empty($xrd_arr["xrd"]["subject"])) {
974 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
977 if (!empty($xrd_arr["xrd"]["alias"])) {
978 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
981 $webfinger["links"] = [];
983 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
984 if (!empty($data["@attributes"])) {
985 $attributes = $data["@attributes"];
986 } elseif ($value == "@attributes") {
992 $webfinger["links"][] = $attributes;
998 * Poll the Friendica specific noscrape page.
1000 * "noscrape" is a faster alternative to fetch the data from the hcard.
1001 * This functionality was originally created for the directory.
1003 * @param string $noscrape_url Link to the noscrape page
1004 * @param array $data The already fetched data
1006 * @return array noscrape data
1007 * @throws HTTPException\InternalServerErrorException
1009 private static function pollNoscrape($noscrape_url, $data)
1011 $curlResult = DI::httpRequest()->get($noscrape_url);
1012 if ($curlResult->isTimeout()) {
1013 self::$istimeout = true;
1016 $content = $curlResult->getBody();
1018 Logger::info('Empty body', ['url' => $noscrape_url]);
1022 $json = json_decode($content, true);
1023 if (!is_array($json)) {
1024 Logger::info('No json data', ['url' => $noscrape_url]);
1028 if (!empty($json["fn"])) {
1029 $data["name"] = $json["fn"];
1032 if (!empty($json["addr"])) {
1033 $data["addr"] = $json["addr"];
1036 if (!empty($json["nick"])) {
1037 $data["nick"] = $json["nick"];
1040 if (!empty($json["guid"])) {
1041 $data["guid"] = $json["guid"];
1044 if (!empty($json["comm"])) {
1045 $data["community"] = $json["comm"];
1048 if (!empty($json["tags"])) {
1049 $keywords = implode(", ", $json["tags"]);
1050 if ($keywords != "") {
1051 $data["keywords"] = $keywords;
1055 $location = Profile::formatLocation($json);
1057 $data["location"] = $location;
1060 if (!empty($json["about"])) {
1061 $data["about"] = $json["about"];
1064 if (!empty($json["key"])) {
1065 $data["pubkey"] = $json["key"];
1068 if (!empty($json["photo"])) {
1069 $data["photo"] = $json["photo"];
1072 if (!empty($json["dfrn-request"])) {
1073 $data["request"] = $json["dfrn-request"];
1076 if (!empty($json["dfrn-confirm"])) {
1077 $data["confirm"] = $json["dfrn-confirm"];
1080 if (!empty($json["dfrn-notify"])) {
1081 $data["notify"] = $json["dfrn-notify"];
1084 if (!empty($json["dfrn-poll"])) {
1085 $data["poll"] = $json["dfrn-poll"];
1088 if (isset($json["hide"])) {
1089 $data["hide"] = (bool)$json["hide"];
1091 $data["hide"] = false;
1098 * Check for valid DFRN data
1100 * @param array $data DFRN data
1102 * @return int Number of errors
1104 public static function validDfrn($data)
1107 if (!isset($data['key'])) {
1110 if (!isset($data['dfrn-request'])) {
1113 if (!isset($data['dfrn-confirm'])) {
1116 if (!isset($data['dfrn-notify'])) {
1119 if (!isset($data['dfrn-poll'])) {
1126 * Fetch data from a DFRN profile page and via "noscrape"
1128 * @param string $profile_link Link to the profile page
1130 * @return array profile data
1131 * @throws HTTPException\InternalServerErrorException
1132 * @throws \ImagickException
1134 public static function profile($profile_link)
1138 Logger::info('Check profile', ['link' => $profile_link]);
1140 // Fetch data via noscrape - this is faster
1141 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1142 $data = self::pollNoscrape($noscrape_url, $data);
1144 if (!isset($data["notify"])
1145 || !isset($data["confirm"])
1146 || !isset($data["request"])
1147 || !isset($data["poll"])
1148 || !isset($data["name"])
1149 || !isset($data["photo"])
1151 $data = self::pollHcard($profile_link, $data, true);
1156 if (empty($data["addr"]) || empty($data["nick"])) {
1157 $probe_data = self::uri($profile_link);
1158 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1159 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1162 $prof_data["addr"] = $data["addr"];
1163 $prof_data["nick"] = $data["nick"];
1164 $prof_data["dfrn-request"] = $data['request'] ?? null;
1165 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1166 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1167 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1168 $prof_data["photo"] = $data['photo'] ?? null;
1169 $prof_data["fn"] = $data['name'] ?? null;
1170 $prof_data["key"] = $data['pubkey'] ?? null;
1172 Logger::debug('Result', ['link' => $profile_link, 'data' => $prof_data]);
1178 * Check for DFRN contact
1180 * @param array $webfinger Webfinger data
1182 * @return array DFRN data
1183 * @throws HTTPException\InternalServerErrorException
1185 private static function dfrn($webfinger)
1189 // The array is reversed to take into account the order of preference for same-rel links
1190 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1191 foreach (array_reverse($webfinger["links"]) as $link) {
1192 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1193 $data["network"] = Protocol::DFRN;
1194 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1195 $data["poll"] = $link["href"];
1196 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1197 $data["url"] = $link["href"];
1198 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1199 $hcard_url = $link["href"];
1200 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1201 $data["poco"] = $link["href"];
1202 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1203 $data["photo"] = $link["href"];
1204 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1205 $data["baseurl"] = trim($link["href"], '/');
1206 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1207 $data["guid"] = $link["href"];
1208 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1209 $data["pubkey"] = base64_decode($link["href"]);
1211 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1212 if (strstr($data["pubkey"], 'RSA ')) {
1213 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1218 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1219 foreach ($webfinger["aliases"] as $alias) {
1220 if (empty($data["url"]) && !strstr($alias, "@")) {
1221 $data["url"] = $alias;
1222 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1223 $data["alias"] = $alias;
1224 } elseif (substr($alias, 0, 5) == 'acct:') {
1225 $data["addr"] = substr($alias, 5);
1230 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1231 $data["addr"] = substr($webfinger["subject"], 5);
1234 if (!isset($data["network"]) || ($hcard_url == "")) {
1238 // Fetch data via noscrape - this is faster
1239 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1240 $data = self::pollNoscrape($noscrape_url, $data);
1242 if (isset($data["notify"])
1243 && isset($data["confirm"])
1244 && isset($data["request"])
1245 && isset($data["poll"])
1246 && isset($data["name"])
1247 && isset($data["photo"])
1252 $data = self::pollHcard($hcard_url, $data, true);
1258 * Poll the hcard page (Diaspora and Friendica specific)
1260 * @param string $hcard_url Link to the hcard page
1261 * @param array $data The already fetched data
1262 * @param boolean $dfrn Poll DFRN specific data
1264 * @return array hcard data
1265 * @throws HTTPException\InternalServerErrorException
1267 private static function pollHcard($hcard_url, $data, $dfrn = false)
1269 $curlResult = DI::httpRequest()->get($hcard_url);
1270 if ($curlResult->isTimeout()) {
1271 self::$istimeout = true;
1274 $content = $curlResult->getBody();
1279 $doc = new DOMDocument();
1280 if (!@$doc->loadHTML($content)) {
1284 $xpath = new DomXPath($doc);
1286 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1287 if (!is_object($vcards)) {
1291 if (!isset($data["baseurl"])) {
1292 $data["baseurl"] = "";
1295 if ($vcards->length > 0) {
1296 $vcard = $vcards->item(0);
1298 // We have to discard the guid from the hcard in favour of the guid from lrdd
1299 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1300 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1301 if (($search->length > 0) && empty($data["guid"])) {
1302 $data["guid"] = $search->item(0)->nodeValue;
1305 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1306 if ($search->length > 0) {
1307 $data["nick"] = $search->item(0)->nodeValue;
1310 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1311 if ($search->length > 0) {
1312 $data["name"] = $search->item(0)->nodeValue;
1315 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1316 if ($search->length > 0) {
1317 $data["searchable"] = $search->item(0)->nodeValue;
1320 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1321 if ($search->length > 0) {
1322 $data["pubkey"] = $search->item(0)->nodeValue;
1323 if (strstr($data["pubkey"], 'RSA ')) {
1324 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1328 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1329 if ($search->length > 0) {
1330 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1335 if (!empty($vcard)) {
1336 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1337 foreach ($photos as $photo) {
1339 foreach ($photo->attributes as $attribute) {
1340 $attr[$attribute->name] = trim($attribute->value);
1343 if (isset($attr["src"]) && isset($attr["width"])) {
1344 $avatar[$attr["width"]] = $attr["src"];
1347 // We don't have a width. So we just take everything that we got.
1348 // This is a Hubzilla workaround which doesn't send a width.
1349 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1350 $avatar[] = $attr["src"];
1355 if (sizeof($avatar)) {
1357 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1361 // Poll DFRN specific data
1362 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1363 if ($search->length > 0) {
1364 foreach ($search as $link) {
1365 //$data["request"] = $search->item(0)->nodeValue;
1367 foreach ($link->attributes as $attribute) {
1368 $attr[$attribute->name] = trim($attribute->value);
1371 $data[substr($attr["rel"], 5)] = $attr["href"];
1375 // Older Friendica versions had used the "uid" field differently than newer versions
1376 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1377 unset($data["guid"]);
1386 * Check for Diaspora contact
1388 * @param array $webfinger Webfinger data
1390 * @return array Diaspora data
1391 * @throws HTTPException\InternalServerErrorException
1393 private static function diaspora($webfinger)
1398 // The array is reversed to take into account the order of preference for same-rel links
1399 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1400 foreach (array_reverse($webfinger["links"]) as $link) {
1401 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1402 $hcard_url = $link["href"];
1403 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1404 $data["baseurl"] = trim($link["href"], '/');
1405 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1406 $data["guid"] = $link["href"];
1407 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1408 $data["url"] = $link["href"];
1409 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1410 $data["poll"] = $link["href"];
1411 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1412 $data["poco"] = $link["href"];
1413 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1414 $data["notify"] = $link["href"];
1415 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1416 $data["pubkey"] = base64_decode($link["href"]);
1418 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1419 if (strstr($data["pubkey"], 'RSA ')) {
1420 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1425 if (empty($data["url"]) || empty($hcard_url)) {
1429 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1430 foreach ($webfinger["aliases"] as $alias) {
1431 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1432 $data["alias"] = $alias;
1433 } elseif (substr($alias, 0, 5) == 'acct:') {
1434 $data["addr"] = substr($alias, 5);
1439 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1440 $data["addr"] = substr($webfinger["subject"], 5);
1443 // Fetch further information from the hcard
1444 $data = self::pollHcard($hcard_url, $data);
1450 if (!empty($data["url"])
1451 && !empty($data["guid"])
1452 && !empty($data["baseurl"])
1453 && !empty($data["pubkey"])
1454 && !empty($hcard_url)
1456 $data["network"] = Protocol::DIASPORA;
1458 // The Diaspora handle must always be lowercase
1459 if (!empty($data["addr"])) {
1460 $data["addr"] = strtolower($data["addr"]);
1463 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1464 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1465 $data["batch"] = $data["baseurl"] . "/receive/public";
1474 * Check for OStatus contact
1476 * @param array $webfinger Webfinger data
1477 * @param bool $short Short detection mode
1479 * @return array|bool OStatus data or "false" on error or "true" on short mode
1480 * @throws HTTPException\InternalServerErrorException
1482 private static function ostatus($webfinger, $short = false)
1486 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1487 foreach ($webfinger["aliases"] as $alias) {
1488 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1489 $data["addr"] = str_replace('acct:', '', $alias);
1494 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1495 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1497 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1500 if (!empty($webfinger["links"])) {
1501 // The array is reversed to take into account the order of preference for same-rel links
1502 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1503 foreach (array_reverse($webfinger["links"]) as $link) {
1504 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1505 && (($link["type"] ?? "") == "text/html")
1506 && ($link["href"] != "")
1508 $data["url"] = $data["alias"] = $link["href"];
1509 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1510 $data["notify"] = $link["href"];
1511 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1512 $data["poll"] = $link["href"];
1513 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1514 $pubkey = $link["href"];
1516 if (substr($pubkey, 0, 5) === 'data:') {
1517 if (strstr($pubkey, ',')) {
1518 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1520 $pubkey = substr($pubkey, 5);
1522 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1523 $curlResult = DI::httpRequest()->get($pubkey);
1524 if ($curlResult->isTimeout()) {
1525 self::$istimeout = true;
1526 return $short ? false : [];
1528 $pubkey = $curlResult->getBody();
1531 $key = explode(".", $pubkey);
1533 if (sizeof($key) >= 3) {
1534 $m = Strings::base64UrlDecode($key[1]);
1535 $e = Strings::base64UrlDecode($key[2]);
1536 $data["pubkey"] = Crypto::meToPem($m, $e);
1542 if (isset($data["notify"]) && isset($data["pubkey"])
1543 && isset($data["poll"])
1544 && isset($data["url"])
1546 $data["network"] = Protocol::OSTATUS;
1548 return $short ? false : [];
1555 // Fetch all additional data from the feed
1556 $curlResult = DI::httpRequest()->get($data["poll"]);
1557 if ($curlResult->isTimeout()) {
1558 self::$istimeout = true;
1561 $feed = $curlResult->getBody();
1562 $feed_data = Feed::import($feed);
1567 if (!empty($feed_data["header"]["author-name"])) {
1568 $data["name"] = $feed_data["header"]["author-name"];
1570 if (!empty($feed_data["header"]["author-nick"])) {
1571 $data["nick"] = $feed_data["header"]["author-nick"];
1573 if (!empty($feed_data["header"]["author-avatar"])) {
1574 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1576 if (!empty($feed_data["header"]["author-id"])) {
1577 $data["alias"] = $feed_data["header"]["author-id"];
1579 if (!empty($feed_data["header"]["author-location"])) {
1580 $data["location"] = $feed_data["header"]["author-location"];
1582 if (!empty($feed_data["header"]["author-about"])) {
1583 $data["about"] = $feed_data["header"]["author-about"];
1585 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1586 // So we take the value that we just fetched, although the other one worked as well
1587 if (!empty($feed_data["header"]["author-link"])) {
1588 $data["url"] = $feed_data["header"]["author-link"];
1591 if ($data["url"] == $data["alias"]) {
1592 $data["alias"] = '';
1595 /// @todo Fetch location and "about" from the feed as well
1600 * Fetch data from a pump.io profile page
1602 * @param string $profile_link Link to the profile page
1604 * @return array profile data
1606 private static function pumpioProfileData($profile_link)
1608 $curlResult = DI::httpRequest()->get($profile_link);
1609 if (!$curlResult->isSuccess()) {
1613 $doc = new DOMDocument();
1614 if (!@$doc->loadHTML($curlResult->getBody())) {
1618 $xpath = new DomXPath($doc);
1622 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1624 if ($data["name"] == '') {
1625 // This is ugly - but pump.io doesn't seem to know a better way for it
1626 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1627 $pos = strpos($data["name"], chr(10));
1629 $data["name"] = trim(substr($data["name"], 0, $pos));
1633 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1635 if ($data["location"] == '') {
1636 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1639 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1641 if ($data["about"] == '') {
1642 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1645 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1647 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1650 foreach ($avatar->attributes as $attribute) {
1651 if ($attribute->name == "src") {
1652 $data["photo"] = trim($attribute->value);
1661 * Check for pump.io contact
1663 * @param array $webfinger Webfinger data
1664 * @param string $addr
1665 * @return array pump.io data
1667 private static function pumpio($webfinger, $addr)
1670 // The array is reversed to take into account the order of preference for same-rel links
1671 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1672 foreach (array_reverse($webfinger["links"]) as $link) {
1673 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1674 && (($link["type"] ?? "") == "text/html")
1675 && ($link["href"] != "")
1677 $data["url"] = $link["href"];
1678 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1679 $data["notify"] = $link["href"];
1680 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1681 $data["poll"] = $link["href"];
1682 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1683 $data["dialback"] = $link["href"];
1686 if (isset($data["poll"]) && isset($data["notify"])
1687 && isset($data["dialback"])
1688 && isset($data["url"])
1690 // by now we use these fields only for the network type detection
1691 // So we unset all data that isn't used at the moment
1692 unset($data["dialback"]);
1694 $data["network"] = Protocol::PUMPIO;
1699 $profile_data = self::pumpioProfileData($data["url"]);
1701 if (!$profile_data) {
1705 $data = array_merge($data, $profile_data);
1707 if (($addr != '') && ($data['name'] != '')) {
1708 $name = trim(str_replace($addr, '', $data['name']));
1710 $data['name'] = $name;
1718 * Check for twitter contact
1720 * @param string $uri
1722 * @return array twitter data
1724 private static function twitter($uri)
1726 if (preg_match('=([^@]+)@(?:mobile\.)?twitter\.com$=i', $uri, $matches)) {
1727 $nick = $matches[1];
1728 } elseif (preg_match('=^https?://(?:mobile\.)?twitter\.com/(.+)=i', $uri, $matches)) {
1729 $nick = $matches[1];
1735 $data['url'] = 'https://twitter.com/' . $nick;
1736 $data['addr'] = $nick . '@twitter.com';
1737 $data['nick'] = $data['name'] = $nick;
1738 $data['network'] = Protocol::TWITTER;
1739 $data['baseurl'] = 'https://twitter.com';
1745 * Checks HTML page for RSS feed link
1747 * @param string $url Page link
1748 * @param string $body Page body string
1749 * @return string|false Feed link or false if body was invalid HTML document
1751 public static function getFeedLink(string $url, string $body)
1753 $doc = new DOMDocument();
1754 if (!@$doc->loadHTML($body)) {
1758 $xpath = new DOMXPath($doc);
1760 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1762 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1768 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1770 * Loosely based on RFC 1808
1772 * @see https://tools.ietf.org/html/rfc1808
1774 * @param string $href The potential relative href found in the HTML document
1775 * @param string $base The HTML document URL
1776 * @param DOMXPath $xpath The HTML document XPath
1779 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath)
1781 if (filter_var($href, FILTER_VALIDATE_URL)) {
1785 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1787 $baseParts = parse_url($base);
1788 if (empty($baseParts['host'])) {
1792 // Naked domain case (scheme://basehost)
1793 $path = $baseParts['path'] ?? '/';
1795 // Remove the filename part of the path if it exists (/base/path/file)
1796 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1798 $hrefParts = parse_url($href);
1800 // Root path case (/path) including relative scheme case (//host/path)
1801 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1802 $path = $hrefParts['path'];
1804 $path = $path . '/' . $hrefParts['path'];
1806 // Resolve arbitrary relative path
1807 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1808 $parts = array_filter(explode('/', $path), 'strlen');
1809 $absolutes = array();
1810 foreach ($parts as $part) {
1811 if ('.' == $part) continue;
1812 if ('..' == $part) {
1813 array_pop($absolutes);
1815 $absolutes[] = $part;
1819 $path = '/' . implode('/', $absolutes);
1822 // Relative scheme case (//host/path)
1823 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1824 $baseParts['path'] = $path;
1825 unset($baseParts['query']);
1826 unset($baseParts['fragment']);
1828 return Network::unparseURL($baseParts);
1832 * Check for feed contact
1834 * @param string $url Profile link
1835 * @param boolean $probe Do a probe if the page contains a feed link
1837 * @return array feed data
1838 * @throws HTTPException\InternalServerErrorException
1840 private static function feed($url, $probe = true)
1842 $curlResult = DI::httpRequest()->get($url);
1843 if ($curlResult->isTimeout()) {
1844 self::$istimeout = true;
1847 $feed = $curlResult->getBody();
1848 $feed_data = Feed::import($feed);
1855 $feed_url = self::getFeedLink($url, $feed);
1861 return self::feed($feed_url, false);
1864 if (!empty($feed_data["header"]["author-name"])) {
1865 $data["name"] = $feed_data["header"]["author-name"];
1868 if (!empty($feed_data["header"]["author-nick"])) {
1869 $data["nick"] = $feed_data["header"]["author-nick"];
1872 if (!empty($feed_data["header"]["author-avatar"])) {
1873 $data["photo"] = $feed_data["header"]["author-avatar"];
1876 if (!empty($feed_data["header"]["author-id"])) {
1877 $data["alias"] = $feed_data["header"]["author-id"];
1880 $data["url"] = $url;
1881 $data["poll"] = $url;
1883 $data["network"] = Protocol::FEED;
1889 * Check for mail contact
1891 * @param string $uri Profile link
1892 * @param integer $uid User ID
1894 * @return array mail data
1895 * @throws \Exception
1897 private static function mail($uri, $uid)
1899 if (!Network::isEmailDomainValid($uri)) {
1907 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1909 $condition = ["`uid` = ? AND `server` != ''", $uid];
1910 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1911 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1913 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1917 $mailbox = Email::constructMailboxName($mailacct);
1919 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1920 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1925 $msgs = Email::poll($mbox, $uri);
1926 Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
1928 if (!count($msgs)) {
1932 $phost = substr($uri, strpos($uri, '@') + 1);
1935 $data["addr"] = $uri;
1936 $data["network"] = Protocol::MAIL;
1937 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1938 $data["nick"] = $data["name"];
1939 $data["photo"] = Network::lookupAvatarByEmail($uri);
1940 $data["url"] = 'mailto:'.$uri;
1941 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1942 $data["poll"] = 'email ' . Strings::getRandomHex();
1944 $x = Email::messageMeta($mbox, $msgs[0]);
1945 if (stristr($x[0]->from, $uri)) {
1946 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1947 } elseif (stristr($x[0]->to, $uri)) {
1948 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1951 foreach ($adr as $feadr) {
1952 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1953 &&(strcasecmp($feadr->host, $phost) == 0)
1954 && (strlen($feadr->personal))
1956 $personal = imap_mime_header_decode($feadr->personal);
1958 foreach ($personal as $perspart) {
1959 if ($perspart->charset != "default") {
1960 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1962 $data["name"] .= $perspart->text;
1966 $data["name"] = Strings::escapeTags($data["name"]);
1970 if (!empty($mbox)) {
1977 * Mix two paths together to possibly fix missing parts
1979 * @param string $avatar Path to the avatar
1980 * @param string $base Another path that is hopefully complete
1982 * @return string fixed avatar path
1983 * @throws \Exception
1985 public static function fixAvatar($avatar, $base)
1987 $base_parts = parse_url($base);
1989 // Remove all parts that could create a problem
1990 unset($base_parts['path']);
1991 unset($base_parts['query']);
1992 unset($base_parts['fragment']);
1994 $avatar_parts = parse_url($avatar);
1997 $parts = array_merge($base_parts, $avatar_parts);
1999 // And put them together again
2000 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
2001 $host = isset($parts['host']) ? $parts['host'] : '';
2002 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
2003 $path = isset($parts['path']) ? $parts['path'] : '';
2004 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
2005 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
2007 $fixed = $scheme.$host.$port.$path.$query.$fragment;
2009 Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
2015 * Fetch the last date that the contact had posted something (publically)
2017 * @param string $data probing result
2018 * @return string last activity
2020 public static function getLastUpdate(array $data)
2022 if ($lastUpdate = self::updateFromNoScrape($data)) {
2026 if (!empty($data['outbox'])) {
2027 return self::updateFromOutbox($data['outbox'], $data);
2028 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
2029 return self::updateFromOutbox($data['poll'], $data);
2030 } elseif (!empty($data['poll'])) {
2031 return self::updateFromFeed($data);
2038 * Fetch the last activity date from the "noscrape" endpoint
2040 * @param array $data Probing result
2041 * @return string last activity
2043 * @return bool 'true' if update was successful or the server was unreachable
2045 private static function updateFromNoScrape(array $data)
2047 if (empty($data['baseurl'])) {
2051 // Check the 'noscrape' endpoint when it is a Friendica server
2052 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
2053 Strings::normaliseLink($data['baseurl'])]);
2054 if (!DBA::isResult($gserver)) {
2058 $curlResult = DI::httpRequest()->get($gserver['noscrape'] . '/' . $data['nick']);
2060 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
2061 $noscrape = json_decode($curlResult->getBody(), true);
2062 if (!empty($noscrape) && !empty($noscrape['updated'])) {
2063 return DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2071 * Fetch the last activity date from an ActivityPub Outbox
2073 * @param string $feed
2074 * @param array $data Probing result
2075 * @return string last activity
2076 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2078 private static function updateFromOutbox(string $feed, array $data)
2080 $outbox = ActivityPub::fetchContent($feed);
2081 if (empty($outbox)) {
2085 if (!empty($outbox['orderedItems'])) {
2086 $items = $outbox['orderedItems'];
2087 } elseif (!empty($outbox['first']['orderedItems'])) {
2088 $items = $outbox['first']['orderedItems'];
2089 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2090 return self::updateFromOutbox($outbox['first']['href'], $data);
2091 } elseif (!empty($outbox['first'])) {
2092 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2093 return self::updateFromOutbox($outbox['first'], $data);
2095 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2103 foreach ($items as $activity) {
2104 if (!empty($activity['published'])) {
2105 $published = DateTimeFormat::utc($activity['published']);
2106 } elseif (!empty($activity['object']['published'])) {
2107 $published = DateTimeFormat::utc($activity['object']['published']);
2112 if ($last_updated < $published) {
2113 $last_updated = $published;
2117 if (!empty($last_updated)) {
2118 return $last_updated;
2125 * Fetch the last activity date from an XML feed
2127 * @param array $data Probing result
2128 * @return string last activity
2130 private static function updateFromFeed(array $data)
2132 // Search for the newest entry in the feed
2133 $curlResult = DI::httpRequest()->get($data['poll']);
2134 if (!$curlResult->isSuccess()) {
2138 $doc = new DOMDocument();
2139 @$doc->loadXML($curlResult->getBody());
2141 $xpath = new DOMXPath($doc);
2142 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2144 $entries = $xpath->query('/atom:feed/atom:entry');
2148 foreach ($entries as $entry) {
2149 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2150 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
2151 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2152 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2154 if (empty($published) || empty($updated)) {
2155 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2159 if ($last_updated < $published) {
2160 $last_updated = $published;
2163 if ($last_updated < $updated) {
2164 $last_updated = $updated;
2168 if (!empty($last_updated)) {
2169 return $last_updated;