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\GServer;
33 use Friendica\Model\Profile;
34 use Friendica\Model\User;
35 use Friendica\Protocol\ActivityNamespace;
36 use Friendica\Protocol\ActivityPub;
37 use Friendica\Protocol\Email;
38 use Friendica\Protocol\Feed;
39 use Friendica\Util\Crypto;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\Network;
42 use Friendica\Util\Strings;
43 use Friendica\Util\XML;
46 * This class contain functions for probing URL
50 const WEBFINGER = '/.well-known/webfinger?resource={uri}';
52 private static $baseurl;
53 private static $istimeout;
56 * Remove stuff from an URI that doesn't belong there
59 * @return string Cleaned URI
61 public static function cleanURI(string $URI)
63 // At first remove leading and trailing junk
64 $URI = trim($URI, "@#?:/ \t\n\r\0\x0B");
66 $parts = parse_url($URI);
68 if (empty($parts['scheme'])) {
72 // Remove the URL fragment, since these shouldn't be part of any profile URL
73 unset($parts['fragment']);
75 $URI = Network::unparseURL($parts);
81 * Rearrange the array so that it always has the same order
83 * @param array $data Unordered data
85 * @return array Ordered data
87 private static function rearrangeData($data)
89 $fields = ["name", "nick", "guid", "url", "addr", "alias", "photo", "account-type",
90 "community", "keywords", "location", "about", "hide",
91 "batch", "notify", "poll", "request", "confirm", "subscribe", "poco",
92 "following", "followers", "inbox", "outbox", "sharedinbox",
93 "priority", "network", "pubkey", "baseurl", "gsid"];
96 foreach ($fields as $field) {
97 if (isset($data[$field])) {
98 if (in_array($field, ["gsid", "hide", "account-type"])) {
99 $newdata[$field] = (int)$data[$field];
101 $newdata[$field] = $data[$field];
103 } elseif ($field != "gsid") {
104 $newdata[$field] = "";
106 $newdata[$field] = null;
110 // We don't use the "priority" field anymore and replace it with a dummy.
111 $newdata["priority"] = 0;
117 * Check if the hostname belongs to the own server
119 * @param string $host The hostname that is to be checked
121 * @return bool Does the testes hostname belongs to the own server?
123 private static function ownHost($host)
125 $own_host = DI::baseUrl()->getHostname();
127 $parts = parse_url($host);
129 if (!isset($parts['scheme'])) {
130 $parts = parse_url('http://'.$host);
133 if (!isset($parts['host'])) {
136 return $parts['host'] == $own_host;
140 * Probes for webfinger path via "host-meta"
142 * We have to check if the servers in the future still will offer this.
143 * It seems as if it was dropped from the standard.
145 * @param string $host The host part of an url
147 * @return array with template and type of the webfinger template for JSON or XML
148 * @throws HTTPException\InternalServerErrorException
150 private static function hostMeta($host)
152 // Reset the static variable
155 // Handles the case when the hostname contains the scheme
156 if (!parse_url($host, PHP_URL_SCHEME)) {
157 $ssl_url = "https://" . $host . "/.well-known/host-meta";
158 $url = "http://" . $host . "/.well-known/host-meta";
160 $ssl_url = $host . "/.well-known/host-meta";
164 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
166 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
169 $curlResult = DI::httpRequest()->get($ssl_url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
170 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
171 if ($curlResult->isSuccess()) {
172 $xml = $curlResult->getBody();
173 $xrd = XML::parseString($xml, true);
175 $host_url = 'https://' . $host;
179 } elseif ($curlResult->isTimeout()) {
180 Logger::info('Probing timeout', ['url' => $ssl_url]);
181 self::$istimeout = true;
185 if (!is_object($xrd) && !empty($url)) {
186 $curlResult = DI::httpRequest()->get($url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
187 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
188 if ($curlResult->isTimeout()) {
189 Logger::info('Probing timeout', ['url' => $url]);
190 self::$istimeout = true;
192 } elseif ($connection_error && $ssl_connection_error) {
193 self::$istimeout = true;
197 $xml = $curlResult->getBody();
198 $xrd = XML::parseString($xml, true);
199 $host_url = 'http://'.$host;
201 if (!is_object($xrd)) {
202 Logger::info('No xrd object found', ['host' => $host]);
206 $links = XML::elementToArray($xrd);
207 if (!isset($links["xrd"]["link"])) {
208 Logger::info('No xrd data found', ['host' => $host]);
214 foreach ($links["xrd"]["link"] as $value => $link) {
215 if (!empty($link["@attributes"])) {
216 $attributes = $link["@attributes"];
217 } elseif ($value == "@attributes") {
223 if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
224 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
226 $lrdd[$type] = $attributes["template"];
230 self::$baseurl = $host_url;
232 Logger::info('Probing successful', ['host' => $host]);
238 * Perform Webfinger lookup and return DFRN data
240 * Given an email style address, perform webfinger lookup and
241 * return the resulting DFRN profile URL, or if no DFRN profile URL
242 * is located, returns an OStatus subscription template (prefixed
243 * with the string 'stat:' to identify it as on OStatus template).
244 * If this isn't an email style address just return $webbie.
245 * Return an empty string if email-style addresses but webfinger fails,
246 * or if the resultant personal XRD doesn't contain a supported
247 * subscription/friend-request attribute.
249 * amended 7/9/2011 to return an hcard which could save potentially loading
250 * a lengthy content page to scrape dfrn attributes
252 * @param string $webbie Address that should be probed
253 * @param string $hcard_url Link to the hcard - is returned by reference
255 * @return string profile link
256 * @throws HTTPException\InternalServerErrorException
258 public static function webfingerDfrn($webbie, &$hcard_url)
262 $links = self::lrdd($webbie);
263 Logger::debug('Result', ['url' => $webbie, 'links' => $links]);
264 if (!empty($links) && is_array($links)) {
265 foreach ($links as $link) {
266 if ($link['@attributes']['rel'] === ActivityNamespace::DFRN) {
267 $profile_link = $link['@attributes']['href'];
269 if (($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) && ($profile_link == "")) {
270 $profile_link = 'stat:'.$link['@attributes']['template'];
272 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
273 $hcard_url = $link['@attributes']['href'];
277 return $profile_link;
281 * Check an URI for LRDD data
283 * @param string $uri Address that should be probed
285 * @return array uri data
286 * @throws HTTPException\InternalServerErrorException
288 public static function lrdd(string $uri)
290 $data = self::getWebfingerArray($uri);
294 $webfinger = $data['webfinger'];
296 if (empty($webfinger["links"])) {
297 Logger::info('No webfinger links found', ['uri' => $uri]);
303 foreach ($webfinger["links"] as $link) {
304 $data[] = ["@attributes" => $link];
307 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
308 foreach ($webfinger["aliases"] as $alias) {
309 $data[] = ["@attributes" =>
319 * Fetch information (protocol endpoints and user information) about a given uri
321 * @param string $uri Address that should be probed
322 * @param string $network Test for this specific network
323 * @param integer $uid User ID for the probe (only used for mails)
324 * @param boolean $cache Use cached values?
326 * @return array uri data
327 * @throws HTTPException\InternalServerErrorException
328 * @throws \ImagickException
330 public static function uri($uri, $network = '', $uid = -1)
332 // Local profiles aren't probed via network
333 if (empty($network) && strpos($uri, DI::baseUrl()->getHostname())) {
334 $data = self::localProbe($uri);
344 if (empty($network) || ($network == Protocol::ACTIVITYPUB)) {
345 $ap_profile = ActivityPub::probeProfile($uri);
350 self::$istimeout = false;
352 if ($network != Protocol::ACTIVITYPUB) {
353 $data = self::detect($uri, $network, $uid, $ap_profile);
354 if (!is_array($data)) {
357 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
359 } elseif (!empty($ap_profile)) {
360 $ap_profile['batch'] = '';
361 $data = array_merge($ap_profile, $data);
367 if (!isset($data['url'])) {
371 if (empty($data['photo'])) {
372 $data['photo'] = DI::baseUrl() . '/images/person-300.jpg';
375 if (empty($data['name'])) {
376 if (!empty($data['nick'])) {
377 $data['name'] = $data['nick'];
380 if (empty($data['name'])) {
381 $data['name'] = $data['url'];
385 if (empty($data['nick'])) {
386 $data['nick'] = strtolower($data['name']);
388 if (strpos($data['nick'], ' ')) {
389 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
393 if (!empty($data['baseurl']) && empty($data['gsid'])) {
394 $data['gsid'] = GServer::getID($data['baseurl']);
397 if (empty($data['network'])) {
398 $data['network'] = Protocol::PHANTOM;
401 // Ensure that local connections always are DFRN
402 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
403 $data['network'] = Protocol::DFRN;
406 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
407 $data['hide'] = self::getHideStatus($data['url']);
410 return self::rearrangeData($data);
415 * Fetches the "hide" status from the profile
417 * @param string $url URL of the profile
419 * @return boolean "hide" status
421 private static function getHideStatus($url)
423 $curlResult = DI::httpRequest()->get($url);
424 if (!$curlResult->isSuccess()) {
428 // If the file is too large then exit
429 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
433 // If it isn't a HTML file then exit
434 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
438 $body = $curlResult->getBody();
440 $doc = new DOMDocument();
441 @$doc->loadHTML($body);
443 $xpath = new DOMXPath($doc);
445 $list = $xpath->query('//meta[@name]');
446 foreach ($list as $node) {
448 if ($node->attributes->length) {
449 foreach ($node->attributes as $attribute) {
450 $meta_tag[$attribute->name] = $attribute->value;
454 if (empty($meta_tag['content'])) {
458 $content = strtolower(trim($meta_tag['content']));
460 switch (strtolower(trim($meta_tag['name']))) {
461 case 'dfrn-global-visibility':
462 if ($content == 'false') {
467 if (strpos($content, 'noindex') !== false) {
478 * Fetch the "subscribe" and add it to the result
480 * @param array $result
481 * @param array $webfinger
482 * @return array result
484 private static function getSubscribeLink(array $result, array $webfinger)
486 if (empty($webfinger['links'])) {
490 foreach ($webfinger['links'] as $link) {
491 if (!empty($link['template']) && ($link['rel'] === ActivityNamespace::OSTATUSSUB)) {
492 $result['subscribe'] = $link['template'];
500 * Get webfinger data from a given URI
503 * @return array Webfinger array
505 private static function getWebfingerArray(string $uri)
507 $parts = parse_url($uri);
509 if (!empty($parts['scheme']) && !empty($parts['host'])) {
510 $host = $parts['host'];
511 if (!empty($parts['port'])) {
512 $host .= ':'.$parts['port'];
515 $baseurl = $parts['scheme'] . '://' . $host;
520 $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
521 if (!empty($path_parts)) {
522 $nick = ltrim(end($path_parts), '@');
523 // When the last part of the URI is numeric then it is most likely an ID and not a nick name
524 if (!is_numeric($nick)) {
525 $addr = $nick."@".$host;
531 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
532 if (empty($webfinger)) {
533 $lrdd = self::hostMeta($host);
536 if (empty($webfinger) && empty($lrdd)) {
537 while (empty($lrdd) && empty($webfinger) && (sizeof($path_parts) > 1)) {
538 $host .= "/".array_shift($path_parts);
539 $baseurl = $parts['scheme'] . '://' . $host;
542 $addr = $nick."@".$host;
545 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
546 if (empty($webfinger)) {
547 $lrdd = self::hostMeta($host);
551 if (empty($lrdd) && empty($webfinger)) {
555 } elseif (strstr($uri, '@')) {
556 // Remove "acct:" from the URI
557 $uri = str_replace('acct:', '', $uri);
559 $host = substr($uri, strpos($uri, '@') + 1);
560 $nick = substr($uri, 0, strpos($uri, '@'));
563 $webfinger = self::getWebfinger('https://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
564 if (self::$istimeout) {
568 if (empty($webfinger)) {
569 $webfinger = self::getWebfinger('http://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
570 if (self::$istimeout) {
574 $baseurl = 'https://' . $host;
577 if (empty($webfinger)) {
578 $lrdd = self::hostMeta($host);
579 if (self::$istimeout) {
582 $baseurl = self::$baseurl;
584 $baseurl = 'http://' . $host;
587 Logger::info('URI was not detectable', ['uri' => $uri]);
591 if (empty($webfinger)) {
592 foreach ($lrdd as $type => $template) {
597 $webfinger = self::getWebfinger($template, $type, $uri, $addr);
601 if (empty($webfinger)) {
605 if ($webfinger['detected'] == $addr) {
606 $webfinger['nick'] = $nick;
607 $webfinger['addr'] = $addr;
610 $webfinger['baseurl'] = $baseurl;
616 * Perform network request for webfinger data
618 * @param string $template
619 * @param string $type
621 * @param string $addr
622 * @return array webfinger results
624 private static function getWebfinger(string $template, string $type, string $uri, string $addr)
626 // First try the address because this is the primary purpose of webfinger
629 $path = str_replace('{uri}', urlencode("acct:" . $addr), $template);
630 $webfinger = self::webfinger($path, $type);
631 if (self::$istimeout) {
637 if (empty($webfinger) && $uri != $addr) {
639 $path = str_replace('{uri}', urlencode($uri), $template);
640 $webfinger = self::webfinger($path, $type);
641 if (self::$istimeout) {
646 if (empty($webfinger)) {
650 return ['webfinger' => $webfinger, 'detected' => $detected];
654 * Fetch information (protocol endpoints and user information) about a given uri
656 * This function is only called by the "uri" function that adds caching and rearranging of data.
658 * @param string $uri Address that should be probed
659 * @param string $network Test for this specific network
660 * @param integer $uid User ID for the probe (only used for mails)
661 * @param array $ap_profile Previously probed AP profile
663 * @return array uri data
664 * @throws HTTPException\InternalServerErrorException
666 private static function detect(string $uri, string $network, int $uid, array $ap_profile)
670 'network' => $network,
675 Hook::callAll('probe_detect', $hookData);
677 if ($hookData['result']) {
678 if (!is_array($hookData['result'])) {
681 return $hookData['result'];
685 $parts = parse_url($uri);
687 if (!empty($parts['scheme']) && !empty($parts['host'])) {
688 if (in_array($parts['host'], ['twitter.com', 'mobile.twitter.com'])) {
689 return self::twitter($uri);
691 } elseif (strstr($uri, '@')) {
692 // If the URI starts with "mailto:" then jump directly to the mail detection
693 if (strpos($uri, 'mailto:') !== false) {
694 $uri = str_replace('mailto:', '', $uri);
695 return self::mail($uri, $uid);
698 if ($network == Protocol::MAIL) {
699 return self::mail($uri, $uid);
702 if (Strings::endsWith($uri, '@twitter.com')
703 || Strings::endsWith($uri, '@mobile.twitter.com')
705 return self::twitter($uri);
708 Logger::info('URI was not detectable', ['uri' => $uri]);
712 Logger::info('Probing start', ['uri' => $uri]);
714 $data = self::getWebfingerArray($uri);
716 if (!empty($parts['scheme'])) {
717 return self::feed($uri);
718 } elseif (!empty($uid)) {
719 return self::mail($uri, $uid);
725 $webfinger = $data['webfinger'];
726 $nick = $data['nick'] ?? '';
727 $addr = $data['addr'] ?? '';
728 $baseurl = $data['baseurl'] ?? '';
732 if (in_array($network, ["", Protocol::DFRN])) {
733 $result = self::dfrn($webfinger);
735 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
736 $result = self::diaspora($webfinger);
738 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
739 $result = self::ostatus($webfinger);
741 if (in_array($network, ['', Protocol::ZOT])) {
742 $result = self::zot($webfinger, $result, $baseurl);
744 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
745 $result = self::pumpio($webfinger, $addr);
747 if (empty($result['network']) && empty($ap_profile['network']) || ($network == Protocol::FEED)) {
748 $result = self::feed($uri);
750 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
751 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
752 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
753 $result["nick"] = $nick;
756 if (empty($result["addr"]) && ($addr != "")) {
757 $result["addr"] = $addr;
761 $result = self::getSubscribeLink($result, $webfinger);
763 if (empty($result["network"])) {
764 $result["network"] = Protocol::PHANTOM;
767 if (empty($result['baseurl']) && !empty($baseurl)) {
768 $result['baseurl'] = $baseurl;
771 if (empty($result["url"])) {
772 $result["url"] = $uri;
775 Logger::info('Probing done', ['uri' => $uri, 'network' => $result["network"]]);
781 * Check for Zot contact
783 * @param array $webfinger Webfinger data
784 * @param array $data previously probed data
786 * @return array Zot data
787 * @throws HTTPException\InternalServerErrorException
789 private static function zot($webfinger, $data, $baseurl)
791 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
792 foreach ($webfinger["aliases"] as $alias) {
793 if (substr($alias, 0, 5) == 'acct:') {
794 $data["addr"] = substr($alias, 5);
799 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
800 $data["addr"] = substr($webfinger["subject"], 5);
804 foreach ($webfinger['links'] as $link) {
805 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
806 $zot_url = $link['href'];
810 if (empty($zot_url) && !empty($data['addr']) && !empty($baseurl)) {
811 $condition = ['nurl' => Strings::normaliseLink($baseurl), 'platform' => ['hubzilla']];
812 if (!DBA::exists('gserver', $condition)) {
815 $zot_url = $baseurl . '/.well-known/zot-info?address=' . $data['addr'];
818 if (empty($zot_url)) {
822 $data = self::pollZot($zot_url, $data);
824 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
825 foreach ($webfinger['aliases'] as $alias) {
826 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
827 $data['alias'] = $alias;
835 public static function pollZot($url, $data)
837 $curlResult = DI::httpRequest()->get($url);
838 if ($curlResult->isTimeout()) {
841 $content = $curlResult->getBody();
846 $json = json_decode($content, true);
847 if (!is_array($json)) {
851 if (empty($data['network'])) {
852 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
853 $data['network'] = Protocol::ZOT;
854 } elseif (!isset($json['protocols'])) {
855 $data['network'] = Protocol::ZOT;
859 if (!empty($json['guid']) && empty($data['guid'])) {
860 $data['guid'] = $json['guid'];
862 if (!empty($json['key']) && empty($data['pubkey'])) {
863 $data['pubkey'] = $json['key'];
865 if (!empty($json['name'])) {
866 $data['name'] = $json['name'];
868 if (!empty($json['photo'])) {
869 $data['photo'] = $json['photo'];
870 if (!empty($json['photo_updated'])) {
871 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
874 if (!empty($json['address'])) {
875 $data['addr'] = $json['address'];
877 if (!empty($json['url'])) {
878 $data['url'] = $json['url'];
880 if (!empty($json['connections_url'])) {
881 $data['poco'] = $json['connections_url'];
883 if (isset($json['searchable'])) {
884 $data['hide'] = !$json['searchable'];
886 if (!empty($json['public_forum'])) {
887 $data['community'] = $json['public_forum'];
888 $data['account-type'] = User::PAGE_FLAGS_COMMUNITY;
891 if (!empty($json['profile'])) {
892 $profile = $json['profile'];
893 if (!empty($profile['description'])) {
894 $data['about'] = $profile['description'];
896 if (!empty($profile['keywords'])) {
897 $keywords = implode(', ', $profile['keywords']);
898 if (!empty($keywords)) {
899 $data['keywords'] = $keywords;
904 if (!empty($profile['region'])) {
905 $loc['region'] = $profile['region'];
907 if (!empty($profile['country'])) {
908 $loc['country-name'] = $profile['country'];
910 $location = Profile::formatLocation($loc);
911 if (!empty($location)) {
912 $data['location'] = $location;
920 * Perform a webfinger request.
922 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
924 * @param string $url Address that should be probed
925 * @param string $type type
927 * @return array webfinger data
928 * @throws HTTPException\InternalServerErrorException
930 public static function webfinger($url, $type)
932 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
934 $curlResult = DI::httpRequest()->get($url, false, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
935 if ($curlResult->isTimeout()) {
936 self::$istimeout = true;
939 $data = $curlResult->getBody();
941 $webfinger = json_decode($data, true);
942 if (!empty($webfinger)) {
943 if (!isset($webfinger["links"])) {
944 Logger::info('No json webfinger links', ['url' => $url]);
950 // If it is not JSON, maybe it is XML
951 $xrd = XML::parseString($data, true);
952 if (!is_object($xrd)) {
953 Logger::info('No webfinger data retrievable', ['url' => $url]);
957 $xrd_arr = XML::elementToArray($xrd);
958 if (!isset($xrd_arr["xrd"]["link"])) {
959 Logger::info('No XML webfinger links', ['url' => $url]);
965 if (!empty($xrd_arr["xrd"]["subject"])) {
966 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
969 if (!empty($xrd_arr["xrd"]["alias"])) {
970 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
973 $webfinger["links"] = [];
975 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
976 if (!empty($data["@attributes"])) {
977 $attributes = $data["@attributes"];
978 } elseif ($value == "@attributes") {
984 $webfinger["links"][] = $attributes;
990 * Poll the Friendica specific noscrape page.
992 * "noscrape" is a faster alternative to fetch the data from the hcard.
993 * This functionality was originally created for the directory.
995 * @param string $noscrape_url Link to the noscrape page
996 * @param array $data The already fetched data
998 * @return array noscrape data
999 * @throws HTTPException\InternalServerErrorException
1001 private static function pollNoscrape($noscrape_url, $data)
1003 $curlResult = DI::httpRequest()->get($noscrape_url);
1004 if ($curlResult->isTimeout()) {
1005 self::$istimeout = true;
1008 $content = $curlResult->getBody();
1010 Logger::info('Empty body', ['url' => $noscrape_url]);
1014 $json = json_decode($content, true);
1015 if (!is_array($json)) {
1016 Logger::info('No json data', ['url' => $noscrape_url]);
1020 if (!empty($json["fn"])) {
1021 $data["name"] = $json["fn"];
1024 if (!empty($json["addr"])) {
1025 $data["addr"] = $json["addr"];
1028 if (!empty($json["nick"])) {
1029 $data["nick"] = $json["nick"];
1032 if (!empty($json["guid"])) {
1033 $data["guid"] = $json["guid"];
1036 if (!empty($json["comm"])) {
1037 $data["community"] = $json["comm"];
1040 if (!empty($json["tags"])) {
1041 $keywords = implode(", ", $json["tags"]);
1042 if ($keywords != "") {
1043 $data["keywords"] = $keywords;
1047 $location = Profile::formatLocation($json);
1049 $data["location"] = $location;
1052 if (!empty($json["about"])) {
1053 $data["about"] = $json["about"];
1056 if (!empty($json["key"])) {
1057 $data["pubkey"] = $json["key"];
1060 if (!empty($json["photo"])) {
1061 $data["photo"] = $json["photo"];
1064 if (!empty($json["dfrn-request"])) {
1065 $data["request"] = $json["dfrn-request"];
1068 if (!empty($json["dfrn-confirm"])) {
1069 $data["confirm"] = $json["dfrn-confirm"];
1072 if (!empty($json["dfrn-notify"])) {
1073 $data["notify"] = $json["dfrn-notify"];
1076 if (!empty($json["dfrn-poll"])) {
1077 $data["poll"] = $json["dfrn-poll"];
1080 if (isset($json["hide"])) {
1081 $data["hide"] = (bool)$json["hide"];
1083 $data["hide"] = false;
1090 * Check for valid DFRN data
1092 * @param array $data DFRN data
1094 * @return int Number of errors
1096 public static function validDfrn($data)
1099 if (!isset($data['key'])) {
1102 if (!isset($data['dfrn-request'])) {
1105 if (!isset($data['dfrn-confirm'])) {
1108 if (!isset($data['dfrn-notify'])) {
1111 if (!isset($data['dfrn-poll'])) {
1118 * Fetch data from a DFRN profile page and via "noscrape"
1120 * @param string $profile_link Link to the profile page
1122 * @return array profile data
1123 * @throws HTTPException\InternalServerErrorException
1124 * @throws \ImagickException
1126 public static function profile($profile_link)
1130 Logger::info('Check profile', ['link' => $profile_link]);
1132 // Fetch data via noscrape - this is faster
1133 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1134 $data = self::pollNoscrape($noscrape_url, $data);
1136 if (!isset($data["notify"])
1137 || !isset($data["confirm"])
1138 || !isset($data["request"])
1139 || !isset($data["poll"])
1140 || !isset($data["name"])
1141 || !isset($data["photo"])
1143 $data = self::pollHcard($profile_link, $data, true);
1148 if (empty($data["addr"]) || empty($data["nick"])) {
1149 $probe_data = self::uri($profile_link);
1150 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1151 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1154 $prof_data["addr"] = $data["addr"];
1155 $prof_data["nick"] = $data["nick"];
1156 $prof_data["dfrn-request"] = $data['request'] ?? null;
1157 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1158 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1159 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1160 $prof_data["photo"] = $data['photo'] ?? null;
1161 $prof_data["fn"] = $data['name'] ?? null;
1162 $prof_data["key"] = $data['pubkey'] ?? null;
1164 Logger::debug('Result', ['link' => $profile_link, 'data' => $prof_data]);
1170 * Check for DFRN contact
1172 * @param array $webfinger Webfinger data
1174 * @return array DFRN data
1175 * @throws HTTPException\InternalServerErrorException
1177 private static function dfrn($webfinger)
1181 // The array is reversed to take into account the order of preference for same-rel links
1182 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1183 foreach (array_reverse($webfinger["links"]) as $link) {
1184 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1185 $data["network"] = Protocol::DFRN;
1186 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1187 $data["poll"] = $link["href"];
1188 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1189 $data["url"] = $link["href"];
1190 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1191 $hcard_url = $link["href"];
1192 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1193 $data["poco"] = $link["href"];
1194 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1195 $data["photo"] = $link["href"];
1196 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1197 $data["baseurl"] = trim($link["href"], '/');
1198 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1199 $data["guid"] = $link["href"];
1200 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1201 $data["pubkey"] = base64_decode($link["href"]);
1203 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1204 if (strstr($data["pubkey"], 'RSA ')) {
1205 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1210 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1211 foreach ($webfinger["aliases"] as $alias) {
1212 if (empty($data["url"]) && !strstr($alias, "@")) {
1213 $data["url"] = $alias;
1214 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1215 $data["alias"] = $alias;
1216 } elseif (substr($alias, 0, 5) == 'acct:') {
1217 $data["addr"] = substr($alias, 5);
1222 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1223 $data["addr"] = substr($webfinger["subject"], 5);
1226 if (!isset($data["network"]) || ($hcard_url == "")) {
1230 // Fetch data via noscrape - this is faster
1231 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1232 $data = self::pollNoscrape($noscrape_url, $data);
1234 if (isset($data["notify"])
1235 && isset($data["confirm"])
1236 && isset($data["request"])
1237 && isset($data["poll"])
1238 && isset($data["name"])
1239 && isset($data["photo"])
1244 $data = self::pollHcard($hcard_url, $data, true);
1250 * Poll the hcard page (Diaspora and Friendica specific)
1252 * @param string $hcard_url Link to the hcard page
1253 * @param array $data The already fetched data
1254 * @param boolean $dfrn Poll DFRN specific data
1256 * @return array hcard data
1257 * @throws HTTPException\InternalServerErrorException
1259 private static function pollHcard($hcard_url, $data, $dfrn = false)
1261 $curlResult = DI::httpRequest()->get($hcard_url);
1262 if ($curlResult->isTimeout()) {
1263 self::$istimeout = true;
1266 $content = $curlResult->getBody();
1271 $doc = new DOMDocument();
1272 if (!@$doc->loadHTML($content)) {
1276 $xpath = new DomXPath($doc);
1278 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1279 if (!is_object($vcards)) {
1283 if (!isset($data["baseurl"])) {
1284 $data["baseurl"] = "";
1287 if ($vcards->length > 0) {
1288 $vcard = $vcards->item(0);
1290 // We have to discard the guid from the hcard in favour of the guid from lrdd
1291 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1292 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1293 if (($search->length > 0) && empty($data["guid"])) {
1294 $data["guid"] = $search->item(0)->nodeValue;
1297 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1298 if ($search->length > 0) {
1299 $data["nick"] = $search->item(0)->nodeValue;
1302 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1303 if ($search->length > 0) {
1304 $data["name"] = $search->item(0)->nodeValue;
1307 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1308 if ($search->length > 0) {
1309 $data["searchable"] = $search->item(0)->nodeValue;
1312 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1313 if ($search->length > 0) {
1314 $data["pubkey"] = $search->item(0)->nodeValue;
1315 if (strstr($data["pubkey"], 'RSA ')) {
1316 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1320 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1321 if ($search->length > 0) {
1322 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1327 if (!empty($vcard)) {
1328 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1329 foreach ($photos as $photo) {
1331 foreach ($photo->attributes as $attribute) {
1332 $attr[$attribute->name] = trim($attribute->value);
1335 if (isset($attr["src"]) && isset($attr["width"])) {
1336 $avatar[$attr["width"]] = $attr["src"];
1339 // We don't have a width. So we just take everything that we got.
1340 // This is a Hubzilla workaround which doesn't send a width.
1341 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1342 $avatar[] = $attr["src"];
1347 if (sizeof($avatar)) {
1349 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1353 // Poll DFRN specific data
1354 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1355 if ($search->length > 0) {
1356 foreach ($search as $link) {
1357 //$data["request"] = $search->item(0)->nodeValue;
1359 foreach ($link->attributes as $attribute) {
1360 $attr[$attribute->name] = trim($attribute->value);
1363 $data[substr($attr["rel"], 5)] = $attr["href"];
1367 // Older Friendica versions had used the "uid" field differently than newer versions
1368 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1369 unset($data["guid"]);
1378 * Check for Diaspora contact
1380 * @param array $webfinger Webfinger data
1382 * @return array Diaspora data
1383 * @throws HTTPException\InternalServerErrorException
1385 private static function diaspora($webfinger)
1390 // The array is reversed to take into account the order of preference for same-rel links
1391 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1392 foreach (array_reverse($webfinger["links"]) as $link) {
1393 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1394 $hcard_url = $link["href"];
1395 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1396 $data["baseurl"] = trim($link["href"], '/');
1397 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1398 $data["guid"] = $link["href"];
1399 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1400 $data["url"] = $link["href"];
1401 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1402 $data["poll"] = $link["href"];
1403 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1404 $data["poco"] = $link["href"];
1405 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1406 $data["notify"] = $link["href"];
1407 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1408 $data["pubkey"] = base64_decode($link["href"]);
1410 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1411 if (strstr($data["pubkey"], 'RSA ')) {
1412 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1417 if (empty($data["url"]) || empty($hcard_url)) {
1421 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1422 foreach ($webfinger["aliases"] as $alias) {
1423 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1424 $data["alias"] = $alias;
1425 } elseif (substr($alias, 0, 5) == 'acct:') {
1426 $data["addr"] = substr($alias, 5);
1431 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1432 $data["addr"] = substr($webfinger["subject"], 5);
1435 // Fetch further information from the hcard
1436 $data = self::pollHcard($hcard_url, $data);
1442 if (!empty($data["url"])
1443 && !empty($data["guid"])
1444 && !empty($data["baseurl"])
1445 && !empty($data["pubkey"])
1446 && !empty($hcard_url)
1448 $data["network"] = Protocol::DIASPORA;
1450 // The Diaspora handle must always be lowercase
1451 if (!empty($data["addr"])) {
1452 $data["addr"] = strtolower($data["addr"]);
1455 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1456 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1457 $data["batch"] = $data["baseurl"] . "/receive/public";
1466 * Check for OStatus contact
1468 * @param array $webfinger Webfinger data
1469 * @param bool $short Short detection mode
1471 * @return array|bool OStatus data or "false" on error or "true" on short mode
1472 * @throws HTTPException\InternalServerErrorException
1474 private static function ostatus($webfinger, $short = false)
1478 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1479 foreach ($webfinger["aliases"] as $alias) {
1480 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1481 $data["addr"] = str_replace('acct:', '', $alias);
1486 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1487 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1489 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1492 if (!empty($webfinger["links"])) {
1493 // The array is reversed to take into account the order of preference for same-rel links
1494 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1495 foreach (array_reverse($webfinger["links"]) as $link) {
1496 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1497 && (($link["type"] ?? "") == "text/html")
1498 && ($link["href"] != "")
1500 $data["url"] = $data["alias"] = $link["href"];
1501 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1502 $data["notify"] = $link["href"];
1503 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1504 $data["poll"] = $link["href"];
1505 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1506 $pubkey = $link["href"];
1508 if (substr($pubkey, 0, 5) === 'data:') {
1509 if (strstr($pubkey, ',')) {
1510 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1512 $pubkey = substr($pubkey, 5);
1514 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1515 $curlResult = DI::httpRequest()->get($pubkey);
1516 if ($curlResult->isTimeout()) {
1517 self::$istimeout = true;
1518 return $short ? false : [];
1520 $pubkey = $curlResult->getBody();
1523 $key = explode(".", $pubkey);
1525 if (sizeof($key) >= 3) {
1526 $m = Strings::base64UrlDecode($key[1]);
1527 $e = Strings::base64UrlDecode($key[2]);
1528 $data["pubkey"] = Crypto::meToPem($m, $e);
1534 if (isset($data["notify"]) && isset($data["pubkey"])
1535 && isset($data["poll"])
1536 && isset($data["url"])
1538 $data["network"] = Protocol::OSTATUS;
1540 return $short ? false : [];
1547 // Fetch all additional data from the feed
1548 $curlResult = DI::httpRequest()->get($data["poll"]);
1549 if ($curlResult->isTimeout()) {
1550 self::$istimeout = true;
1553 $feed = $curlResult->getBody();
1554 $feed_data = Feed::import($feed);
1559 if (!empty($feed_data["header"]["author-name"])) {
1560 $data["name"] = $feed_data["header"]["author-name"];
1562 if (!empty($feed_data["header"]["author-nick"])) {
1563 $data["nick"] = $feed_data["header"]["author-nick"];
1565 if (!empty($feed_data["header"]["author-avatar"])) {
1566 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1568 if (!empty($feed_data["header"]["author-id"])) {
1569 $data["alias"] = $feed_data["header"]["author-id"];
1571 if (!empty($feed_data["header"]["author-location"])) {
1572 $data["location"] = $feed_data["header"]["author-location"];
1574 if (!empty($feed_data["header"]["author-about"])) {
1575 $data["about"] = $feed_data["header"]["author-about"];
1577 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1578 // So we take the value that we just fetched, although the other one worked as well
1579 if (!empty($feed_data["header"]["author-link"])) {
1580 $data["url"] = $feed_data["header"]["author-link"];
1583 if ($data["url"] == $data["alias"]) {
1584 $data["alias"] = '';
1587 /// @todo Fetch location and "about" from the feed as well
1592 * Fetch data from a pump.io profile page
1594 * @param string $profile_link Link to the profile page
1596 * @return array profile data
1598 private static function pumpioProfileData($profile_link)
1600 $curlResult = DI::httpRequest()->get($profile_link);
1601 if (!$curlResult->isSuccess()) {
1605 $doc = new DOMDocument();
1606 if (!@$doc->loadHTML($curlResult->getBody())) {
1610 $xpath = new DomXPath($doc);
1614 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1616 if ($data["name"] == '') {
1617 // This is ugly - but pump.io doesn't seem to know a better way for it
1618 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1619 $pos = strpos($data["name"], chr(10));
1621 $data["name"] = trim(substr($data["name"], 0, $pos));
1625 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1627 if ($data["location"] == '') {
1628 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1631 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1633 if ($data["about"] == '') {
1634 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1637 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1639 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1642 foreach ($avatar->attributes as $attribute) {
1643 if ($attribute->name == "src") {
1644 $data["photo"] = trim($attribute->value);
1653 * Check for pump.io contact
1655 * @param array $webfinger Webfinger data
1656 * @param string $addr
1657 * @return array pump.io data
1659 private static function pumpio($webfinger, $addr)
1662 // The array is reversed to take into account the order of preference for same-rel links
1663 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1664 foreach (array_reverse($webfinger["links"]) as $link) {
1665 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1666 && (($link["type"] ?? "") == "text/html")
1667 && ($link["href"] != "")
1669 $data["url"] = $link["href"];
1670 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1671 $data["notify"] = $link["href"];
1672 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1673 $data["poll"] = $link["href"];
1674 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1675 $data["dialback"] = $link["href"];
1678 if (isset($data["poll"]) && isset($data["notify"])
1679 && isset($data["dialback"])
1680 && isset($data["url"])
1682 // by now we use these fields only for the network type detection
1683 // So we unset all data that isn't used at the moment
1684 unset($data["dialback"]);
1686 $data["network"] = Protocol::PUMPIO;
1691 $profile_data = self::pumpioProfileData($data["url"]);
1693 if (!$profile_data) {
1697 $data = array_merge($data, $profile_data);
1699 if (($addr != '') && ($data['name'] != '')) {
1700 $name = trim(str_replace($addr, '', $data['name']));
1702 $data['name'] = $name;
1710 * Check for twitter contact
1712 * @param string $uri
1714 * @return array twitter data
1716 private static function twitter($uri)
1718 if (preg_match('=([^@]+)@(?:mobile\.)?twitter\.com$=i', $uri, $matches)) {
1719 $nick = $matches[1];
1720 } elseif (preg_match('=^https?://(?:mobile\.)?twitter\.com/(.+)=i', $uri, $matches)) {
1721 $nick = $matches[1];
1727 $data['url'] = 'https://twitter.com/' . $nick;
1728 $data['addr'] = $nick . '@twitter.com';
1729 $data['nick'] = $data['name'] = $nick;
1730 $data['network'] = Protocol::TWITTER;
1731 $data['baseurl'] = 'https://twitter.com';
1737 * Checks HTML page for RSS feed link
1739 * @param string $url Page link
1740 * @param string $body Page body string
1741 * @return string|false Feed link or false if body was invalid HTML document
1743 public static function getFeedLink(string $url, string $body)
1745 $doc = new DOMDocument();
1746 if (!@$doc->loadHTML($body)) {
1750 $xpath = new DOMXPath($doc);
1752 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1754 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1760 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1762 * Loosely based on RFC 1808
1764 * @see https://tools.ietf.org/html/rfc1808
1766 * @param string $href The potential relative href found in the HTML document
1767 * @param string $base The HTML document URL
1768 * @param DOMXPath $xpath The HTML document XPath
1771 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath)
1773 if (filter_var($href, FILTER_VALIDATE_URL)) {
1777 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1779 $baseParts = parse_url($base);
1780 if (empty($baseParts['host'])) {
1784 // Naked domain case (scheme://basehost)
1785 $path = $baseParts['path'] ?? '/';
1787 // Remove the filename part of the path if it exists (/base/path/file)
1788 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1790 $hrefParts = parse_url($href);
1792 // Root path case (/path) including relative scheme case (//host/path)
1793 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1794 $path = $hrefParts['path'];
1796 $path = $path . '/' . $hrefParts['path'];
1798 // Resolve arbitrary relative path
1799 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1800 $parts = array_filter(explode('/', $path), 'strlen');
1801 $absolutes = array();
1802 foreach ($parts as $part) {
1803 if ('.' == $part) continue;
1804 if ('..' == $part) {
1805 array_pop($absolutes);
1807 $absolutes[] = $part;
1811 $path = '/' . implode('/', $absolutes);
1814 // Relative scheme case (//host/path)
1815 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1816 $baseParts['path'] = $path;
1817 unset($baseParts['query']);
1818 unset($baseParts['fragment']);
1820 return Network::unparseURL($baseParts);
1824 * Check for feed contact
1826 * @param string $url Profile link
1827 * @param boolean $probe Do a probe if the page contains a feed link
1829 * @return array feed data
1830 * @throws HTTPException\InternalServerErrorException
1832 private static function feed($url, $probe = true)
1834 $curlResult = DI::httpRequest()->get($url);
1835 if ($curlResult->isTimeout()) {
1836 self::$istimeout = true;
1839 $feed = $curlResult->getBody();
1840 $feed_data = Feed::import($feed);
1847 $feed_url = self::getFeedLink($url, $feed);
1853 return self::feed($feed_url, false);
1856 if (!empty($feed_data["header"]["author-name"])) {
1857 $data["name"] = $feed_data["header"]["author-name"];
1860 if (!empty($feed_data["header"]["author-nick"])) {
1861 $data["nick"] = $feed_data["header"]["author-nick"];
1864 if (!empty($feed_data["header"]["author-avatar"])) {
1865 $data["photo"] = $feed_data["header"]["author-avatar"];
1868 if (!empty($feed_data["header"]["author-id"])) {
1869 $data["alias"] = $feed_data["header"]["author-id"];
1872 $data["url"] = $url;
1873 $data["poll"] = $url;
1875 $data["network"] = Protocol::FEED;
1881 * Check for mail contact
1883 * @param string $uri Profile link
1884 * @param integer $uid User ID
1886 * @return array mail data
1887 * @throws \Exception
1889 private static function mail($uri, $uid)
1891 if (!Network::isEmailDomainValid($uri)) {
1899 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1901 $condition = ["`uid` = ? AND `server` != ''", $uid];
1902 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1903 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1905 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1909 $mailbox = Email::constructMailboxName($mailacct);
1911 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1912 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1917 $msgs = Email::poll($mbox, $uri);
1918 Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
1920 if (!count($msgs)) {
1924 $phost = substr($uri, strpos($uri, '@') + 1);
1927 $data["addr"] = $uri;
1928 $data["network"] = Protocol::MAIL;
1929 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1930 $data["nick"] = $data["name"];
1931 $data["photo"] = Network::lookupAvatarByEmail($uri);
1932 $data["url"] = 'mailto:'.$uri;
1933 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1934 $data["poll"] = 'email ' . Strings::getRandomHex();
1936 $x = Email::messageMeta($mbox, $msgs[0]);
1937 if (stristr($x[0]->from, $uri)) {
1938 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1939 } elseif (stristr($x[0]->to, $uri)) {
1940 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1943 foreach ($adr as $feadr) {
1944 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1945 &&(strcasecmp($feadr->host, $phost) == 0)
1946 && (strlen($feadr->personal))
1948 $personal = imap_mime_header_decode($feadr->personal);
1950 foreach ($personal as $perspart) {
1951 if ($perspart->charset != "default") {
1952 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1954 $data["name"] .= $perspart->text;
1958 $data["name"] = Strings::escapeTags($data["name"]);
1962 if (!empty($mbox)) {
1969 * Mix two paths together to possibly fix missing parts
1971 * @param string $avatar Path to the avatar
1972 * @param string $base Another path that is hopefully complete
1974 * @return string fixed avatar path
1975 * @throws \Exception
1977 public static function fixAvatar($avatar, $base)
1979 $base_parts = parse_url($base);
1981 // Remove all parts that could create a problem
1982 unset($base_parts['path']);
1983 unset($base_parts['query']);
1984 unset($base_parts['fragment']);
1986 $avatar_parts = parse_url($avatar);
1989 $parts = array_merge($base_parts, $avatar_parts);
1991 // And put them together again
1992 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1993 $host = isset($parts['host']) ? $parts['host'] : '';
1994 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1995 $path = isset($parts['path']) ? $parts['path'] : '';
1996 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1997 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1999 $fixed = $scheme.$host.$port.$path.$query.$fragment;
2001 Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
2007 * Fetch the last date that the contact had posted something (publically)
2009 * @param string $data probing result
2010 * @return string last activity
2012 public static function getLastUpdate(array $data)
2014 if ($lastUpdate = self::updateFromNoScrape($data)) {
2018 if (!empty($data['outbox'])) {
2019 return self::updateFromOutbox($data['outbox'], $data);
2020 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
2021 return self::updateFromOutbox($data['poll'], $data);
2022 } elseif (!empty($data['poll'])) {
2023 return self::updateFromFeed($data);
2030 * Fetch the last activity date from the "noscrape" endpoint
2032 * @param array $data Probing result
2033 * @return string last activity
2035 * @return bool 'true' if update was successful or the server was unreachable
2037 private static function updateFromNoScrape(array $data)
2039 if (empty($data['baseurl'])) {
2043 // Check the 'noscrape' endpoint when it is a Friendica server
2044 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
2045 Strings::normaliseLink($data['baseurl'])]);
2046 if (!DBA::isResult($gserver)) {
2050 $curlResult = DI::httpRequest()->get($gserver['noscrape'] . '/' . $data['nick']);
2052 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
2053 $noscrape = json_decode($curlResult->getBody(), true);
2054 if (!empty($noscrape) && !empty($noscrape['updated'])) {
2055 return DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2063 * Fetch the last activity date from an ActivityPub Outbox
2065 * @param string $feed
2066 * @param array $data Probing result
2067 * @return string last activity
2068 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2070 private static function updateFromOutbox(string $feed, array $data)
2072 $outbox = ActivityPub::fetchContent($feed);
2073 if (empty($outbox)) {
2077 if (!empty($outbox['orderedItems'])) {
2078 $items = $outbox['orderedItems'];
2079 } elseif (!empty($outbox['first']['orderedItems'])) {
2080 $items = $outbox['first']['orderedItems'];
2081 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2082 return self::updateFromOutbox($outbox['first']['href'], $data);
2083 } elseif (!empty($outbox['first'])) {
2084 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2085 return self::updateFromOutbox($outbox['first'], $data);
2087 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2095 foreach ($items as $activity) {
2096 if (!empty($activity['published'])) {
2097 $published = DateTimeFormat::utc($activity['published']);
2098 } elseif (!empty($activity['object']['published'])) {
2099 $published = DateTimeFormat::utc($activity['object']['published']);
2104 if ($last_updated < $published) {
2105 $last_updated = $published;
2109 if (!empty($last_updated)) {
2110 return $last_updated;
2117 * Fetch the last activity date from an XML feed
2119 * @param array $data Probing result
2120 * @return string last activity
2122 private static function updateFromFeed(array $data)
2124 // Search for the newest entry in the feed
2125 $curlResult = DI::httpRequest()->get($data['poll']);
2126 if (!$curlResult->isSuccess()) {
2130 $doc = new DOMDocument();
2131 @$doc->loadXML($curlResult->getBody());
2133 $xpath = new DOMXPath($doc);
2134 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2136 $entries = $xpath->query('/atom:feed/atom:entry');
2140 foreach ($entries as $entry) {
2141 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2142 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
2143 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2144 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2146 if (empty($published) || empty($updated)) {
2147 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2151 if ($last_updated < $published) {
2152 $last_updated = $published;
2155 if ($last_updated < $updated) {
2156 $last_updated = $updated;
2160 if (!empty($last_updated)) {
2161 return $last_updated;
2168 * Probe data from local profiles without network traffic
2170 * @param string $url
2171 * @return array probed data
2173 public static function localProbe(string $url)
2175 $uid = User::getIdForURL($url);
2180 $profile = User::getOwnerDataById($uid);
2181 if (empty($profile)) {
2185 $approfile = ActivityPub\Transmitter::getProfile($uid);
2186 if (empty($approfile)) {
2190 if (empty($profile['gsid'])) {
2191 $profile['gsid'] = GServer::getID($approfile['generator']['url']);
2194 $data = ['name' => $profile['name'], 'nick' => $profile['nick'], 'guid' => $approfile['diaspora:guid'],
2195 'url' => $profile['url'], 'addr' => $profile['addr'], 'alias' => $profile['alias'],
2196 'photo' => $profile['photo'], 'account-type' => $profile['contact-type'],
2197 'community' => ($profile['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY),
2198 'keywords' => $profile['keywords'], 'location' => $profile['location'], 'about' => $profile['about'],
2199 'hide' => !$profile['net-publish'], 'batch' => '', 'notify' => $profile['notify'],
2200 'poll' => $profile['poll'], 'request' => $profile['request'], 'confirm' => $profile['confirm'],
2201 'subscribe' => $approfile['generator']['url'] . '/follow?url={uri}', 'poco' => $profile['poco'],
2202 'following' => $approfile['following'], 'followers' => $approfile['followers'],
2203 'inbox' => $approfile['inbox'], 'outbox' => $approfile['outbox'],
2204 'sharedinbox' => $approfile['endpoints']['sharedInbox'], 'network' => Protocol::DFRN,
2205 'pubkey' => $profile['upubkey'], 'baseurl' => $approfile['generator']['url'], 'gsid' => $profile['gsid']];
2206 return self::rearrangeData($data);