3 * @file src/Network/Probe.php
5 namespace Friendica\Network;
8 * @file src/Network/Probe.php
9 * @brief Functions for probing URL
14 use Friendica\Core\Cache;
15 use Friendica\Core\Config;
16 use Friendica\Core\Logger;
17 use Friendica\Core\Protocol;
18 use Friendica\Core\System;
19 use Friendica\Database\DBA;
20 use Friendica\Model\Profile;
21 use Friendica\Protocol\ActivityPub;
22 use Friendica\Protocol\Email;
23 use Friendica\Protocol\Feed;
24 use Friendica\Util\Crypto;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\Network;
27 use Friendica\Util\Strings;
28 use Friendica\Util\XML;
31 * @brief This class contain functions for probing URL
36 private static $baseurl;
37 private static $istimeout;
40 * @brief Rearrange the array so that it always has the same order
42 * @param array $data Unordered data
44 * @return array Ordered data
46 private static function rearrangeData($data)
48 $fields = ["name", "nick", "guid", "url", "addr", "alias",
49 "photo", "community", "keywords", "location", "about",
50 "batch", "notify", "poll", "request", "confirm", "poco",
51 "priority", "network", "pubkey", "baseurl"];
54 foreach ($fields as $field) {
55 if (isset($data[$field])) {
56 $newdata[$field] = $data[$field];
58 $newdata[$field] = "";
62 // We don't use the "priority" field anymore and replace it with a dummy.
63 $newdata["priority"] = 0;
69 * @brief Check if the hostname belongs to the own server
71 * @param string $host The hostname that is to be checked
73 * @return bool Does the testes hostname belongs to the own server?
75 private static function ownHost($host)
77 $own_host = \get_app()->getHostName();
79 $parts = parse_url($host);
81 if (!isset($parts['scheme'])) {
82 $parts = parse_url('http://'.$host);
85 if (!isset($parts['host'])) {
88 return $parts['host'] == $own_host;
92 * @brief Probes for webfinger path via "host-meta"
94 * We have to check if the servers in the future still will offer this.
95 * It seems as if it was dropped from the standard.
97 * @param string $host The host part of an url
99 * @return array with template and type of the webfinger template for JSON or XML
100 * @throws HTTPException\InternalServerErrorException
102 private static function hostMeta($host)
104 // Reset the static variable
107 $ssl_url = "https://".$host."/.well-known/host-meta";
108 $url = "http://".$host."/.well-known/host-meta";
110 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
112 Logger::log("Probing for ".$host, Logger::DEBUG);
115 $curlResult = Network::curl($ssl_url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
116 if ($curlResult->isSuccess()) {
117 $xml = $curlResult->getBody();
118 $xrd = XML::parseString($xml, false);
119 $host_url = 'https://'.$host;
122 if (!is_object($xrd)) {
123 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
124 if ($curlResult->isTimeout()) {
125 Logger::log("Probing timeout for " . $url, Logger::DEBUG);
126 self::$istimeout = true;
129 $xml = $curlResult->getBody();
130 $xrd = XML::parseString($xml, false);
131 $host_url = 'http://'.$host;
133 if (!is_object($xrd)) {
134 Logger::log("No xrd object found for ".$host, Logger::DEBUG);
138 $links = XML::elementToArray($xrd);
139 if (!isset($links["xrd"]["link"])) {
140 Logger::log("No xrd data found for ".$host, Logger::DEBUG);
145 // The following webfinger path is defined in RFC 7033 https://tools.ietf.org/html/rfc7033
146 // Problem is that Hubzilla currently doesn't provide all data in the JSON webfinger
147 // compared to the XML webfinger. So this is commented out by now.
148 // $lrdd = array("application/jrd+json" => $host_url.'/.well-known/webfinger?resource={uri}');
150 foreach ($links["xrd"]["link"] as $value => $link) {
151 if (!empty($link["@attributes"])) {
152 $attributes = $link["@attributes"];
153 } elseif ($value == "@attributes") {
159 if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
160 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
162 $lrdd[$type] = $attributes["template"];
166 self::$baseurl = $host_url;
168 Logger::log("Probing successful for ".$host, Logger::DEBUG);
174 * @brief Perform Webfinger lookup and return DFRN data
176 * Given an email style address, perform webfinger lookup and
177 * return the resulting DFRN profile URL, or if no DFRN profile URL
178 * is located, returns an OStatus subscription template (prefixed
179 * with the string 'stat:' to identify it as on OStatus template).
180 * If this isn't an email style address just return $webbie.
181 * Return an empty string if email-style addresses but webfinger fails,
182 * or if the resultant personal XRD doesn't contain a supported
183 * subscription/friend-request attribute.
185 * amended 7/9/2011 to return an hcard which could save potentially loading
186 * a lengthy content page to scrape dfrn attributes
188 * @param string $webbie Address that should be probed
189 * @param string $hcard_url Link to the hcard - is returned by reference
191 * @return string profile link
192 * @throws HTTPException\InternalServerErrorException
194 public static function webfingerDfrn($webbie, &$hcard_url)
198 $links = self::lrdd($webbie);
199 Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA);
200 if (!empty($links) && is_array($links)) {
201 foreach ($links as $link) {
202 if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
203 $profile_link = $link['@attributes']['href'];
205 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) && ($profile_link == "")) {
206 $profile_link = 'stat:'.$link['@attributes']['template'];
208 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
209 $hcard_url = $link['@attributes']['href'];
213 return $profile_link;
217 * @brief Check an URI for LRDD data
219 * this is a replacement for the "lrdd" function.
220 * It isn't used in this class and has some redundancies in the code.
221 * When time comes we can check the existing calls for "lrdd" if we can rework them.
223 * @param string $uri Address that should be probed
225 * @return array uri data
226 * @throws HTTPException\InternalServerErrorException
228 public static function lrdd($uri)
230 $lrdd = self::hostMeta($uri);
233 if (is_bool($lrdd)) {
238 $parts = @parse_url($uri);
239 if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
243 $host = $parts["host"];
244 if (!empty($parts["port"])) {
245 $host .= ':'.$parts["port"];
248 $path_parts = explode("/", trim($parts["path"], "/"));
250 $nick = array_pop($path_parts);
253 $lrdd = self::hostMeta($host);
254 $host .= "/".array_shift($path_parts);
255 } while (!$lrdd && (sizeof($path_parts) > 0));
259 Logger::log("No lrdd data found for ".$uri, Logger::DEBUG);
263 foreach ($lrdd as $type => $template) {
268 $path = str_replace('{uri}', urlencode($uri), $template);
269 $webfinger = self::webfinger($path, $type);
271 if (!$webfinger && (strstr($uri, "@"))) {
272 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
273 $webfinger = self::webfinger($path, $type);
276 // Special treatment for Mastodon
277 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
278 // But the webfinger for this format fails.
279 if (!$webfinger && !empty($nick)) {
280 // Mastodon uses a "@" as prefix for usernames in their url format
281 $nick = ltrim($nick, '@');
283 $addr = $nick."@".$host;
285 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
286 $webfinger = self::webfinger($path, $type);
290 if (!is_array($webfinger["links"])) {
291 Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
297 foreach ($webfinger["links"] as $link) {
298 $data[] = ["@attributes" => $link];
301 if (is_array($webfinger["aliases"])) {
302 foreach ($webfinger["aliases"] as $alias) {
303 $data[] = ["@attributes" =>
313 * @brief Fetch information (protocol endpoints and user information) about a given uri
315 * @param string $uri Address that should be probed
316 * @param string $network Test for this specific network
317 * @param integer $uid User ID for the probe (only used for mails)
318 * @param boolean $cache Use cached values?
320 * @return array uri data
321 * @throws HTTPException\InternalServerErrorException
322 * @throws \ImagickException
324 public static function uri($uri, $network = '', $uid = -1, $cache = true)
327 $result = Cache::get('Probe::uri:' . $network . ':' . $uri);
328 if (!is_null($result)) {
337 self::$istimeout = false;
339 if ($network != Protocol::ACTIVITYPUB) {
340 $data = self::detect($uri, $network, $uid);
345 // When the previous detection process had got a time out
346 // we could falsely detect a Friendica profile as AP profile.
347 if (!self::$istimeout) {
348 $ap_profile = ActivityPub::probeProfile($uri);
350 if (!empty($ap_profile) && empty($network) && (defaults($data, 'network', '') != Protocol::DFRN)) {
354 Logger::notice('Time out detected. AP will not be probed.', ['uri' => $uri]);
357 if (!isset($data['url'])) {
361 if (!empty($data['photo'])) {
362 $data['baseurl'] = Network::getUrlMatch(Strings::normaliseLink(defaults($data, 'baseurl', '')), Strings::normaliseLink($data['photo']));
364 $data['photo'] = System::baseUrl() . '/images/person-300.jpg';
367 if (empty($data['name'])) {
368 if (!empty($data['nick'])) {
369 $data['name'] = $data['nick'];
372 if (empty($data['name'])) {
373 $data['name'] = $data['url'];
377 if (empty($data['nick'])) {
378 $data['nick'] = strtolower($data['name']);
380 if (strpos($data['nick'], ' ')) {
381 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
385 if (!empty(self::$baseurl)) {
386 $data['baseurl'] = self::$baseurl;
389 if (empty($data['network'])) {
390 $data['network'] = Protocol::PHANTOM;
393 $data = self::rearrangeData($data);
395 // Only store into the cache if the value seems to be valid
396 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
397 Cache::set('Probe::uri:' . $network . ':' . $uri, $data, Cache::DAY);
404 * @brief Checks if a profile url should be OStatus but only provides partial information
406 * @param array $webfinger Webfinger data
407 * @param string $lrdd Path template for webfinger request
408 * @param string $type type
410 * @return array fixed webfinger data
411 * @throws HTTPException\InternalServerErrorException
413 private static function fixOStatus($webfinger, $lrdd, $type)
415 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
422 foreach ($webfinger['links'] as $link) {
423 if ($link['rel'] == NAMESPACE_OSTATUSSUB) {
426 if ($link['rel'] == 'magic-public-key') {
431 if (!$is_ostatus || $has_key) {
435 $url = Network::switchScheme($webfinger['subject']);
436 $path = str_replace('{uri}', urlencode($url), $lrdd);
437 $webfinger2 = self::webfinger($path, $type);
439 // Is the new webfinger detectable as OStatus?
440 if (self::ostatus($webfinger2, true)) {
441 $webfinger = $webfinger2;
448 * @brief Fetch information (protocol endpoints and user information) about a given uri
450 * This function is only called by the "uri" function that adds caching and rearranging of data.
452 * @param string $uri Address that should be probed
453 * @param string $network Test for this specific network
454 * @param integer $uid User ID for the probe (only used for mails)
456 * @return array uri data
457 * @throws HTTPException\InternalServerErrorException
459 private static function detect($uri, $network, $uid)
461 $parts = parse_url($uri);
463 if (!empty($parts["scheme"]) && !empty($parts["host"])) {
464 $host = $parts["host"];
465 if (!empty($parts["port"])) {
466 $host .= ':'.$parts["port"];
469 if ($host == 'twitter.com') {
470 return ["network" => Protocol::TWITTER];
472 $lrdd = self::hostMeta($host);
474 if (is_bool($lrdd)) {
478 $path_parts = explode("/", trim(defaults($parts, 'path', ''), "/"));
480 while (!$lrdd && (sizeof($path_parts) > 1)) {
481 $host .= "/".array_shift($path_parts);
482 $lrdd = self::hostMeta($host);
485 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
486 return self::feed($uri);
488 $nick = array_pop($path_parts);
490 // Mastodon uses a "@" as prefix for usernames in their url format
491 $nick = ltrim($nick, '@');
493 $addr = $nick."@".$host;
494 } elseif (strstr($uri, '@')) {
495 // If the URI starts with "mailto:" then jump directly to the mail detection
496 if (strpos($uri, 'mailto:') !== false) {
497 $uri = str_replace('mailto:', '', $uri);
498 return self::mail($uri, $uid);
501 if ($network == Protocol::MAIL) {
502 return self::mail($uri, $uid);
504 // Remove "acct:" from the URI
505 $uri = str_replace('acct:', '', $uri);
507 $host = substr($uri, strpos($uri, '@') + 1);
508 $nick = substr($uri, 0, strpos($uri, '@'));
510 if (strpos($uri, '@twitter.com')) {
511 return ["network" => Protocol::TWITTER];
513 $lrdd = self::hostMeta($host);
515 if (is_bool($lrdd)) {
520 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
521 return self::mail($uri, $uid);
525 Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
531 /// @todo Do we need the prefix "acct:" or "acct://"?
533 foreach ($lrdd as $type => $template) {
538 // At first try it with the given uri
539 $path = str_replace('{uri}', urlencode($uri), $template);
540 $webfinger = self::webfinger($path, $type);
542 // Fix possible problems with GNU Social probing to wrong scheme
543 $webfinger = self::fixOStatus($webfinger, $template, $type);
545 // We cannot be sure that the detected address was correct, so we don't use the values
546 if ($webfinger && ($uri != $addr)) {
551 // Try webfinger with the address (user@domain.tld)
553 $path = str_replace('{uri}', urlencode($addr), $template);
554 $webfinger = self::webfinger($path, $type);
557 // Mastodon needs to have it with "acct:"
559 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
560 $webfinger = self::webfinger($path, $type);
565 return self::feed($uri);
570 Logger::log("Probing ".$uri, Logger::DEBUG);
572 if (in_array($network, ["", Protocol::DFRN])) {
573 $result = self::dfrn($webfinger);
575 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
576 $result = self::diaspora($webfinger);
578 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
579 $result = self::ostatus($webfinger);
581 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
582 $result = self::pumpio($webfinger, $addr);
584 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
585 $result = self::feed($uri);
587 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
588 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
589 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
590 $result["nick"] = $nick;
593 if (empty($result["addr"]) && ($addr != "")) {
594 $result["addr"] = $addr;
598 if (empty($result["network"])) {
599 $result["network"] = Protocol::PHANTOM;
602 if (empty($result["url"])) {
603 $result["url"] = $uri;
606 Logger::log($uri." is ".$result["network"], Logger::DEBUG);
608 if (empty($result["baseurl"])) {
609 $pos = strpos($result["url"], $host);
611 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
618 * @brief Perform a webfinger request.
620 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
622 * @param string $url Address that should be probed
623 * @param string $type type
625 * @return array webfinger data
626 * @throws HTTPException\InternalServerErrorException
628 private static function webfinger($url, $type)
630 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
632 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
633 if ($curlResult->isTimeout()) {
634 self::$istimeout = true;
637 $data = $curlResult->getBody();
639 $webfinger = json_decode($data, true);
640 if (is_array($webfinger)) {
641 if (!isset($webfinger["links"])) {
642 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
648 // If it is not JSON, maybe it is XML
649 $xrd = XML::parseString($data, false);
650 if (!is_object($xrd)) {
651 Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
655 $xrd_arr = XML::elementToArray($xrd);
656 if (!isset($xrd_arr["xrd"]["link"])) {
657 Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
663 if (!empty($xrd_arr["xrd"]["subject"])) {
664 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
667 if (!empty($xrd_arr["xrd"]["alias"])) {
668 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
671 $webfinger["links"] = [];
673 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
674 if (!empty($data["@attributes"])) {
675 $attributes = $data["@attributes"];
676 } elseif ($value == "@attributes") {
682 $webfinger["links"][] = $attributes;
688 * @brief Poll the Friendica specific noscrape page.
690 * "noscrape" is a faster alternative to fetch the data from the hcard.
691 * This functionality was originally created for the directory.
693 * @param string $noscrape_url Link to the noscrape page
694 * @param array $data The already fetched data
696 * @return array noscrape data
697 * @throws HTTPException\InternalServerErrorException
699 private static function pollNoscrape($noscrape_url, $data)
701 $curlResult = Network::curl($noscrape_url);
702 if ($curlResult->isTimeout()) {
703 self::$istimeout = true;
706 $content = $curlResult->getBody();
708 Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
712 $json = json_decode($content, true);
713 if (!is_array($json)) {
714 Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
718 if (!empty($json["fn"])) {
719 $data["name"] = $json["fn"];
722 if (!empty($json["addr"])) {
723 $data["addr"] = $json["addr"];
726 if (!empty($json["nick"])) {
727 $data["nick"] = $json["nick"];
730 if (!empty($json["guid"])) {
731 $data["guid"] = $json["guid"];
734 if (!empty($json["comm"])) {
735 $data["community"] = $json["comm"];
738 if (!empty($json["tags"])) {
739 $keywords = implode(" ", $json["tags"]);
740 if ($keywords != "") {
741 $data["keywords"] = $keywords;
745 $location = Profile::formatLocation($json);
747 $data["location"] = $location;
750 if (!empty($json["about"])) {
751 $data["about"] = $json["about"];
754 if (!empty($json["key"])) {
755 $data["pubkey"] = $json["key"];
758 if (!empty($json["photo"])) {
759 $data["photo"] = $json["photo"];
762 if (!empty($json["dfrn-request"])) {
763 $data["request"] = $json["dfrn-request"];
766 if (!empty($json["dfrn-confirm"])) {
767 $data["confirm"] = $json["dfrn-confirm"];
770 if (!empty($json["dfrn-notify"])) {
771 $data["notify"] = $json["dfrn-notify"];
774 if (!empty($json["dfrn-poll"])) {
775 $data["poll"] = $json["dfrn-poll"];
782 * @brief Check for valid DFRN data
784 * @param array $data DFRN data
786 * @return int Number of errors
788 public static function validDfrn($data)
791 if (!isset($data['key'])) {
794 if (!isset($data['dfrn-request'])) {
797 if (!isset($data['dfrn-confirm'])) {
800 if (!isset($data['dfrn-notify'])) {
803 if (!isset($data['dfrn-poll'])) {
810 * @brief Fetch data from a DFRN profile page and via "noscrape"
812 * @param string $profile_link Link to the profile page
814 * @return array profile data
815 * @throws HTTPException\InternalServerErrorException
816 * @throws \ImagickException
818 public static function profile($profile_link)
822 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
824 // Fetch data via noscrape - this is faster
825 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
826 $data = self::pollNoscrape($noscrape_url, $data);
828 if (!isset($data["notify"])
829 || !isset($data["confirm"])
830 || !isset($data["request"])
831 || !isset($data["poll"])
832 || !isset($data["name"])
833 || !isset($data["photo"])
835 $data = self::pollHcard($profile_link, $data, true);
840 if (empty($data["addr"]) || empty($data["nick"])) {
841 $probe_data = self::uri($profile_link);
842 $data["addr"] = defaults($data, "addr", $probe_data["addr"]);
843 $data["nick"] = defaults($data, "nick", $probe_data["nick"]);
846 $prof_data["addr"] = $data["addr"];
847 $prof_data["nick"] = $data["nick"];
848 $prof_data["dfrn-request"] = defaults($data, 'request', null);
849 $prof_data["dfrn-confirm"] = defaults($data, 'confirm', null);
850 $prof_data["dfrn-notify"] = defaults($data, 'notify' , null);
851 $prof_data["dfrn-poll"] = defaults($data, 'poll' , null);
852 $prof_data["photo"] = defaults($data, 'photo' , null);
853 $prof_data["fn"] = defaults($data, 'name' , null);
854 $prof_data["key"] = defaults($data, 'pubkey' , null);
856 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
862 * @brief Check for DFRN contact
864 * @param array $webfinger Webfinger data
866 * @return array DFRN data
867 * @throws HTTPException\InternalServerErrorException
869 private static function dfrn($webfinger)
873 // The array is reversed to take into account the order of preference for same-rel links
874 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
875 foreach (array_reverse($webfinger["links"]) as $link) {
876 if (($link["rel"] == NAMESPACE_DFRN) && !empty($link["href"])) {
877 $data["network"] = Protocol::DFRN;
878 } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
879 $data["poll"] = $link["href"];
880 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (defaults($link, "type", "") == "text/html") && !empty($link["href"])) {
881 $data["url"] = $link["href"];
882 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
883 $hcard_url = $link["href"];
884 } elseif (($link["rel"] == NAMESPACE_POCO) && !empty($link["href"])) {
885 $data["poco"] = $link["href"];
886 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
887 $data["photo"] = $link["href"];
888 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
889 $data["baseurl"] = trim($link["href"], '/');
890 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
891 $data["guid"] = $link["href"];
892 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
893 $data["pubkey"] = base64_decode($link["href"]);
895 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
896 if (strstr($data["pubkey"], 'RSA ')) {
897 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
902 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
903 foreach ($webfinger["aliases"] as $alias) {
904 if (empty($data["url"]) && !strstr($alias, "@")) {
905 $data["url"] = $alias;
906 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
907 $data["alias"] = $alias;
908 } elseif (substr($alias, 0, 5) == 'acct:') {
909 $data["addr"] = substr($alias, 5);
914 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
915 $data["addr"] = substr($webfinger["subject"], 5);
918 if (!isset($data["network"]) || ($hcard_url == "")) {
922 // Fetch data via noscrape - this is faster
923 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
924 $data = self::pollNoscrape($noscrape_url, $data);
926 if (isset($data["notify"])
927 && isset($data["confirm"])
928 && isset($data["request"])
929 && isset($data["poll"])
930 && isset($data["name"])
931 && isset($data["photo"])
936 $data = self::pollHcard($hcard_url, $data, true);
942 * @brief Poll the hcard page (Diaspora and Friendica specific)
944 * @param string $hcard_url Link to the hcard page
945 * @param array $data The already fetched data
946 * @param boolean $dfrn Poll DFRN specific data
948 * @return array hcard data
949 * @throws HTTPException\InternalServerErrorException
951 private static function pollHcard($hcard_url, $data, $dfrn = false)
953 $curlResult = Network::curl($hcard_url);
954 if ($curlResult->isTimeout()) {
955 self::$istimeout = true;
958 $content = $curlResult->getBody();
963 $doc = new DOMDocument();
964 if (!@$doc->loadHTML($content)) {
968 $xpath = new DomXPath($doc);
970 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
971 if (!is_object($vcards)) {
975 if (!isset($data["baseurl"])) {
976 $data["baseurl"] = "";
979 if ($vcards->length > 0) {
980 $vcard = $vcards->item(0);
982 // We have to discard the guid from the hcard in favour of the guid from lrdd
983 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
984 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
985 if (($search->length > 0) && empty($data["guid"])) {
986 $data["guid"] = $search->item(0)->nodeValue;
989 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
990 if ($search->length > 0) {
991 $data["nick"] = $search->item(0)->nodeValue;
994 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
995 if ($search->length > 0) {
996 $data["name"] = $search->item(0)->nodeValue;
999 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1000 if ($search->length > 0) {
1001 $data["searchable"] = $search->item(0)->nodeValue;
1004 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1005 if ($search->length > 0) {
1006 $data["pubkey"] = $search->item(0)->nodeValue;
1007 if (strstr($data["pubkey"], 'RSA ')) {
1008 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1012 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1013 if ($search->length > 0) {
1014 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1019 if (!empty($vcard)) {
1020 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1021 foreach ($photos as $photo) {
1023 foreach ($photo->attributes as $attribute) {
1024 $attr[$attribute->name] = trim($attribute->value);
1027 if (isset($attr["src"]) && isset($attr["width"])) {
1028 $avatar[$attr["width"]] = $attr["src"];
1031 // We don't have a width. So we just take everything that we got.
1032 // This is a Hubzilla workaround which doesn't send a width.
1033 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1034 $avatar[] = $attr["src"];
1039 if (sizeof($avatar)) {
1041 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1045 // Poll DFRN specific data
1046 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1047 if ($search->length > 0) {
1048 foreach ($search as $link) {
1049 //$data["request"] = $search->item(0)->nodeValue;
1051 foreach ($link->attributes as $attribute) {
1052 $attr[$attribute->name] = trim($attribute->value);
1055 $data[substr($attr["rel"], 5)] = $attr["href"];
1059 // Older Friendica versions had used the "uid" field differently than newer versions
1060 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1061 unset($data["guid"]);
1070 * @brief Check for Diaspora contact
1072 * @param array $webfinger Webfinger data
1074 * @return array Diaspora data
1075 * @throws HTTPException\InternalServerErrorException
1077 private static function diaspora($webfinger)
1081 // The array is reversed to take into account the order of preference for same-rel links
1082 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1083 foreach (array_reverse($webfinger["links"]) as $link) {
1084 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1085 $hcard_url = $link["href"];
1086 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1087 $data["baseurl"] = trim($link["href"], '/');
1088 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1089 $data["guid"] = $link["href"];
1090 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (defaults($link, "type", "") == "text/html") && !empty($link["href"])) {
1091 $data["url"] = $link["href"];
1092 } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
1093 $data["poll"] = $link["href"];
1094 } elseif (($link["rel"] == NAMESPACE_POCO) && !empty($link["href"])) {
1095 $data["poco"] = $link["href"];
1096 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1097 $data["notify"] = $link["href"];
1098 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1099 $data["pubkey"] = base64_decode($link["href"]);
1101 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1102 if (strstr($data["pubkey"], 'RSA ')) {
1103 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1108 if (!isset($data["url"]) || ($hcard_url == "")) {
1112 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1113 foreach ($webfinger["aliases"] as $alias) {
1114 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1115 $data["alias"] = $alias;
1116 } elseif (substr($alias, 0, 5) == 'acct:') {
1117 $data["addr"] = substr($alias, 5);
1122 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1123 $data["addr"] = substr($webfinger["subject"], 5);
1126 // Fetch further information from the hcard
1127 $data = self::pollHcard($hcard_url, $data);
1133 if (isset($data["url"])
1134 && isset($data["guid"])
1135 && isset($data["baseurl"])
1136 && isset($data["pubkey"])
1137 && ($hcard_url != "")
1139 $data["network"] = Protocol::DIASPORA;
1141 // The Diaspora handle must always be lowercase
1142 if (!empty($data["addr"])) {
1143 $data["addr"] = strtolower($data["addr"]);
1146 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1147 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1148 $data["batch"] = $data["baseurl"] . "/receive/public";
1157 * @brief Check for OStatus contact
1159 * @param array $webfinger Webfinger data
1160 * @param bool $short Short detection mode
1162 * @return array|bool OStatus data or "false" on error or "true" on short mode
1163 * @throws HTTPException\InternalServerErrorException
1165 private static function ostatus($webfinger, $short = false)
1169 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1170 foreach ($webfinger["aliases"] as $alias) {
1171 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1172 $data["addr"] = str_replace('acct:', '', $alias);
1177 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1178 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1180 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1183 if (is_array($webfinger["links"])) {
1184 // The array is reversed to take into account the order of preference for same-rel links
1185 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1186 foreach (array_reverse($webfinger["links"]) as $link) {
1187 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1188 && (defaults($link, "type", "") == "text/html")
1189 && ($link["href"] != "")
1191 $data["url"] = $link["href"];
1192 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1193 $data["notify"] = $link["href"];
1194 } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
1195 $data["poll"] = $link["href"];
1196 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1197 $pubkey = $link["href"];
1199 if (substr($pubkey, 0, 5) === 'data:') {
1200 if (strstr($pubkey, ',')) {
1201 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1203 $pubkey = substr($pubkey, 5);
1205 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1206 $curlResult = Network::curl($pubkey);
1207 if ($curlResult->isTimeout()) {
1208 self::$istimeout = true;
1211 $pubkey = $curlResult->getBody();
1214 $key = explode(".", $pubkey);
1216 if (sizeof($key) >= 3) {
1217 $m = Strings::base64UrlDecode($key[1]);
1218 $e = Strings::base64UrlDecode($key[2]);
1219 $data["pubkey"] = Crypto::meToPem($m, $e);
1225 if (isset($data["notify"]) && isset($data["pubkey"])
1226 && isset($data["poll"])
1227 && isset($data["url"])
1229 $data["network"] = Protocol::OSTATUS;
1238 // Fetch all additional data from the feed
1239 $curlResult = Network::curl($data["poll"]);
1240 if ($curlResult->isTimeout()) {
1241 self::$istimeout = true;
1244 $feed = $curlResult->getBody();
1248 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1253 if (!empty($feed_data["header"]["author-name"])) {
1254 $data["name"] = $feed_data["header"]["author-name"];
1256 if (!empty($feed_data["header"]["author-nick"])) {
1257 $data["nick"] = $feed_data["header"]["author-nick"];
1259 if (!empty($feed_data["header"]["author-avatar"])) {
1260 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1262 if (!empty($feed_data["header"]["author-id"])) {
1263 $data["alias"] = $feed_data["header"]["author-id"];
1265 if (!empty($feed_data["header"]["author-location"])) {
1266 $data["location"] = $feed_data["header"]["author-location"];
1268 if (!empty($feed_data["header"]["author-about"])) {
1269 $data["about"] = $feed_data["header"]["author-about"];
1271 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1272 // So we take the value that we just fetched, although the other one worked as well
1273 if (!empty($feed_data["header"]["author-link"])) {
1274 $data["url"] = $feed_data["header"]["author-link"];
1277 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1278 $data['url'] = $data["alias"];
1279 $data["alias"] = '';
1282 /// @todo Fetch location and "about" from the feed as well
1287 * @brief Fetch data from a pump.io profile page
1289 * @param string $profile_link Link to the profile page
1291 * @return array profile data
1293 private static function pumpioProfileData($profile_link)
1295 $doc = new DOMDocument();
1296 if (!@$doc->loadHTMLFile($profile_link)) {
1300 $xpath = new DomXPath($doc);
1304 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1306 if ($data["name"] == '') {
1307 // This is ugly - but pump.io doesn't seem to know a better way for it
1308 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1309 $pos = strpos($data["name"], chr(10));
1311 $data["name"] = trim(substr($data["name"], 0, $pos));
1315 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1317 if ($data["location"] == '') {
1318 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1321 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1323 if ($data["about"] == '') {
1324 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1327 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1329 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1332 foreach ($avatar->attributes as $attribute) {
1333 if ($attribute->name == "src") {
1334 $data["photo"] = trim($attribute->value);
1343 * @brief Check for pump.io contact
1345 * @param array $webfinger Webfinger data
1348 * @return array pump.io data
1350 private static function pumpio($webfinger, $addr)
1353 // The array is reversed to take into account the order of preference for same-rel links
1354 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1355 foreach (array_reverse($webfinger["links"]) as $link) {
1356 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1357 && (defaults($link, "type", "") == "text/html")
1358 && ($link["href"] != "")
1360 $data["url"] = $link["href"];
1361 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1362 $data["notify"] = $link["href"];
1363 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1364 $data["poll"] = $link["href"];
1365 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1366 $data["dialback"] = $link["href"];
1369 if (isset($data["poll"]) && isset($data["notify"])
1370 && isset($data["dialback"])
1371 && isset($data["url"])
1373 // by now we use these fields only for the network type detection
1374 // So we unset all data that isn't used at the moment
1375 unset($data["dialback"]);
1377 $data["network"] = Protocol::PUMPIO;
1382 $profile_data = self::pumpioProfileData($data["url"]);
1384 if (!$profile_data) {
1388 $data = array_merge($data, $profile_data);
1390 if (($addr != '') && ($data['name'] != '')) {
1391 $name = trim(str_replace($addr, '', $data['name']));
1393 $data['name'] = $name;
1401 * @brief Check page for feed link
1403 * @param string $url Page link
1405 * @return string feed link
1407 private static function getFeedLink($url)
1409 $doc = new DOMDocument();
1411 if (!@$doc->loadHTMLFile($url)) {
1415 $xpath = new DomXPath($doc);
1417 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1418 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1419 if (!is_object($feeds)) {
1423 if ($feeds->length == 0) {
1429 foreach ($feeds as $feed) {
1431 foreach ($feed->attributes as $attribute) {
1432 $attr[$attribute->name] = trim($attribute->value);
1435 if ($feed_url == "") {
1436 $feed_url = $attr["href"];
1444 * @brief Check for feed contact
1446 * @param string $url Profile link
1447 * @param boolean $probe Do a probe if the page contains a feed link
1449 * @return array feed data
1450 * @throws HTTPException\InternalServerErrorException
1452 private static function feed($url, $probe = true)
1454 $curlResult = Network::curl($url);
1455 if ($curlResult->isTimeout()) {
1456 self::$istimeout = true;
1459 $feed = $curlResult->getBody();
1460 $dummy1 = $dummy2 = $dummy3 = null;
1461 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1468 $feed_url = self::getFeedLink($url);
1474 return self::feed($feed_url, false);
1477 if (!empty($feed_data["header"]["author-name"])) {
1478 $data["name"] = $feed_data["header"]["author-name"];
1481 if (!empty($feed_data["header"]["author-nick"])) {
1482 $data["nick"] = $feed_data["header"]["author-nick"];
1485 if (!empty($feed_data["header"]["author-avatar"])) {
1486 $data["photo"] = $feed_data["header"]["author-avatar"];
1489 if (!empty($feed_data["header"]["author-id"])) {
1490 $data["alias"] = $feed_data["header"]["author-id"];
1493 $data["url"] = $url;
1494 $data["poll"] = $url;
1496 if (!empty($feed_data["header"]["author-link"])) {
1497 $data["baseurl"] = $feed_data["header"]["author-link"];
1499 $data["baseurl"] = $data["url"];
1502 $data["network"] = Protocol::FEED;
1508 * @brief Check for mail contact
1510 * @param string $uri Profile link
1511 * @param integer $uid User ID
1513 * @return array mail data
1514 * @throws \Exception
1516 private static function mail($uri, $uid)
1518 if (!Network::isEmailDomainValid($uri)) {
1526 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1528 $condition = ["`uid` = ? AND `server` != ''", $uid];
1529 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1530 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1532 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1536 $mailbox = Email::constructMailboxName($mailacct);
1538 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1539 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1544 $msgs = Email::poll($mbox, $uri);
1545 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1547 if (!count($msgs)) {
1551 $phost = substr($uri, strpos($uri, '@') + 1);
1554 $data["addr"] = $uri;
1555 $data["network"] = Protocol::MAIL;
1556 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1557 $data["nick"] = $data["name"];
1558 $data["photo"] = Network::lookupAvatarByEmail($uri);
1559 $data["url"] = 'mailto:'.$uri;
1560 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1561 $data["poll"] = 'email ' . Strings::getRandomHex();
1563 $x = Email::messageMeta($mbox, $msgs[0]);
1564 if (stristr($x[0]->from, $uri)) {
1565 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1566 } elseif (stristr($x[0]->to, $uri)) {
1567 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1570 foreach ($adr as $feadr) {
1571 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1572 &&(strcasecmp($feadr->host, $phost) == 0)
1573 && (strlen($feadr->personal))
1575 $personal = imap_mime_header_decode($feadr->personal);
1577 foreach ($personal as $perspart) {
1578 if ($perspart->charset != "default") {
1579 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1581 $data["name"] .= $perspart->text;
1585 $data["name"] = Strings::escapeTags($data["name"]);
1589 if (!empty($mbox)) {
1596 * @brief Mix two paths together to possibly fix missing parts
1598 * @param string $avatar Path to the avatar
1599 * @param string $base Another path that is hopefully complete
1601 * @return string fixed avatar path
1602 * @throws \Exception
1604 public static function fixAvatar($avatar, $base)
1606 $base_parts = parse_url($base);
1608 // Remove all parts that could create a problem
1609 unset($base_parts['path']);
1610 unset($base_parts['query']);
1611 unset($base_parts['fragment']);
1613 $avatar_parts = parse_url($avatar);
1616 $parts = array_merge($base_parts, $avatar_parts);
1618 // And put them together again
1619 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1620 $host = isset($parts['host']) ? $parts['host'] : '';
1621 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1622 $path = isset($parts['path']) ? $parts['path'] : '';
1623 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1624 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1626 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1628 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);