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", "photo", "account-type",
49 "community", "keywords", "location", "about", "gender", "hide",
50 "batch", "notify", "poll", "request", "confirm", "poco",
51 "following", "followers", "inbox", "outbox", "sharedinbox",
52 "priority", "network", "pubkey", "baseurl"];
55 foreach ($fields as $field) {
56 if (isset($data[$field])) {
57 $newdata[$field] = $data[$field];
59 $newdata[$field] = "";
63 // We don't use the "priority" field anymore and replace it with a dummy.
64 $newdata["priority"] = 0;
70 * @brief Check if the hostname belongs to the own server
72 * @param string $host The hostname that is to be checked
74 * @return bool Does the testes hostname belongs to the own server?
76 private static function ownHost($host)
78 $own_host = \get_app()->getHostName();
80 $parts = parse_url($host);
82 if (!isset($parts['scheme'])) {
83 $parts = parse_url('http://'.$host);
86 if (!isset($parts['host'])) {
89 return $parts['host'] == $own_host;
93 * @brief Probes for webfinger path via "host-meta"
95 * We have to check if the servers in the future still will offer this.
96 * It seems as if it was dropped from the standard.
98 * @param string $host The host part of an url
100 * @return array with template and type of the webfinger template for JSON or XML
101 * @throws HTTPException\InternalServerErrorException
103 private static function hostMeta($host)
105 // Reset the static variable
108 $ssl_url = "https://".$host."/.well-known/host-meta";
109 $url = "http://".$host."/.well-known/host-meta";
111 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
113 Logger::log("Probing for ".$host, Logger::DEBUG);
116 $curlResult = Network::curl($ssl_url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
117 if ($curlResult->isSuccess()) {
118 $xml = $curlResult->getBody();
119 $xrd = XML::parseString($xml, false);
120 $host_url = 'https://'.$host;
123 if (!is_object($xrd)) {
124 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
125 if ($curlResult->isTimeout()) {
126 Logger::log("Probing timeout for " . $url, Logger::DEBUG);
127 self::$istimeout = true;
130 $xml = $curlResult->getBody();
131 $xrd = XML::parseString($xml, false);
132 $host_url = 'http://'.$host;
134 if (!is_object($xrd)) {
135 Logger::log("No xrd object found for ".$host, Logger::DEBUG);
139 $links = XML::elementToArray($xrd);
140 if (!isset($links["xrd"]["link"])) {
141 Logger::log("No xrd data found for ".$host, Logger::DEBUG);
146 // The following webfinger path is defined in RFC 7033 https://tools.ietf.org/html/rfc7033
147 // Problem is that Hubzilla currently doesn't provide all data in the JSON webfinger
148 // compared to the XML webfinger. So this is commented out by now.
149 // $lrdd = array("application/jrd+json" => $host_url.'/.well-known/webfinger?resource={uri}');
151 foreach ($links["xrd"]["link"] as $value => $link) {
152 if (!empty($link["@attributes"])) {
153 $attributes = $link["@attributes"];
154 } elseif ($value == "@attributes") {
160 if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
161 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
163 $lrdd[$type] = $attributes["template"];
167 self::$baseurl = $host_url;
169 Logger::log("Probing successful for ".$host, Logger::DEBUG);
175 * @brief Perform Webfinger lookup and return DFRN data
177 * Given an email style address, perform webfinger lookup and
178 * return the resulting DFRN profile URL, or if no DFRN profile URL
179 * is located, returns an OStatus subscription template (prefixed
180 * with the string 'stat:' to identify it as on OStatus template).
181 * If this isn't an email style address just return $webbie.
182 * Return an empty string if email-style addresses but webfinger fails,
183 * or if the resultant personal XRD doesn't contain a supported
184 * subscription/friend-request attribute.
186 * amended 7/9/2011 to return an hcard which could save potentially loading
187 * a lengthy content page to scrape dfrn attributes
189 * @param string $webbie Address that should be probed
190 * @param string $hcard_url Link to the hcard - is returned by reference
192 * @return string profile link
193 * @throws HTTPException\InternalServerErrorException
195 public static function webfingerDfrn($webbie, &$hcard_url)
199 $links = self::lrdd($webbie);
200 Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA);
201 if (!empty($links) && is_array($links)) {
202 foreach ($links as $link) {
203 if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
204 $profile_link = $link['@attributes']['href'];
206 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) && ($profile_link == "")) {
207 $profile_link = 'stat:'.$link['@attributes']['template'];
209 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
210 $hcard_url = $link['@attributes']['href'];
214 return $profile_link;
218 * @brief Check an URI for LRDD data
220 * this is a replacement for the "lrdd" function.
221 * It isn't used in this class and has some redundancies in the code.
222 * When time comes we can check the existing calls for "lrdd" if we can rework them.
224 * @param string $uri Address that should be probed
226 * @return array uri data
227 * @throws HTTPException\InternalServerErrorException
229 public static function lrdd($uri)
231 $lrdd = self::hostMeta($uri);
234 if (is_bool($lrdd)) {
239 $parts = @parse_url($uri);
240 if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
244 $host = $parts["host"];
245 if (!empty($parts["port"])) {
246 $host .= ':'.$parts["port"];
249 $path_parts = explode("/", trim($parts["path"], "/"));
251 $nick = array_pop($path_parts);
254 $lrdd = self::hostMeta($host);
255 $host .= "/".array_shift($path_parts);
256 } while (!$lrdd && (sizeof($path_parts) > 0));
260 Logger::log("No lrdd data found for ".$uri, Logger::DEBUG);
264 foreach ($lrdd as $type => $template) {
269 $path = str_replace('{uri}', urlencode($uri), $template);
270 $webfinger = self::webfinger($path, $type);
272 if (!$webfinger && (strstr($uri, "@"))) {
273 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
274 $webfinger = self::webfinger($path, $type);
277 // Special treatment for Mastodon
278 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
279 // But the webfinger for this format fails.
280 if (!$webfinger && !empty($nick)) {
281 // Mastodon uses a "@" as prefix for usernames in their url format
282 $nick = ltrim($nick, '@');
284 $addr = $nick."@".$host;
286 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
287 $webfinger = self::webfinger($path, $type);
291 if (!is_array($webfinger["links"])) {
292 Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
298 foreach ($webfinger["links"] as $link) {
299 $data[] = ["@attributes" => $link];
302 if (is_array($webfinger["aliases"])) {
303 foreach ($webfinger["aliases"] as $alias) {
304 $data[] = ["@attributes" =>
314 * @brief Fetch information (protocol endpoints and user information) about a given uri
316 * @param string $uri Address that should be probed
317 * @param string $network Test for this specific network
318 * @param integer $uid User ID for the probe (only used for mails)
319 * @param boolean $cache Use cached values?
321 * @return array uri data
322 * @throws HTTPException\InternalServerErrorException
323 * @throws \ImagickException
325 public static function uri($uri, $network = '', $uid = -1, $cache = true)
328 $result = Cache::get('Probe::uri:' . $network . ':' . $uri);
329 if (!is_null($result)) {
338 self::$istimeout = false;
340 if ($network != Protocol::ACTIVITYPUB) {
341 $data = self::detect($uri, $network, $uid);
346 // When the previous detection process had got a time out
347 // we could falsely detect a Friendica profile as AP profile.
348 if (!self::$istimeout) {
349 $ap_profile = ActivityPub::probeProfile($uri);
351 if (empty($data) || (!empty($ap_profile) && empty($network) && (defaults($data, 'network', '') != Protocol::DFRN))) {
353 } elseif (!empty($ap_profile)) {
354 $ap_profile['batch'] = '';
355 $data = array_merge($ap_profile, $data);
358 Logger::notice('Time out detected. AP will not be probed.', ['uri' => $uri]);
361 if (!isset($data['url'])) {
365 if (!empty($data['photo'])) {
366 $data['baseurl'] = Network::getUrlMatch(Strings::normaliseLink(defaults($data, 'baseurl', '')), Strings::normaliseLink($data['photo']));
368 $data['photo'] = System::baseUrl() . '/images/person-300.jpg';
371 if (empty($data['name'])) {
372 if (!empty($data['nick'])) {
373 $data['name'] = $data['nick'];
376 if (empty($data['name'])) {
377 $data['name'] = $data['url'];
381 if (empty($data['nick'])) {
382 $data['nick'] = strtolower($data['name']);
384 if (strpos($data['nick'], ' ')) {
385 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
389 if (!empty(self::$baseurl)) {
390 $data['baseurl'] = self::$baseurl;
393 if (empty($data['network'])) {
394 $data['network'] = Protocol::PHANTOM;
397 $data = self::rearrangeData($data);
399 // Only store into the cache if the value seems to be valid
400 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
401 Cache::set('Probe::uri:' . $network . ':' . $uri, $data, Cache::DAY);
408 * @brief Checks if a profile url should be OStatus but only provides partial information
410 * @param array $webfinger Webfinger data
411 * @param string $lrdd Path template for webfinger request
412 * @param string $type type
414 * @return array fixed webfinger data
415 * @throws HTTPException\InternalServerErrorException
417 private static function fixOStatus($webfinger, $lrdd, $type)
419 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
426 foreach ($webfinger['links'] as $link) {
427 if ($link['rel'] == NAMESPACE_OSTATUSSUB) {
430 if ($link['rel'] == 'magic-public-key') {
435 if (!$is_ostatus || $has_key) {
439 $url = Network::switchScheme($webfinger['subject']);
440 $path = str_replace('{uri}', urlencode($url), $lrdd);
441 $webfinger2 = self::webfinger($path, $type);
443 // Is the new webfinger detectable as OStatus?
444 if (self::ostatus($webfinger2, true)) {
445 $webfinger = $webfinger2;
452 * @brief Fetch information (protocol endpoints and user information) about a given uri
454 * This function is only called by the "uri" function that adds caching and rearranging of data.
456 * @param string $uri Address that should be probed
457 * @param string $network Test for this specific network
458 * @param integer $uid User ID for the probe (only used for mails)
460 * @return array uri data
461 * @throws HTTPException\InternalServerErrorException
463 private static function detect($uri, $network, $uid)
465 $parts = parse_url($uri);
467 if (!empty($parts["scheme"]) && !empty($parts["host"])) {
468 $host = $parts["host"];
469 if (!empty($parts["port"])) {
470 $host .= ':'.$parts["port"];
473 if ($host == 'twitter.com') {
474 return self::twitter($uri);
476 $lrdd = self::hostMeta($host);
478 if (is_bool($lrdd)) {
482 $path_parts = explode("/", trim(defaults($parts, 'path', ''), "/"));
484 while (!$lrdd && (sizeof($path_parts) > 1)) {
485 $host .= "/".array_shift($path_parts);
486 $lrdd = self::hostMeta($host);
489 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
490 return self::feed($uri);
492 $nick = array_pop($path_parts);
494 // Mastodon uses a "@" as prefix for usernames in their url format
495 $nick = ltrim($nick, '@');
497 $addr = $nick."@".$host;
498 } elseif (strstr($uri, '@')) {
499 // If the URI starts with "mailto:" then jump directly to the mail detection
500 if (strpos($uri, 'mailto:') !== false) {
501 $uri = str_replace('mailto:', '', $uri);
502 return self::mail($uri, $uid);
505 if ($network == Protocol::MAIL) {
506 return self::mail($uri, $uid);
508 // Remove "acct:" from the URI
509 $uri = str_replace('acct:', '', $uri);
511 $host = substr($uri, strpos($uri, '@') + 1);
512 $nick = substr($uri, 0, strpos($uri, '@'));
514 if (strpos($uri, '@twitter.com')) {
515 return self::twitter($uri);
517 $lrdd = self::hostMeta($host);
519 if (is_bool($lrdd)) {
524 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
525 return self::mail($uri, $uid);
529 Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
535 /// @todo Do we need the prefix "acct:" or "acct://"?
537 foreach ($lrdd as $type => $template) {
542 // At first try it with the given uri
543 $path = str_replace('{uri}', urlencode($uri), $template);
544 $webfinger = self::webfinger($path, $type);
546 // Fix possible problems with GNU Social probing to wrong scheme
547 $webfinger = self::fixOStatus($webfinger, $template, $type);
549 // We cannot be sure that the detected address was correct, so we don't use the values
550 if ($webfinger && ($uri != $addr)) {
555 // Try webfinger with the address (user@domain.tld)
557 $path = str_replace('{uri}', urlencode($addr), $template);
558 $webfinger = self::webfinger($path, $type);
561 // Mastodon needs to have it with "acct:"
563 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
564 $webfinger = self::webfinger($path, $type);
569 return self::feed($uri);
574 Logger::log("Probing ".$uri, Logger::DEBUG);
576 if (in_array($network, ["", Protocol::DFRN])) {
577 $result = self::dfrn($webfinger);
579 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
580 $result = self::diaspora($webfinger);
582 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
583 $result = self::ostatus($webfinger);
585 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
586 $result = self::pumpio($webfinger, $addr);
588 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
589 $result = self::feed($uri);
591 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
592 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
593 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
594 $result["nick"] = $nick;
597 if (empty($result["addr"]) && ($addr != "")) {
598 $result["addr"] = $addr;
602 if (empty($result["network"])) {
603 $result["network"] = Protocol::PHANTOM;
606 if (empty($result["url"])) {
607 $result["url"] = $uri;
610 Logger::log($uri." is ".$result["network"], Logger::DEBUG);
612 if (empty($result["baseurl"])) {
613 $pos = strpos($result["url"], $host);
615 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
622 * @brief Perform a webfinger request.
624 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
626 * @param string $url Address that should be probed
627 * @param string $type type
629 * @return array webfinger data
630 * @throws HTTPException\InternalServerErrorException
632 private static function webfinger($url, $type)
634 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
636 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
637 if ($curlResult->isTimeout()) {
638 self::$istimeout = true;
641 $data = $curlResult->getBody();
643 $webfinger = json_decode($data, true);
644 if (is_array($webfinger)) {
645 if (!isset($webfinger["links"])) {
646 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
652 // If it is not JSON, maybe it is XML
653 $xrd = XML::parseString($data, false);
654 if (!is_object($xrd)) {
655 Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
659 $xrd_arr = XML::elementToArray($xrd);
660 if (!isset($xrd_arr["xrd"]["link"])) {
661 Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
667 if (!empty($xrd_arr["xrd"]["subject"])) {
668 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
671 if (!empty($xrd_arr["xrd"]["alias"])) {
672 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
675 $webfinger["links"] = [];
677 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
678 if (!empty($data["@attributes"])) {
679 $attributes = $data["@attributes"];
680 } elseif ($value == "@attributes") {
686 $webfinger["links"][] = $attributes;
692 * @brief Poll the Friendica specific noscrape page.
694 * "noscrape" is a faster alternative to fetch the data from the hcard.
695 * This functionality was originally created for the directory.
697 * @param string $noscrape_url Link to the noscrape page
698 * @param array $data The already fetched data
700 * @return array noscrape data
701 * @throws HTTPException\InternalServerErrorException
703 private static function pollNoscrape($noscrape_url, $data)
705 $curlResult = Network::curl($noscrape_url);
706 if ($curlResult->isTimeout()) {
707 self::$istimeout = true;
710 $content = $curlResult->getBody();
712 Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
716 $json = json_decode($content, true);
717 if (!is_array($json)) {
718 Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
722 if (!empty($json["fn"])) {
723 $data["name"] = $json["fn"];
726 if (!empty($json["addr"])) {
727 $data["addr"] = $json["addr"];
730 if (!empty($json["nick"])) {
731 $data["nick"] = $json["nick"];
734 if (!empty($json["guid"])) {
735 $data["guid"] = $json["guid"];
738 if (!empty($json["comm"])) {
739 $data["community"] = $json["comm"];
742 if (!empty($json["tags"])) {
743 $keywords = implode(", ", $json["tags"]);
744 if ($keywords != "") {
745 $data["keywords"] = $keywords;
749 $location = Profile::formatLocation($json);
751 $data["location"] = $location;
754 if (!empty($json["about"])) {
755 $data["about"] = $json["about"];
758 if (!empty($json["gender"])) {
759 $data["gender"] = $json["gender"];
762 if (!empty($json["key"])) {
763 $data["pubkey"] = $json["key"];
766 if (!empty($json["photo"])) {
767 $data["photo"] = $json["photo"];
770 if (!empty($json["dfrn-request"])) {
771 $data["request"] = $json["dfrn-request"];
774 if (!empty($json["dfrn-confirm"])) {
775 $data["confirm"] = $json["dfrn-confirm"];
778 if (!empty($json["dfrn-notify"])) {
779 $data["notify"] = $json["dfrn-notify"];
782 if (!empty($json["dfrn-poll"])) {
783 $data["poll"] = $json["dfrn-poll"];
786 if (isset($json["hide"])) {
787 $data["hide"] = (bool)$json["hide"];
789 $data["hide"] = false;
796 * @brief Check for valid DFRN data
798 * @param array $data DFRN data
800 * @return int Number of errors
802 public static function validDfrn($data)
805 if (!isset($data['key'])) {
808 if (!isset($data['dfrn-request'])) {
811 if (!isset($data['dfrn-confirm'])) {
814 if (!isset($data['dfrn-notify'])) {
817 if (!isset($data['dfrn-poll'])) {
824 * @brief Fetch data from a DFRN profile page and via "noscrape"
826 * @param string $profile_link Link to the profile page
828 * @return array profile data
829 * @throws HTTPException\InternalServerErrorException
830 * @throws \ImagickException
832 public static function profile($profile_link)
836 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
838 // Fetch data via noscrape - this is faster
839 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
840 $data = self::pollNoscrape($noscrape_url, $data);
842 if (!isset($data["notify"])
843 || !isset($data["confirm"])
844 || !isset($data["request"])
845 || !isset($data["poll"])
846 || !isset($data["name"])
847 || !isset($data["photo"])
849 $data = self::pollHcard($profile_link, $data, true);
854 if (empty($data["addr"]) || empty($data["nick"])) {
855 $probe_data = self::uri($profile_link);
856 $data["addr"] = defaults($data, "addr", $probe_data["addr"]);
857 $data["nick"] = defaults($data, "nick", $probe_data["nick"]);
860 $prof_data["addr"] = $data["addr"];
861 $prof_data["nick"] = $data["nick"];
862 $prof_data["dfrn-request"] = defaults($data, 'request', null);
863 $prof_data["dfrn-confirm"] = defaults($data, 'confirm', null);
864 $prof_data["dfrn-notify"] = defaults($data, 'notify' , null);
865 $prof_data["dfrn-poll"] = defaults($data, 'poll' , null);
866 $prof_data["photo"] = defaults($data, 'photo' , null);
867 $prof_data["fn"] = defaults($data, 'name' , null);
868 $prof_data["key"] = defaults($data, 'pubkey' , null);
870 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
876 * @brief Check for DFRN contact
878 * @param array $webfinger Webfinger data
880 * @return array DFRN data
881 * @throws HTTPException\InternalServerErrorException
883 private static function dfrn($webfinger)
887 // The array is reversed to take into account the order of preference for same-rel links
888 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
889 foreach (array_reverse($webfinger["links"]) as $link) {
890 if (($link["rel"] == NAMESPACE_DFRN) && !empty($link["href"])) {
891 $data["network"] = Protocol::DFRN;
892 } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
893 $data["poll"] = $link["href"];
894 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (defaults($link, "type", "") == "text/html") && !empty($link["href"])) {
895 $data["url"] = $link["href"];
896 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
897 $hcard_url = $link["href"];
898 } elseif (($link["rel"] == NAMESPACE_POCO) && !empty($link["href"])) {
899 $data["poco"] = $link["href"];
900 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
901 $data["photo"] = $link["href"];
902 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
903 $data["baseurl"] = trim($link["href"], '/');
904 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
905 $data["guid"] = $link["href"];
906 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
907 $data["pubkey"] = base64_decode($link["href"]);
909 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
910 if (strstr($data["pubkey"], 'RSA ')) {
911 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
916 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
917 foreach ($webfinger["aliases"] as $alias) {
918 if (empty($data["url"]) && !strstr($alias, "@")) {
919 $data["url"] = $alias;
920 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
921 $data["alias"] = $alias;
922 } elseif (substr($alias, 0, 5) == 'acct:') {
923 $data["addr"] = substr($alias, 5);
928 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
929 $data["addr"] = substr($webfinger["subject"], 5);
932 if (!isset($data["network"]) || ($hcard_url == "")) {
936 // Fetch data via noscrape - this is faster
937 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
938 $data = self::pollNoscrape($noscrape_url, $data);
940 if (isset($data["notify"])
941 && isset($data["confirm"])
942 && isset($data["request"])
943 && isset($data["poll"])
944 && isset($data["name"])
945 && isset($data["photo"])
950 $data = self::pollHcard($hcard_url, $data, true);
956 * @brief Poll the hcard page (Diaspora and Friendica specific)
958 * @param string $hcard_url Link to the hcard page
959 * @param array $data The already fetched data
960 * @param boolean $dfrn Poll DFRN specific data
962 * @return array hcard data
963 * @throws HTTPException\InternalServerErrorException
965 private static function pollHcard($hcard_url, $data, $dfrn = false)
967 $curlResult = Network::curl($hcard_url);
968 if ($curlResult->isTimeout()) {
969 self::$istimeout = true;
972 $content = $curlResult->getBody();
977 $doc = new DOMDocument();
978 if (!@$doc->loadHTML($content)) {
982 $xpath = new DomXPath($doc);
984 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
985 if (!is_object($vcards)) {
989 if (!isset($data["baseurl"])) {
990 $data["baseurl"] = "";
993 if ($vcards->length > 0) {
994 $vcard = $vcards->item(0);
996 // We have to discard the guid from the hcard in favour of the guid from lrdd
997 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
998 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
999 if (($search->length > 0) && empty($data["guid"])) {
1000 $data["guid"] = $search->item(0)->nodeValue;
1003 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1004 if ($search->length > 0) {
1005 $data["nick"] = $search->item(0)->nodeValue;
1008 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1009 if ($search->length > 0) {
1010 $data["name"] = $search->item(0)->nodeValue;
1013 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1014 if ($search->length > 0) {
1015 $data["searchable"] = $search->item(0)->nodeValue;
1018 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1019 if ($search->length > 0) {
1020 $data["pubkey"] = $search->item(0)->nodeValue;
1021 if (strstr($data["pubkey"], 'RSA ')) {
1022 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1026 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1027 if ($search->length > 0) {
1028 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1033 if (!empty($vcard)) {
1034 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1035 foreach ($photos as $photo) {
1037 foreach ($photo->attributes as $attribute) {
1038 $attr[$attribute->name] = trim($attribute->value);
1041 if (isset($attr["src"]) && isset($attr["width"])) {
1042 $avatar[$attr["width"]] = $attr["src"];
1045 // We don't have a width. So we just take everything that we got.
1046 // This is a Hubzilla workaround which doesn't send a width.
1047 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1048 $avatar[] = $attr["src"];
1053 if (sizeof($avatar)) {
1055 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1059 // Poll DFRN specific data
1060 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1061 if ($search->length > 0) {
1062 foreach ($search as $link) {
1063 //$data["request"] = $search->item(0)->nodeValue;
1065 foreach ($link->attributes as $attribute) {
1066 $attr[$attribute->name] = trim($attribute->value);
1069 $data[substr($attr["rel"], 5)] = $attr["href"];
1073 // Older Friendica versions had used the "uid" field differently than newer versions
1074 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1075 unset($data["guid"]);
1084 * @brief Check for Diaspora contact
1086 * @param array $webfinger Webfinger data
1088 * @return array Diaspora data
1089 * @throws HTTPException\InternalServerErrorException
1091 private static function diaspora($webfinger)
1095 // The array is reversed to take into account the order of preference for same-rel links
1096 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1097 foreach (array_reverse($webfinger["links"]) as $link) {
1098 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1099 $hcard_url = $link["href"];
1100 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1101 $data["baseurl"] = trim($link["href"], '/');
1102 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1103 $data["guid"] = $link["href"];
1104 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (defaults($link, "type", "") == "text/html") && !empty($link["href"])) {
1105 $data["url"] = $link["href"];
1106 } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
1107 $data["poll"] = $link["href"];
1108 } elseif (($link["rel"] == NAMESPACE_POCO) && !empty($link["href"])) {
1109 $data["poco"] = $link["href"];
1110 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1111 $data["notify"] = $link["href"];
1112 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1113 $data["pubkey"] = base64_decode($link["href"]);
1115 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1116 if (strstr($data["pubkey"], 'RSA ')) {
1117 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1122 if (!isset($data["url"]) || ($hcard_url == "")) {
1126 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1127 foreach ($webfinger["aliases"] as $alias) {
1128 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1129 $data["alias"] = $alias;
1130 } elseif (substr($alias, 0, 5) == 'acct:') {
1131 $data["addr"] = substr($alias, 5);
1136 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1137 $data["addr"] = substr($webfinger["subject"], 5);
1140 // Fetch further information from the hcard
1141 $data = self::pollHcard($hcard_url, $data);
1147 if (isset($data["url"])
1148 && isset($data["guid"])
1149 && isset($data["baseurl"])
1150 && isset($data["pubkey"])
1151 && ($hcard_url != "")
1153 $data["network"] = Protocol::DIASPORA;
1155 // The Diaspora handle must always be lowercase
1156 if (!empty($data["addr"])) {
1157 $data["addr"] = strtolower($data["addr"]);
1160 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1161 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1162 $data["batch"] = $data["baseurl"] . "/receive/public";
1171 * @brief Check for OStatus contact
1173 * @param array $webfinger Webfinger data
1174 * @param bool $short Short detection mode
1176 * @return array|bool OStatus data or "false" on error or "true" on short mode
1177 * @throws HTTPException\InternalServerErrorException
1179 private static function ostatus($webfinger, $short = false)
1183 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1184 foreach ($webfinger["aliases"] as $alias) {
1185 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1186 $data["addr"] = str_replace('acct:', '', $alias);
1191 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1192 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1194 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1197 if (is_array($webfinger["links"])) {
1198 // The array is reversed to take into account the order of preference for same-rel links
1199 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1200 foreach (array_reverse($webfinger["links"]) as $link) {
1201 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1202 && (defaults($link, "type", "") == "text/html")
1203 && ($link["href"] != "")
1205 $data["url"] = $link["href"];
1206 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1207 $data["notify"] = $link["href"];
1208 } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
1209 $data["poll"] = $link["href"];
1210 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1211 $pubkey = $link["href"];
1213 if (substr($pubkey, 0, 5) === 'data:') {
1214 if (strstr($pubkey, ',')) {
1215 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1217 $pubkey = substr($pubkey, 5);
1219 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1220 $curlResult = Network::curl($pubkey);
1221 if ($curlResult->isTimeout()) {
1222 self::$istimeout = true;
1225 $pubkey = $curlResult->getBody();
1228 $key = explode(".", $pubkey);
1230 if (sizeof($key) >= 3) {
1231 $m = Strings::base64UrlDecode($key[1]);
1232 $e = Strings::base64UrlDecode($key[2]);
1233 $data["pubkey"] = Crypto::meToPem($m, $e);
1239 if (isset($data["notify"]) && isset($data["pubkey"])
1240 && isset($data["poll"])
1241 && isset($data["url"])
1243 $data["network"] = Protocol::OSTATUS;
1252 // Fetch all additional data from the feed
1253 $curlResult = Network::curl($data["poll"]);
1254 if ($curlResult->isTimeout()) {
1255 self::$istimeout = true;
1258 $feed = $curlResult->getBody();
1262 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1267 if (!empty($feed_data["header"]["author-name"])) {
1268 $data["name"] = $feed_data["header"]["author-name"];
1270 if (!empty($feed_data["header"]["author-nick"])) {
1271 $data["nick"] = $feed_data["header"]["author-nick"];
1273 if (!empty($feed_data["header"]["author-avatar"])) {
1274 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1276 if (!empty($feed_data["header"]["author-id"])) {
1277 $data["alias"] = $feed_data["header"]["author-id"];
1279 if (!empty($feed_data["header"]["author-location"])) {
1280 $data["location"] = $feed_data["header"]["author-location"];
1282 if (!empty($feed_data["header"]["author-about"])) {
1283 $data["about"] = $feed_data["header"]["author-about"];
1285 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1286 // So we take the value that we just fetched, although the other one worked as well
1287 if (!empty($feed_data["header"]["author-link"])) {
1288 $data["url"] = $feed_data["header"]["author-link"];
1291 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1292 $data['url'] = $data["alias"];
1293 $data["alias"] = '';
1296 /// @todo Fetch location and "about" from the feed as well
1301 * @brief Fetch data from a pump.io profile page
1303 * @param string $profile_link Link to the profile page
1305 * @return array profile data
1307 private static function pumpioProfileData($profile_link)
1309 $doc = new DOMDocument();
1310 if (!@$doc->loadHTMLFile($profile_link)) {
1314 $xpath = new DomXPath($doc);
1318 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1320 if ($data["name"] == '') {
1321 // This is ugly - but pump.io doesn't seem to know a better way for it
1322 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1323 $pos = strpos($data["name"], chr(10));
1325 $data["name"] = trim(substr($data["name"], 0, $pos));
1329 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1331 if ($data["location"] == '') {
1332 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1335 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1337 if ($data["about"] == '') {
1338 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1341 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1343 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1346 foreach ($avatar->attributes as $attribute) {
1347 if ($attribute->name == "src") {
1348 $data["photo"] = trim($attribute->value);
1357 * @brief Check for pump.io contact
1359 * @param array $webfinger Webfinger data
1362 * @return array pump.io data
1364 private static function pumpio($webfinger, $addr)
1367 // The array is reversed to take into account the order of preference for same-rel links
1368 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1369 foreach (array_reverse($webfinger["links"]) as $link) {
1370 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1371 && (defaults($link, "type", "") == "text/html")
1372 && ($link["href"] != "")
1374 $data["url"] = $link["href"];
1375 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1376 $data["notify"] = $link["href"];
1377 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1378 $data["poll"] = $link["href"];
1379 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1380 $data["dialback"] = $link["href"];
1383 if (isset($data["poll"]) && isset($data["notify"])
1384 && isset($data["dialback"])
1385 && isset($data["url"])
1387 // by now we use these fields only for the network type detection
1388 // So we unset all data that isn't used at the moment
1389 unset($data["dialback"]);
1391 $data["network"] = Protocol::PUMPIO;
1396 $profile_data = self::pumpioProfileData($data["url"]);
1398 if (!$profile_data) {
1402 $data = array_merge($data, $profile_data);
1404 if (($addr != '') && ($data['name'] != '')) {
1405 $name = trim(str_replace($addr, '', $data['name']));
1407 $data['name'] = $name;
1415 * @brief Check for twitter contact
1417 * @param string $uri
1419 * @return array twitter data
1421 private static function twitter($uri)
1423 if (preg_match('=(.*)@twitter.com=i', $uri, $matches)) {
1424 $nick = $matches[1];
1425 } elseif (preg_match('=https?://twitter.com/(.*)=i', $uri, $matches)) {
1426 $nick = $matches[1];
1432 $data['url'] = 'https://twitter.com/' . $nick;
1433 $data['addr'] = $nick . '@twitter.com';
1434 $data['nick'] = $data['name'] = $nick;
1435 $data['network'] = Protocol::TWITTER;
1436 $data['baseurl'] = 'https://twitter.com';
1438 $curlResult = Network::curl($data['url'], false);
1439 if ($curlResult->isSuccess()) {
1446 * @brief Check page for feed link
1448 * @param string $url Page link
1450 * @return string feed link
1452 private static function getFeedLink($url)
1454 $doc = new DOMDocument();
1456 if (!@$doc->loadHTMLFile($url)) {
1460 $xpath = new DomXPath($doc);
1462 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1463 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1464 if (!is_object($feeds)) {
1468 if ($feeds->length == 0) {
1474 foreach ($feeds as $feed) {
1476 foreach ($feed->attributes as $attribute) {
1477 $attr[$attribute->name] = trim($attribute->value);
1480 if ($feed_url == "") {
1481 $feed_url = $attr["href"];
1489 * @brief Check for feed contact
1491 * @param string $url Profile link
1492 * @param boolean $probe Do a probe if the page contains a feed link
1494 * @return array feed data
1495 * @throws HTTPException\InternalServerErrorException
1497 private static function feed($url, $probe = true)
1499 $curlResult = Network::curl($url);
1500 if ($curlResult->isTimeout()) {
1501 self::$istimeout = true;
1504 $feed = $curlResult->getBody();
1505 $dummy1 = $dummy2 = $dummy3 = null;
1506 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1513 $feed_url = self::getFeedLink($url);
1519 return self::feed($feed_url, false);
1522 if (!empty($feed_data["header"]["author-name"])) {
1523 $data["name"] = $feed_data["header"]["author-name"];
1526 if (!empty($feed_data["header"]["author-nick"])) {
1527 $data["nick"] = $feed_data["header"]["author-nick"];
1530 if (!empty($feed_data["header"]["author-avatar"])) {
1531 $data["photo"] = $feed_data["header"]["author-avatar"];
1534 if (!empty($feed_data["header"]["author-id"])) {
1535 $data["alias"] = $feed_data["header"]["author-id"];
1538 $data["url"] = $url;
1539 $data["poll"] = $url;
1541 if (!empty($feed_data["header"]["author-link"])) {
1542 $data["baseurl"] = $feed_data["header"]["author-link"];
1544 $data["baseurl"] = $data["url"];
1547 $data["network"] = Protocol::FEED;
1553 * @brief Check for mail contact
1555 * @param string $uri Profile link
1556 * @param integer $uid User ID
1558 * @return array mail data
1559 * @throws \Exception
1561 private static function mail($uri, $uid)
1563 if (!Network::isEmailDomainValid($uri)) {
1571 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1573 $condition = ["`uid` = ? AND `server` != ''", $uid];
1574 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1575 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1577 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1581 $mailbox = Email::constructMailboxName($mailacct);
1583 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1584 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1589 $msgs = Email::poll($mbox, $uri);
1590 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1592 if (!count($msgs)) {
1596 $phost = substr($uri, strpos($uri, '@') + 1);
1599 $data["addr"] = $uri;
1600 $data["network"] = Protocol::MAIL;
1601 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1602 $data["nick"] = $data["name"];
1603 $data["photo"] = Network::lookupAvatarByEmail($uri);
1604 $data["url"] = 'mailto:'.$uri;
1605 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1606 $data["poll"] = 'email ' . Strings::getRandomHex();
1608 $x = Email::messageMeta($mbox, $msgs[0]);
1609 if (stristr($x[0]->from, $uri)) {
1610 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1611 } elseif (stristr($x[0]->to, $uri)) {
1612 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1615 foreach ($adr as $feadr) {
1616 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1617 &&(strcasecmp($feadr->host, $phost) == 0)
1618 && (strlen($feadr->personal))
1620 $personal = imap_mime_header_decode($feadr->personal);
1622 foreach ($personal as $perspart) {
1623 if ($perspart->charset != "default") {
1624 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1626 $data["name"] .= $perspart->text;
1630 $data["name"] = Strings::escapeTags($data["name"]);
1634 if (!empty($mbox)) {
1641 * @brief Mix two paths together to possibly fix missing parts
1643 * @param string $avatar Path to the avatar
1644 * @param string $base Another path that is hopefully complete
1646 * @return string fixed avatar path
1647 * @throws \Exception
1649 public static function fixAvatar($avatar, $base)
1651 $base_parts = parse_url($base);
1653 // Remove all parts that could create a problem
1654 unset($base_parts['path']);
1655 unset($base_parts['query']);
1656 unset($base_parts['fragment']);
1658 $avatar_parts = parse_url($avatar);
1661 $parts = array_merge($base_parts, $avatar_parts);
1663 // And put them together again
1664 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1665 $host = isset($parts['host']) ? $parts['host'] : '';
1666 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1667 $path = isset($parts['path']) ? $parts['path'] : '';
1668 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1669 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1671 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1673 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);