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\Contact;
34 use Friendica\Model\GServer;
35 use Friendica\Model\Profile;
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\Network;
42 use Friendica\Util\Strings;
43 use Friendica\Util\XML;
46 * This class contain functions for probing URL
50 private static $baseurl;
51 private static $istimeout;
54 * Remove stuff from an URI that doesn't belong there
57 * @return string Cleaned URI
59 public static function cleanURI(string $URI)
61 // At first remove leading and trailing junk
62 $URI = trim($URI, "@#?:/ \t\n\r\0\x0B");
64 $parts = parse_url($URI);
66 if (empty($parts['scheme'])) {
70 // Remove the URL fragment, since these shouldn't be part of any profile URL
71 unset($parts['fragment']);
73 $URI = Network::unparseURL($parts);
79 * Rearrange the array so that it always has the same order
81 * @param array $data Unordered data
83 * @return array Ordered data
85 private static function rearrangeData($data)
87 $fields = ["name", "nick", "guid", "url", "addr", "alias", "photo", "account-type",
88 "community", "keywords", "location", "about", "hide",
89 "batch", "notify", "poll", "request", "confirm", "subscribe", "poco",
90 "following", "followers", "inbox", "outbox", "sharedinbox",
91 "priority", "network", "pubkey", "baseurl", "gsid"];
94 foreach ($fields as $field) {
95 if (isset($data[$field])) {
96 if (in_array($field, ["gsid", "hide", "account-type"])) {
97 $newdata[$field] = (int)$data[$field];
99 $newdata[$field] = $data[$field];
101 } elseif ($field != "gsid") {
102 $newdata[$field] = "";
104 $newdata[$field] = null;
108 // We don't use the "priority" field anymore and replace it with a dummy.
109 $newdata["priority"] = 0;
115 * Check if the hostname belongs to the own server
117 * @param string $host The hostname that is to be checked
119 * @return bool Does the testes hostname belongs to the own server?
121 private static function ownHost($host)
123 $own_host = DI::baseUrl()->getHostname();
125 $parts = parse_url($host);
127 if (!isset($parts['scheme'])) {
128 $parts = parse_url('http://'.$host);
131 if (!isset($parts['host'])) {
134 return $parts['host'] == $own_host;
138 * Probes for webfinger path via "host-meta"
140 * We have to check if the servers in the future still will offer this.
141 * It seems as if it was dropped from the standard.
143 * @param string $host The host part of an url
145 * @return array with template and type of the webfinger template for JSON or XML
146 * @throws HTTPException\InternalServerErrorException
148 private static function hostMeta($host)
150 // Reset the static variable
153 // Handles the case when the hostname contains the scheme
154 if (!parse_url($host, PHP_URL_SCHEME)) {
155 $ssl_url = "https://" . $host . "/.well-known/host-meta";
156 $url = "http://" . $host . "/.well-known/host-meta";
158 $ssl_url = $host . "/.well-known/host-meta";
162 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
164 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
167 $curlResult = Network::curl($ssl_url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
168 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
169 if ($curlResult->isSuccess()) {
170 $xml = $curlResult->getBody();
171 $xrd = XML::parseString($xml, true);
173 $host_url = 'https://' . $host;
177 } elseif ($curlResult->isTimeout()) {
178 Logger::info('Probing timeout', ['url' => $ssl_url], Logger::DEBUG);
179 self::$istimeout = true;
183 if (!is_object($xrd) && !empty($url)) {
184 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
185 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
186 if ($curlResult->isTimeout()) {
187 Logger::info('Probing timeout', ['url' => $url], Logger::DEBUG);
188 self::$istimeout = true;
190 } elseif ($connection_error && $ssl_connection_error) {
191 self::$istimeout = true;
195 $xml = $curlResult->getBody();
196 $xrd = XML::parseString($xml, true);
197 $host_url = 'http://'.$host;
199 if (!is_object($xrd)) {
200 Logger::log("No xrd object found for ".$host, Logger::DEBUG);
204 $links = XML::elementToArray($xrd);
205 if (!isset($links["xrd"]["link"])) {
206 Logger::log("No xrd data found for ".$host, Logger::DEBUG);
210 $lrdd = ['application/jrd+json' => $host_url . '/.well-known/webfinger?resource={uri}'];
212 foreach ($links["xrd"]["link"] as $value => $link) {
213 if (!empty($link["@attributes"])) {
214 $attributes = $link["@attributes"];
215 } elseif ($value == "@attributes") {
221 if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
222 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
224 $lrdd[$type] = $attributes["template"];
228 self::$baseurl = $host_url;
230 Logger::log("Probing successful for ".$host, Logger::DEBUG);
236 * Perform Webfinger lookup and return DFRN data
238 * Given an email style address, perform webfinger lookup and
239 * return the resulting DFRN profile URL, or if no DFRN profile URL
240 * is located, returns an OStatus subscription template (prefixed
241 * with the string 'stat:' to identify it as on OStatus template).
242 * If this isn't an email style address just return $webbie.
243 * Return an empty string if email-style addresses but webfinger fails,
244 * or if the resultant personal XRD doesn't contain a supported
245 * subscription/friend-request attribute.
247 * amended 7/9/2011 to return an hcard which could save potentially loading
248 * a lengthy content page to scrape dfrn attributes
250 * @param string $webbie Address that should be probed
251 * @param string $hcard_url Link to the hcard - is returned by reference
253 * @return string profile link
254 * @throws HTTPException\InternalServerErrorException
256 public static function webfingerDfrn($webbie, &$hcard_url)
260 $links = self::lrdd($webbie);
261 Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA);
262 if (!empty($links) && is_array($links)) {
263 foreach ($links as $link) {
264 if ($link['@attributes']['rel'] === ActivityNamespace::DFRN) {
265 $profile_link = $link['@attributes']['href'];
267 if (($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) && ($profile_link == "")) {
268 $profile_link = 'stat:'.$link['@attributes']['template'];
270 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
271 $hcard_url = $link['@attributes']['href'];
275 return $profile_link;
279 * Check an URI for LRDD data
281 * @param string $uri Address that should be probed
283 * @return array uri data
284 * @throws HTTPException\InternalServerErrorException
286 public static function lrdd(string $uri)
288 $lrdd = self::hostMeta($uri);
291 if (is_bool($lrdd)) {
296 $parts = @parse_url($uri);
297 if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
301 $host = $parts['scheme'] . '://' . $parts["host"];
302 if (!empty($parts["port"])) {
303 $host .= ':'.$parts["port"];
306 $path_parts = explode("/", trim($parts["path"], "/"));
308 $nick = array_pop($path_parts);
311 $lrdd = self::hostMeta($host);
312 $host .= "/".array_shift($path_parts);
313 } while (!$lrdd && (sizeof($path_parts) > 0));
317 Logger::log("No lrdd data found for ".$uri, Logger::DEBUG);
321 foreach ($lrdd as $type => $template) {
326 $path = str_replace('{uri}', urlencode($uri), $template);
327 $webfinger = self::webfinger($path, $type);
329 if (!$webfinger && (strstr($uri, "@"))) {
330 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
331 $webfinger = self::webfinger($path, $type);
334 // Special treatment for Mastodon
335 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
336 // But the webfinger for this format fails.
337 if (!$webfinger && !empty($nick)) {
338 // Mastodon uses a "@" as prefix for usernames in their url format
339 $nick = ltrim($nick, '@');
341 $addr = $nick."@".$host;
343 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
344 $webfinger = self::webfinger($path, $type);
348 if (empty($webfinger["links"])) {
349 Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
355 foreach ($webfinger["links"] as $link) {
356 $data[] = ["@attributes" => $link];
359 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
360 foreach ($webfinger["aliases"] as $alias) {
361 $data[] = ["@attributes" =>
371 * Fetch information (protocol endpoints and user information) about a given uri
373 * @param string $uri Address that should be probed
374 * @param string $network Test for this specific network
375 * @param integer $uid User ID for the probe (only used for mails)
376 * @param boolean $cache Use cached values?
378 * @return array uri data
379 * @throws HTTPException\InternalServerErrorException
380 * @throws \ImagickException
382 public static function uri($uri, $network = '', $uid = -1, $cache = true)
385 $result = DI::cache()->get('Probe::uri:' . $network . ':' . $uri);
386 if (!is_null($result)) {
395 self::$istimeout = false;
397 if ($network != Protocol::ACTIVITYPUB) {
398 $data = self::detect($uri, $network, $uid);
403 // When the previous detection process had got a time out
404 // we could falsely detect a Friendica profile as AP profile.
405 if (!self::$istimeout) {
406 $ap_profile = ActivityPub::probeProfile($uri, !$cache);
408 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
410 } elseif (!empty($ap_profile)) {
411 $ap_profile['batch'] = '';
412 $data = array_merge($ap_profile, $data);
415 Logger::notice('Time out detected. AP will not be probed.', ['uri' => $uri]);
418 if (!isset($data['url'])) {
422 if (empty($data['photo'])) {
423 $data['photo'] = DI::baseUrl() . '/images/person-300.jpg';
426 if (empty($data['name'])) {
427 if (!empty($data['nick'])) {
428 $data['name'] = $data['nick'];
431 if (empty($data['name'])) {
432 $data['name'] = $data['url'];
436 if (empty($data['nick'])) {
437 $data['nick'] = strtolower($data['name']);
439 if (strpos($data['nick'], ' ')) {
440 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
444 if (!empty(self::$baseurl)) {
445 $data['baseurl'] = self::$baseurl;
448 if (!empty($data['baseurl']) && empty($data['gsid'])) {
449 $data['gsid'] = GServer::getID($data['baseurl']);
452 if (empty($data['network'])) {
453 $data['network'] = Protocol::PHANTOM;
456 // Ensure that local connections always are DFRN
457 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
458 $data['network'] = Protocol::DFRN;
461 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
462 $data['hide'] = self::getHideStatus($data['url']);
465 $data = self::rearrangeData($data);
467 // Only store into the cache if the value seems to be valid
468 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
469 DI::cache()->set('Probe::uri:' . $network . ':' . $uri, $data, Duration::DAY);
477 * Fetches the "hide" status from the profile
479 * @param string $url URL of the profile
481 * @return boolean "hide" status
483 private static function getHideStatus($url)
485 $curlResult = Network::curl($url);
486 if (!$curlResult->isSuccess()) {
490 // If the file is too large then exit
491 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
495 // If it isn't a HTML file then exit
496 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
500 $body = $curlResult->getBody();
502 $doc = new DOMDocument();
503 @$doc->loadHTML($body);
505 $xpath = new DOMXPath($doc);
507 $list = $xpath->query('//meta[@name]');
508 foreach ($list as $node) {
510 if ($node->attributes->length) {
511 foreach ($node->attributes as $attribute) {
512 $meta_tag[$attribute->name] = $attribute->value;
516 if (empty($meta_tag['content'])) {
520 $content = strtolower(trim($meta_tag['content']));
522 switch (strtolower(trim($meta_tag['name']))) {
523 case 'dfrn-global-visibility':
524 if ($content == 'false') {
529 if (strpos($content, 'noindex') !== false) {
540 * Fetch the "subscribe" and add it to the result
542 * @param array $result
543 * @param array $webfinger
544 * @return array result
546 private static function getSubscribeLink(array $result, array $webfinger)
548 if (empty($webfinger['links'])) {
552 foreach ($webfinger['links'] as $link) {
553 if ($link['rel'] === ActivityNamespace::OSTATUSSUB) {
554 $result['subscribe'] = $link['template'];
562 * Fetch information (protocol endpoints and user information) about a given uri
564 * This function is only called by the "uri" function that adds caching and rearranging of data.
566 * @param string $uri Address that should be probed
567 * @param string $network Test for this specific network
568 * @param integer $uid User ID for the probe (only used for mails)
570 * @return array uri data
571 * @throws HTTPException\InternalServerErrorException
573 private static function detect($uri, $network, $uid)
575 $parts = parse_url($uri);
579 'network' => $network,
584 Hook::callAll('probe_detect', $hookData);
586 if ($hookData['result']) {
587 return $hookData['result'];
590 if (!empty($parts["scheme"]) && !empty($parts["host"])) {
591 $host = $parts["host"];
592 if (!empty($parts["port"])) {
593 $host .= ':'.$parts["port"];
596 if ($host == 'twitter.com') {
597 return self::twitter($uri);
599 $lrdd = self::hostMeta($host);
601 if (is_bool($lrdd)) {
605 $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
607 while (!$lrdd && (sizeof($path_parts) > 1)) {
608 $host .= "/".array_shift($path_parts);
609 $lrdd = self::hostMeta($host);
612 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
613 return self::feed($uri);
615 $nick = array_pop($path_parts);
617 // Mastodon uses a "@" as prefix for usernames in their url format
618 $nick = ltrim($nick, '@');
620 $addr = $nick."@".$host;
621 } elseif (strstr($uri, '@')) {
622 // If the URI starts with "mailto:" then jump directly to the mail detection
623 if (strpos($uri, 'mailto:') !== false) {
624 $uri = str_replace('mailto:', '', $uri);
625 return self::mail($uri, $uid);
628 if ($network == Protocol::MAIL) {
629 return self::mail($uri, $uid);
631 // Remove "acct:" from the URI
632 $uri = str_replace('acct:', '', $uri);
634 $host = substr($uri, strpos($uri, '@') + 1);
635 $nick = substr($uri, 0, strpos($uri, '@'));
637 if (strpos($uri, '@twitter.com')) {
638 return self::twitter($uri);
640 $lrdd = self::hostMeta($host);
642 if (is_bool($lrdd)) {
647 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
648 return self::mail($uri, $uid);
652 Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
658 /// @todo Do we need the prefix "acct:" or "acct://"?
660 foreach ($lrdd as $type => $template) {
667 $path = str_replace('{uri}', urlencode($uri), $template);
668 $webfinger = self::webfinger($path, $type);
671 // Then try the address
673 $path = str_replace('{uri}', urlencode("acct:" . $addr), $template);
674 $webfinger = self::webfinger($path, $type);
677 // Finally try without the "acct"
679 $path = str_replace('{uri}', urlencode($addr), $template);
680 $webfinger = self::webfinger($path, $type);
683 // We cannot be sure that the detected address was correct, so we don't use the values
684 if ($webfinger && ($uri != $addr)) {
691 return self::feed($uri);
696 Logger::info("Probing", ['uri' => $uri]);
698 if (in_array($network, ["", Protocol::DFRN])) {
699 $result = self::dfrn($webfinger);
701 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
702 $result = self::diaspora($webfinger);
704 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
705 $result = self::ostatus($webfinger);
707 if (in_array($network, ['', Protocol::ZOT])) {
708 $result = self::zot($webfinger, $result);
710 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
711 $result = self::pumpio($webfinger, $addr);
713 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
714 $result = self::feed($uri);
716 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
717 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
718 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
719 $result["nick"] = $nick;
722 if (empty($result["addr"]) && ($addr != "")) {
723 $result["addr"] = $addr;
727 $result = self::getSubscribeLink($result, $webfinger);
729 if (empty($result["network"])) {
730 $result["network"] = Protocol::PHANTOM;
733 if (empty($result["url"])) {
734 $result["url"] = $uri;
737 Logger::log($uri." is ".$result["network"], Logger::DEBUG);
739 if (empty($result["baseurl"]) && ($result["network"] != Protocol::PHANTOM)) {
740 $pos = strpos($result["url"], $host);
742 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
750 * Check for Zot contact
752 * @param array $webfinger Webfinger data
753 * @param array $data previously probed data
755 * @return array Zot data
756 * @throws HTTPException\InternalServerErrorException
758 private static function zot($webfinger, $data)
760 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
761 foreach ($webfinger["aliases"] as $alias) {
762 if (substr($alias, 0, 5) == 'acct:') {
763 $data["addr"] = substr($alias, 5);
768 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
769 $data["addr"] = substr($webfinger["subject"], 5);
773 foreach ($webfinger['links'] as $link) {
774 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
775 $zot_url = $link['href'];
779 if (empty($zot_url) && !empty($data['addr']) && !empty(self::$baseurl)) {
780 $condition = ['nurl' => Strings::normaliseLink(self::$baseurl), 'platform' => ['hubzilla']];
781 if (!DBA::exists('gserver', $condition)) {
784 $zot_url = self::$baseurl . '/.well-known/zot-info?address=' . $data['addr'];
787 if (empty($zot_url)) {
791 $data = self::pollZot($zot_url, $data);
793 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
794 foreach ($webfinger['aliases'] as $alias) {
795 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
796 $data['alias'] = $alias;
804 public static function pollZot($url, $data)
806 $curlResult = Network::curl($url);
807 if ($curlResult->isTimeout()) {
810 $content = $curlResult->getBody();
815 $json = json_decode($content, true);
816 if (!is_array($json)) {
820 if (empty($data['network'])) {
821 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
822 $data['network'] = Protocol::ZOT;
823 } elseif (!isset($json['protocols'])) {
824 $data['network'] = Protocol::ZOT;
828 if (!empty($json['guid']) && empty($data['guid'])) {
829 $data['guid'] = $json['guid'];
831 if (!empty($json['key']) && empty($data['pubkey'])) {
832 $data['pubkey'] = $json['key'];
834 if (!empty($json['name'])) {
835 $data['name'] = $json['name'];
837 if (!empty($json['photo'])) {
838 $data['photo'] = $json['photo'];
839 if (!empty($json['photo_updated'])) {
840 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
843 if (!empty($json['address'])) {
844 $data['addr'] = $json['address'];
846 if (!empty($json['url'])) {
847 $data['url'] = $json['url'];
849 if (!empty($json['connections_url'])) {
850 $data['poco'] = $json['connections_url'];
852 if (isset($json['searchable'])) {
853 $data['hide'] = !$json['searchable'];
855 if (!empty($json['public_forum'])) {
856 $data['community'] = $json['public_forum'];
857 $data['account-type'] = Contact::PAGE_COMMUNITY;
860 if (!empty($json['profile'])) {
861 $profile = $json['profile'];
862 if (!empty($profile['description'])) {
863 $data['about'] = $profile['description'];
865 if (!empty($profile['keywords'])) {
866 $keywords = implode(', ', $profile['keywords']);
867 if (!empty($keywords)) {
868 $data['keywords'] = $keywords;
873 if (!empty($profile['region'])) {
874 $loc['region'] = $profile['region'];
876 if (!empty($profile['country'])) {
877 $loc['country-name'] = $profile['country'];
879 $location = Profile::formatLocation($loc);
880 if (!empty($location)) {
881 $data['location'] = $location;
889 * Perform a webfinger request.
891 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
893 * @param string $url Address that should be probed
894 * @param string $type type
896 * @return array webfinger data
897 * @throws HTTPException\InternalServerErrorException
899 public static function webfinger($url, $type)
901 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
903 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
904 if ($curlResult->isTimeout()) {
905 self::$istimeout = true;
908 $data = $curlResult->getBody();
910 $webfinger = json_decode($data, true);
911 if (!empty($webfinger)) {
912 if (!isset($webfinger["links"])) {
913 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
919 // If it is not JSON, maybe it is XML
920 $xrd = XML::parseString($data, true);
921 if (!is_object($xrd)) {
922 Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
926 $xrd_arr = XML::elementToArray($xrd);
927 if (!isset($xrd_arr["xrd"]["link"])) {
928 Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
934 if (!empty($xrd_arr["xrd"]["subject"])) {
935 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
938 if (!empty($xrd_arr["xrd"]["alias"])) {
939 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
942 $webfinger["links"] = [];
944 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
945 if (!empty($data["@attributes"])) {
946 $attributes = $data["@attributes"];
947 } elseif ($value == "@attributes") {
953 $webfinger["links"][] = $attributes;
959 * Poll the Friendica specific noscrape page.
961 * "noscrape" is a faster alternative to fetch the data from the hcard.
962 * This functionality was originally created for the directory.
964 * @param string $noscrape_url Link to the noscrape page
965 * @param array $data The already fetched data
967 * @return array noscrape data
968 * @throws HTTPException\InternalServerErrorException
970 private static function pollNoscrape($noscrape_url, $data)
972 $curlResult = Network::curl($noscrape_url);
973 if ($curlResult->isTimeout()) {
974 self::$istimeout = true;
977 $content = $curlResult->getBody();
979 Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
983 $json = json_decode($content, true);
984 if (!is_array($json)) {
985 Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
989 if (!empty($json["fn"])) {
990 $data["name"] = $json["fn"];
993 if (!empty($json["addr"])) {
994 $data["addr"] = $json["addr"];
997 if (!empty($json["nick"])) {
998 $data["nick"] = $json["nick"];
1001 if (!empty($json["guid"])) {
1002 $data["guid"] = $json["guid"];
1005 if (!empty($json["comm"])) {
1006 $data["community"] = $json["comm"];
1009 if (!empty($json["tags"])) {
1010 $keywords = implode(", ", $json["tags"]);
1011 if ($keywords != "") {
1012 $data["keywords"] = $keywords;
1016 $location = Profile::formatLocation($json);
1018 $data["location"] = $location;
1021 if (!empty($json["about"])) {
1022 $data["about"] = $json["about"];
1025 if (!empty($json["key"])) {
1026 $data["pubkey"] = $json["key"];
1029 if (!empty($json["photo"])) {
1030 $data["photo"] = $json["photo"];
1033 if (!empty($json["dfrn-request"])) {
1034 $data["request"] = $json["dfrn-request"];
1037 if (!empty($json["dfrn-confirm"])) {
1038 $data["confirm"] = $json["dfrn-confirm"];
1041 if (!empty($json["dfrn-notify"])) {
1042 $data["notify"] = $json["dfrn-notify"];
1045 if (!empty($json["dfrn-poll"])) {
1046 $data["poll"] = $json["dfrn-poll"];
1049 if (isset($json["hide"])) {
1050 $data["hide"] = (bool)$json["hide"];
1052 $data["hide"] = false;
1059 * Check for valid DFRN data
1061 * @param array $data DFRN data
1063 * @return int Number of errors
1065 public static function validDfrn($data)
1068 if (!isset($data['key'])) {
1071 if (!isset($data['dfrn-request'])) {
1074 if (!isset($data['dfrn-confirm'])) {
1077 if (!isset($data['dfrn-notify'])) {
1080 if (!isset($data['dfrn-poll'])) {
1087 * Fetch data from a DFRN profile page and via "noscrape"
1089 * @param string $profile_link Link to the profile page
1091 * @return array profile data
1092 * @throws HTTPException\InternalServerErrorException
1093 * @throws \ImagickException
1095 public static function profile($profile_link)
1099 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
1101 // Fetch data via noscrape - this is faster
1102 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1103 $data = self::pollNoscrape($noscrape_url, $data);
1105 if (!isset($data["notify"])
1106 || !isset($data["confirm"])
1107 || !isset($data["request"])
1108 || !isset($data["poll"])
1109 || !isset($data["name"])
1110 || !isset($data["photo"])
1112 $data = self::pollHcard($profile_link, $data, true);
1117 if (empty($data["addr"]) || empty($data["nick"])) {
1118 $probe_data = self::uri($profile_link);
1119 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1120 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1123 $prof_data["addr"] = $data["addr"];
1124 $prof_data["nick"] = $data["nick"];
1125 $prof_data["dfrn-request"] = $data['request'] ?? null;
1126 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1127 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1128 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1129 $prof_data["photo"] = $data['photo'] ?? null;
1130 $prof_data["fn"] = $data['name'] ?? null;
1131 $prof_data["key"] = $data['pubkey'] ?? null;
1133 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
1139 * Check for DFRN contact
1141 * @param array $webfinger Webfinger data
1143 * @return array DFRN data
1144 * @throws HTTPException\InternalServerErrorException
1146 private static function dfrn($webfinger)
1150 // The array is reversed to take into account the order of preference for same-rel links
1151 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1152 foreach (array_reverse($webfinger["links"]) as $link) {
1153 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1154 $data["network"] = Protocol::DFRN;
1155 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1156 $data["poll"] = $link["href"];
1157 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1158 $data["url"] = $link["href"];
1159 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1160 $hcard_url = $link["href"];
1161 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1162 $data["poco"] = $link["href"];
1163 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1164 $data["photo"] = $link["href"];
1165 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1166 $data["baseurl"] = trim($link["href"], '/');
1167 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1168 $data["guid"] = $link["href"];
1169 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1170 $data["pubkey"] = base64_decode($link["href"]);
1172 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1173 if (strstr($data["pubkey"], 'RSA ')) {
1174 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1179 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1180 foreach ($webfinger["aliases"] as $alias) {
1181 if (empty($data["url"]) && !strstr($alias, "@")) {
1182 $data["url"] = $alias;
1183 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1184 $data["alias"] = $alias;
1185 } elseif (substr($alias, 0, 5) == 'acct:') {
1186 $data["addr"] = substr($alias, 5);
1191 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1192 $data["addr"] = substr($webfinger["subject"], 5);
1195 if (!isset($data["network"]) || ($hcard_url == "")) {
1199 // Fetch data via noscrape - this is faster
1200 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1201 $data = self::pollNoscrape($noscrape_url, $data);
1203 if (isset($data["notify"])
1204 && isset($data["confirm"])
1205 && isset($data["request"])
1206 && isset($data["poll"])
1207 && isset($data["name"])
1208 && isset($data["photo"])
1213 $data = self::pollHcard($hcard_url, $data, true);
1219 * Poll the hcard page (Diaspora and Friendica specific)
1221 * @param string $hcard_url Link to the hcard page
1222 * @param array $data The already fetched data
1223 * @param boolean $dfrn Poll DFRN specific data
1225 * @return array hcard data
1226 * @throws HTTPException\InternalServerErrorException
1228 private static function pollHcard($hcard_url, $data, $dfrn = false)
1230 $curlResult = Network::curl($hcard_url);
1231 if ($curlResult->isTimeout()) {
1232 self::$istimeout = true;
1235 $content = $curlResult->getBody();
1240 $doc = new DOMDocument();
1241 if (!@$doc->loadHTML($content)) {
1245 $xpath = new DomXPath($doc);
1247 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1248 if (!is_object($vcards)) {
1252 if (!isset($data["baseurl"])) {
1253 $data["baseurl"] = "";
1256 if ($vcards->length > 0) {
1257 $vcard = $vcards->item(0);
1259 // We have to discard the guid from the hcard in favour of the guid from lrdd
1260 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1261 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1262 if (($search->length > 0) && empty($data["guid"])) {
1263 $data["guid"] = $search->item(0)->nodeValue;
1266 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1267 if ($search->length > 0) {
1268 $data["nick"] = $search->item(0)->nodeValue;
1271 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1272 if ($search->length > 0) {
1273 $data["name"] = $search->item(0)->nodeValue;
1276 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1277 if ($search->length > 0) {
1278 $data["searchable"] = $search->item(0)->nodeValue;
1281 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1282 if ($search->length > 0) {
1283 $data["pubkey"] = $search->item(0)->nodeValue;
1284 if (strstr($data["pubkey"], 'RSA ')) {
1285 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1289 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1290 if ($search->length > 0) {
1291 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1296 if (!empty($vcard)) {
1297 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1298 foreach ($photos as $photo) {
1300 foreach ($photo->attributes as $attribute) {
1301 $attr[$attribute->name] = trim($attribute->value);
1304 if (isset($attr["src"]) && isset($attr["width"])) {
1305 $avatar[$attr["width"]] = $attr["src"];
1308 // We don't have a width. So we just take everything that we got.
1309 // This is a Hubzilla workaround which doesn't send a width.
1310 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1311 $avatar[] = $attr["src"];
1316 if (sizeof($avatar)) {
1318 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1322 // Poll DFRN specific data
1323 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1324 if ($search->length > 0) {
1325 foreach ($search as $link) {
1326 //$data["request"] = $search->item(0)->nodeValue;
1328 foreach ($link->attributes as $attribute) {
1329 $attr[$attribute->name] = trim($attribute->value);
1332 $data[substr($attr["rel"], 5)] = $attr["href"];
1336 // Older Friendica versions had used the "uid" field differently than newer versions
1337 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1338 unset($data["guid"]);
1347 * Check for Diaspora contact
1349 * @param array $webfinger Webfinger data
1351 * @return array Diaspora data
1352 * @throws HTTPException\InternalServerErrorException
1354 private static function diaspora($webfinger)
1359 // The array is reversed to take into account the order of preference for same-rel links
1360 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1361 foreach (array_reverse($webfinger["links"]) as $link) {
1362 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1363 $hcard_url = $link["href"];
1364 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1365 $data["baseurl"] = trim($link["href"], '/');
1366 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1367 $data["guid"] = $link["href"];
1368 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1369 $data["url"] = $link["href"];
1370 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1371 $data["poll"] = $link["href"];
1372 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1373 $data["poco"] = $link["href"];
1374 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1375 $data["notify"] = $link["href"];
1376 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1377 $data["pubkey"] = base64_decode($link["href"]);
1379 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1380 if (strstr($data["pubkey"], 'RSA ')) {
1381 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1386 if (empty($data["url"]) || empty($hcard_url)) {
1390 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1391 foreach ($webfinger["aliases"] as $alias) {
1392 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1393 $data["alias"] = $alias;
1394 } elseif (substr($alias, 0, 5) == 'acct:') {
1395 $data["addr"] = substr($alias, 5);
1400 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1401 $data["addr"] = substr($webfinger["subject"], 5);
1404 // Fetch further information from the hcard
1405 $data = self::pollHcard($hcard_url, $data);
1411 if (!empty($data["url"])
1412 && !empty($data["guid"])
1413 && !empty($data["baseurl"])
1414 && !empty($data["pubkey"])
1415 && !empty($hcard_url)
1417 $data["network"] = Protocol::DIASPORA;
1419 // The Diaspora handle must always be lowercase
1420 if (!empty($data["addr"])) {
1421 $data["addr"] = strtolower($data["addr"]);
1424 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1425 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1426 $data["batch"] = $data["baseurl"] . "/receive/public";
1435 * Check for OStatus contact
1437 * @param array $webfinger Webfinger data
1438 * @param bool $short Short detection mode
1440 * @return array|bool OStatus data or "false" on error or "true" on short mode
1441 * @throws HTTPException\InternalServerErrorException
1443 private static function ostatus($webfinger, $short = false)
1447 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1448 foreach ($webfinger["aliases"] as $alias) {
1449 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1450 $data["addr"] = str_replace('acct:', '', $alias);
1455 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1456 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1458 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1461 if (!empty($webfinger["links"])) {
1462 // The array is reversed to take into account the order of preference for same-rel links
1463 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1464 foreach (array_reverse($webfinger["links"]) as $link) {
1465 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1466 && (($link["type"] ?? "") == "text/html")
1467 && ($link["href"] != "")
1469 $data["url"] = $data["alias"] = $link["href"];
1470 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1471 $data["notify"] = $link["href"];
1472 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1473 $data["poll"] = $link["href"];
1474 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1475 $pubkey = $link["href"];
1477 if (substr($pubkey, 0, 5) === 'data:') {
1478 if (strstr($pubkey, ',')) {
1479 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1481 $pubkey = substr($pubkey, 5);
1483 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1484 $curlResult = Network::curl($pubkey);
1485 if ($curlResult->isTimeout()) {
1486 self::$istimeout = true;
1487 return $short ? false : [];
1489 $pubkey = $curlResult->getBody();
1492 $key = explode(".", $pubkey);
1494 if (sizeof($key) >= 3) {
1495 $m = Strings::base64UrlDecode($key[1]);
1496 $e = Strings::base64UrlDecode($key[2]);
1497 $data["pubkey"] = Crypto::meToPem($m, $e);
1503 if (isset($data["notify"]) && isset($data["pubkey"])
1504 && isset($data["poll"])
1505 && isset($data["url"])
1507 $data["network"] = Protocol::OSTATUS;
1509 return $short ? false : [];
1516 // Fetch all additional data from the feed
1517 $curlResult = Network::curl($data["poll"]);
1518 if ($curlResult->isTimeout()) {
1519 self::$istimeout = true;
1522 $feed = $curlResult->getBody();
1523 $feed_data = Feed::import($feed);
1528 if (!empty($feed_data["header"]["author-name"])) {
1529 $data["name"] = $feed_data["header"]["author-name"];
1531 if (!empty($feed_data["header"]["author-nick"])) {
1532 $data["nick"] = $feed_data["header"]["author-nick"];
1534 if (!empty($feed_data["header"]["author-avatar"])) {
1535 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1537 if (!empty($feed_data["header"]["author-id"])) {
1538 $data["alias"] = $feed_data["header"]["author-id"];
1540 if (!empty($feed_data["header"]["author-location"])) {
1541 $data["location"] = $feed_data["header"]["author-location"];
1543 if (!empty($feed_data["header"]["author-about"])) {
1544 $data["about"] = $feed_data["header"]["author-about"];
1546 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1547 // So we take the value that we just fetched, although the other one worked as well
1548 if (!empty($feed_data["header"]["author-link"])) {
1549 $data["url"] = $feed_data["header"]["author-link"];
1552 if ($data["url"] == $data["alias"]) {
1553 $data["alias"] = '';
1556 /// @todo Fetch location and "about" from the feed as well
1561 * Fetch data from a pump.io profile page
1563 * @param string $profile_link Link to the profile page
1565 * @return array profile data
1567 private static function pumpioProfileData($profile_link)
1569 $curlResult = Network::curl($profile_link);
1570 if (!$curlResult->isSuccess()) {
1574 $doc = new DOMDocument();
1575 if (!@$doc->loadHTML($curlResult->getBody())) {
1579 $xpath = new DomXPath($doc);
1583 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1585 if ($data["name"] == '') {
1586 // This is ugly - but pump.io doesn't seem to know a better way for it
1587 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1588 $pos = strpos($data["name"], chr(10));
1590 $data["name"] = trim(substr($data["name"], 0, $pos));
1594 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1596 if ($data["location"] == '') {
1597 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1600 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1602 if ($data["about"] == '') {
1603 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1606 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1608 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1611 foreach ($avatar->attributes as $attribute) {
1612 if ($attribute->name == "src") {
1613 $data["photo"] = trim($attribute->value);
1622 * Check for pump.io contact
1624 * @param array $webfinger Webfinger data
1625 * @param string $addr
1626 * @return array pump.io data
1628 private static function pumpio($webfinger, $addr)
1631 // The array is reversed to take into account the order of preference for same-rel links
1632 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1633 foreach (array_reverse($webfinger["links"]) as $link) {
1634 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1635 && (($link["type"] ?? "") == "text/html")
1636 && ($link["href"] != "")
1638 $data["url"] = $link["href"];
1639 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1640 $data["notify"] = $link["href"];
1641 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1642 $data["poll"] = $link["href"];
1643 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1644 $data["dialback"] = $link["href"];
1647 if (isset($data["poll"]) && isset($data["notify"])
1648 && isset($data["dialback"])
1649 && isset($data["url"])
1651 // by now we use these fields only for the network type detection
1652 // So we unset all data that isn't used at the moment
1653 unset($data["dialback"]);
1655 $data["network"] = Protocol::PUMPIO;
1660 $profile_data = self::pumpioProfileData($data["url"]);
1662 if (!$profile_data) {
1666 $data = array_merge($data, $profile_data);
1668 if (($addr != '') && ($data['name'] != '')) {
1669 $name = trim(str_replace($addr, '', $data['name']));
1671 $data['name'] = $name;
1679 * Check for twitter contact
1681 * @param string $uri
1683 * @return array twitter data
1685 private static function twitter($uri)
1687 if (preg_match('=(.*)@twitter.com=i', $uri, $matches)) {
1688 $nick = $matches[1];
1689 } elseif (preg_match('=https?://twitter.com/(.*)=i', $uri, $matches)) {
1690 $nick = $matches[1];
1696 $data['url'] = 'https://twitter.com/' . $nick;
1697 $data['addr'] = $nick . '@twitter.com';
1698 $data['nick'] = $data['name'] = $nick;
1699 $data['network'] = Protocol::TWITTER;
1700 $data['baseurl'] = 'https://twitter.com';
1706 * Checks HTML page for RSS feed link
1708 * @param string $url Page link
1709 * @param string $body Page body string
1710 * @return string|false Feed link or false if body was invalid HTML document
1712 public static function getFeedLink(string $url, string $body)
1714 $doc = new DOMDocument();
1715 if (!@$doc->loadHTML($body)) {
1719 $xpath = new DOMXPath($doc);
1721 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1723 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1729 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1731 * Loosely based on RFC 1808
1733 * @see https://tools.ietf.org/html/rfc1808
1735 * @param string $href The potential relative href found in the HTML document
1736 * @param string $base The HTML document URL
1737 * @param DOMXPath $xpath The HTML document XPath
1740 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath)
1742 if (filter_var($href, FILTER_VALIDATE_URL)) {
1746 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1748 $baseParts = parse_url($base);
1750 // Naked domain case (scheme://basehost)
1751 $path = $baseParts['path'] ?? '/';
1753 // Remove the filename part of the path if it exists (/base/path/file)
1754 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1756 $hrefParts = parse_url($href);
1758 // Root path case (/path) including relative scheme case (//host/path)
1759 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1760 $path = $hrefParts['path'];
1762 $path = $path . '/' . $hrefParts['path'];
1764 // Resolve arbitrary relative path
1765 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1766 $parts = array_filter(explode('/', $path), 'strlen');
1767 $absolutes = array();
1768 foreach ($parts as $part) {
1769 if ('.' == $part) continue;
1770 if ('..' == $part) {
1771 array_pop($absolutes);
1773 $absolutes[] = $part;
1777 $path = '/' . implode('/', $absolutes);
1780 // Relative scheme case (//host/path)
1781 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1782 $baseParts['path'] = $path;
1783 unset($baseParts['query']);
1784 unset($baseParts['fragment']);
1786 return Network::unparseURL($baseParts);
1790 * Check for feed contact
1792 * @param string $url Profile link
1793 * @param boolean $probe Do a probe if the page contains a feed link
1795 * @return array feed data
1796 * @throws HTTPException\InternalServerErrorException
1798 private static function feed($url, $probe = true)
1800 $curlResult = Network::curl($url);
1801 if ($curlResult->isTimeout()) {
1802 self::$istimeout = true;
1805 $feed = $curlResult->getBody();
1806 $feed_data = Feed::import($feed);
1813 $feed_url = self::getFeedLink($url, $feed);
1819 return self::feed($feed_url, false);
1822 if (!empty($feed_data["header"]["author-name"])) {
1823 $data["name"] = $feed_data["header"]["author-name"];
1826 if (!empty($feed_data["header"]["author-nick"])) {
1827 $data["nick"] = $feed_data["header"]["author-nick"];
1830 if (!empty($feed_data["header"]["author-avatar"])) {
1831 $data["photo"] = $feed_data["header"]["author-avatar"];
1834 if (!empty($feed_data["header"]["author-id"])) {
1835 $data["alias"] = $feed_data["header"]["author-id"];
1838 $data["url"] = $url;
1839 $data["poll"] = $url;
1841 if (!empty($feed_data["header"]["author-link"])) {
1842 $data["baseurl"] = $feed_data["header"]["author-link"];
1844 $data["baseurl"] = $data["url"];
1847 $data["network"] = Protocol::FEED;
1853 * Check for mail contact
1855 * @param string $uri Profile link
1856 * @param integer $uid User ID
1858 * @return array mail data
1859 * @throws \Exception
1861 private static function mail($uri, $uid)
1863 if (!Network::isEmailDomainValid($uri)) {
1871 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1873 $condition = ["`uid` = ? AND `server` != ''", $uid];
1874 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1875 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1877 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1881 $mailbox = Email::constructMailboxName($mailacct);
1883 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1884 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1889 $msgs = Email::poll($mbox, $uri);
1890 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1892 if (!count($msgs)) {
1896 $phost = substr($uri, strpos($uri, '@') + 1);
1899 $data["addr"] = $uri;
1900 $data["network"] = Protocol::MAIL;
1901 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1902 $data["nick"] = $data["name"];
1903 $data["photo"] = Network::lookupAvatarByEmail($uri);
1904 $data["url"] = 'mailto:'.$uri;
1905 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1906 $data["poll"] = 'email ' . Strings::getRandomHex();
1908 $x = Email::messageMeta($mbox, $msgs[0]);
1909 if (stristr($x[0]->from, $uri)) {
1910 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1911 } elseif (stristr($x[0]->to, $uri)) {
1912 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1915 foreach ($adr as $feadr) {
1916 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1917 &&(strcasecmp($feadr->host, $phost) == 0)
1918 && (strlen($feadr->personal))
1920 $personal = imap_mime_header_decode($feadr->personal);
1922 foreach ($personal as $perspart) {
1923 if ($perspart->charset != "default") {
1924 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1926 $data["name"] .= $perspart->text;
1930 $data["name"] = Strings::escapeTags($data["name"]);
1934 if (!empty($mbox)) {
1941 * Mix two paths together to possibly fix missing parts
1943 * @param string $avatar Path to the avatar
1944 * @param string $base Another path that is hopefully complete
1946 * @return string fixed avatar path
1947 * @throws \Exception
1949 public static function fixAvatar($avatar, $base)
1951 $base_parts = parse_url($base);
1953 // Remove all parts that could create a problem
1954 unset($base_parts['path']);
1955 unset($base_parts['query']);
1956 unset($base_parts['fragment']);
1958 $avatar_parts = parse_url($avatar);
1961 $parts = array_merge($base_parts, $avatar_parts);
1963 // And put them together again
1964 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1965 $host = isset($parts['host']) ? $parts['host'] : '';
1966 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1967 $path = isset($parts['path']) ? $parts['path'] : '';
1968 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1969 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1971 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1973 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);