3 * @file src/Network/Probe.php
5 namespace Friendica\Network;
8 * @file src/Network/Probe.php
9 * @brief Functions for probing URL
13 use Friendica\Core\System;
14 use Friendica\Core\Cache;
15 use Friendica\Core\Config;
16 use Friendica\Database\DBM;
17 use Friendica\Model\Profile;
18 use Friendica\Protocol\Email;
19 use Friendica\Protocol\Feed;
20 use Friendica\Util\Crypto;
21 use Friendica\Util\Network;
22 use Friendica\Util\XML;
28 require_once 'include/dba.php';
29 require_once 'include/network.php';
32 * @brief This class contain functions for probing URL
37 private static $baseurl;
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()->get_hostname();
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 * @param string $host The host part of an url
96 * @return array with template and type of the webfinger template for JSON or XML
98 private static function hostMeta($host)
100 // Reset the static variable
103 $ssl_url = "https://".$host."/.well-known/host-meta";
104 $url = "http://".$host."/.well-known/host-meta";
106 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
109 logger("Probing for ".$host, LOGGER_DEBUG);
111 $ret = Network::zFetchURL($ssl_url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
112 if ($ret['success']) {
114 $xrd = parse_xml_string($xml, false);
115 $host_url = 'https://'.$host;
118 if (!is_object($xrd)) {
119 $ret = Network::zFetchURL($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
120 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
121 logger("Probing timeout for ".$url, LOGGER_DEBUG);
125 $xrd = parse_xml_string($xml, false);
126 $host_url = 'http://'.$host;
128 if (!is_object($xrd)) {
129 logger("No xrd object found for ".$host, LOGGER_DEBUG);
133 $links = XML::elementToArray($xrd);
134 if (!isset($links["xrd"]["link"])) {
135 logger("No xrd data found for ".$host, LOGGER_DEBUG);
140 // The following webfinger path is defined in RFC 7033 https://tools.ietf.org/html/rfc7033
141 // Problem is that Hubzilla currently doesn't provide all data in the JSON webfinger
142 // compared to the XML webfinger. So this is commented out by now.
143 // $lrdd = array("application/jrd+json" => $host_url.'/.well-known/webfinger?resource={uri}');
145 foreach ($links["xrd"]["link"] as $value => $link) {
146 if (!empty($link["@attributes"])) {
147 $attributes = $link["@attributes"];
148 } elseif ($value == "@attributes") {
154 if (($attributes["rel"] == "lrdd") && !empty($attributes["template"])) {
155 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
157 $lrdd[$type] = $attributes["template"];
161 self::$baseurl = "http://".$host;
163 logger("Probing successful for ".$host, LOGGER_DEBUG);
169 * @brief Perform Webfinger lookup and return DFRN data
171 * Given an email style address, perform webfinger lookup and
172 * return the resulting DFRN profile URL, or if no DFRN profile URL
173 * is located, returns an OStatus subscription template (prefixed
174 * with the string 'stat:' to identify it as on OStatus template).
175 * If this isn't an email style address just return $webbie.
176 * Return an empty string if email-style addresses but webfinger fails,
177 * or if the resultant personal XRD doesn't contain a supported
178 * subscription/friend-request attribute.
180 * amended 7/9/2011 to return an hcard which could save potentially loading
181 * a lengthy content page to scrape dfrn attributes
183 * @param string $webbie Address that should be probed
184 * @param string $hcard_url Link to the hcard - is returned by reference
186 * @return string profile link
188 public static function webfingerDfrn($webbie, &$hcard_url)
192 $links = self::lrdd($webbie);
193 logger('webfingerDfrn: '.$webbie.':'.print_r($links, true), LOGGER_DATA);
195 foreach ($links as $link) {
196 if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
197 $profile_link = $link['@attributes']['href'];
199 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) && ($profile_link == "")) {
200 $profile_link = 'stat:'.$link['@attributes']['template'];
202 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
203 $hcard_url = $link['@attributes']['href'];
207 return $profile_link;
211 * @brief Check an URI for LRDD data
213 * this is a replacement for the "lrdd" function in include/network.php.
214 * It isn't used in this class and has some redundancies in the code.
215 * When time comes we can check the existing calls for "lrdd" if we can rework them.
217 * @param string $uri Address that should be probed
219 * @return array uri data
221 public static function lrdd($uri)
223 $lrdd = self::hostMeta($uri);
226 if (is_bool($lrdd)) {
231 $parts = @parse_url($uri);
236 $host = $parts["host"];
237 if (!empty($parts["port"])) {
238 $host .= ':'.$parts["port"];
241 $path_parts = explode("/", trim($parts["path"], "/"));
243 $nick = array_pop($path_parts);
246 $lrdd = self::hostMeta($host);
247 $host .= "/".array_shift($path_parts);
248 } while (!$lrdd && (sizeof($path_parts) > 0));
252 logger("No lrdd data found for ".$uri, LOGGER_DEBUG);
256 foreach ($lrdd as $type => $template) {
261 $path = str_replace('{uri}', urlencode($uri), $template);
262 $webfinger = self::webfinger($path, $type);
264 if (!$webfinger && (strstr($uri, "@"))) {
265 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
266 $webfinger = self::webfinger($path, $type);
269 // Special treatment for Mastodon
270 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
271 // But the webfinger for this format fails.
272 if (!$webfinger && !empty($nick)) {
273 // Mastodon uses a "@" as prefix for usernames in their url format
274 $nick = ltrim($nick, '@');
276 $addr = $nick."@".$host;
278 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
279 $webfinger = self::webfinger($path, $type);
283 if (!is_array($webfinger["links"])) {
284 logger("No webfinger links found for ".$uri, LOGGER_DEBUG);
290 foreach ($webfinger["links"] as $link) {
291 $data[] = ["@attributes" => $link];
294 if (is_array($webfinger["aliases"])) {
295 foreach ($webfinger["aliases"] as $alias) {
296 $data[] = ["@attributes" =>
306 * @brief Fetch information (protocol endpoints and user information) about a given uri
308 * @param string $uri Address that should be probed
309 * @param string $network Test for this specific network
310 * @param integer $uid User ID for the probe (only used for mails)
311 * @param boolean $cache Use cached values?
313 * @return array uri data
315 public static function uri($uri, $network = "", $uid = -1, $cache = true)
318 $result = Cache::get("Probe::uri:".$network.":".$uri);
319 if (!is_null($result)) {
328 $data = self::detect($uri, $network, $uid);
330 if (!isset($data["url"])) {
334 if (x($data, "photo")) {
335 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
337 $data["photo"] = System::baseUrl().'/images/person-175.jpg';
340 if (empty($data["name"])) {
341 if (!empty($data["nick"])) {
342 $data["name"] = $data["nick"];
345 if (!x($data, "name")) {
346 $data["name"] = $data["url"];
350 if (empty($data["nick"])) {
351 $data["nick"] = strtolower($data["name"]);
353 if (strpos($data['nick'], ' ')) {
354 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
358 if (self::$baseurl != "") {
359 $data["baseurl"] = self::$baseurl;
362 if (!isset($data["network"])) {
363 $data["network"] = NETWORK_PHANTOM;
366 $data = self::rearrangeData($data);
368 // Only store into the cache if the value seems to be valid
369 if (!in_array($data['network'], [NETWORK_PHANTOM, NETWORK_MAIL])) {
370 Cache::set("Probe::uri:".$network.":".$uri, $data, CACHE_DAY);
372 /// @todo temporary fix - we need a real contact update function that updates only changing fields
373 /// The biggest problem is the avatar picture that could have a reduced image size.
374 /// It should only be updated if the existing picture isn't existing anymore.
375 /// We only update the contact when it is no probing for a specific network.
376 if (($data['network'] != NETWORK_FEED)
384 $fields = ['name' => $data['name'],
385 'nick' => $data['nick'],
386 'url' => $data['url'],
387 'addr' => $data['addr'],
388 'photo' => $data['photo'],
389 'keywords' => $data['keywords'],
390 'location' => $data['location'],
391 'about' => $data['about'],
392 'notify' => $data['notify'],
393 'network' => $data['network'],
394 'server_url' => $data['baseurl']];
398 foreach ($fields as $key => $val) {
400 unset($fields[$key]);
402 $fieldnames[] = $key;
406 $fields['updated'] = DBM::date();
408 $condition = ['nurl' => normalise_link($data["url"])];
410 $old_fields = dba::selectFirst('gcontact', $fieldnames, $condition);
412 dba::update('gcontact', $fields, $condition, $old_fields);
414 $fields = ['name' => $data['name'],
415 'nick' => $data['nick'],
416 'url' => $data['url'],
417 'addr' => $data['addr'],
418 'alias' => $data['alias'],
419 'keywords' => $data['keywords'],
420 'location' => $data['location'],
421 'about' => $data['about'],
422 'batch' => $data['batch'],
423 'notify' => $data['notify'],
424 'poll' => $data['poll'],
425 'request' => $data['request'],
426 'confirm' => $data['confirm'],
427 'poco' => $data['poco'],
428 'network' => $data['network'],
429 'success_update' => DBM::date()];
433 foreach ($fields as $key => $val) {
435 unset($fields[$key]);
437 $fieldnames[] = $key;
441 $condition = ['nurl' => normalise_link($data["url"]), 'self' => false, 'uid' => 0];
443 $old_fields = dba::selectFirst('contact', $fieldnames, $condition);
445 dba::update('contact', $fields, $condition, $old_fields);
453 * @brief Switch the scheme of an url between http and https
455 * @param string $url URL
457 * @return string switched URL
459 private static function switchScheme($url)
461 $parts = parse_url($url);
463 if (!isset($parts['scheme'])) {
467 if ($parts['scheme'] == 'http') {
468 $url = str_replace('http://', 'https://', $url);
469 } elseif ($parts['scheme'] == 'https') {
470 $url = str_replace('https://', 'http://', $url);
477 * @brief Checks if a profile url should be OStatus but only provides partial information
479 * @param array $webfinger Webfinger data
480 * @param string $lrdd Path template for webfinger request
481 * @param string $type type
483 * @return array fixed webfinger data
485 private static function fixOStatus($webfinger, $lrdd, $type)
487 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
494 foreach ($webfinger['links'] as $link) {
495 if ($link['rel'] == NAMESPACE_OSTATUSSUB) {
498 if ($link['rel'] == 'magic-public-key') {
503 if (!$is_ostatus || $has_key) {
507 $url = self::switchScheme($webfinger['subject']);
508 $path = str_replace('{uri}', urlencode($url), $lrdd);
509 $webfinger2 = self::webfinger($path, $type);
511 // Is the new webfinger detectable as OStatus?
512 if (self::ostatus($webfinger2, true)) {
513 $webfinger = $webfinger2;
520 * @brief Fetch information (protocol endpoints and user information) about a given uri
522 * This function is only called by the "uri" function that adds caching and rearranging of data.
524 * @param string $uri Address that should be probed
525 * @param string $network Test for this specific network
526 * @param integer $uid User ID for the probe (only used for mails)
528 * @return array uri data
530 private static function detect($uri, $network, $uid)
532 $parts = parse_url($uri);
534 if (!empty($parts["scheme"]) && !empty($parts["host"]) && !empty($parts["path"])) {
535 $host = $parts["host"];
536 if (!empty($parts["port"])) {
537 $host .= ':'.$parts["port"];
540 if ($host == 'twitter.com') {
541 return ["network" => NETWORK_TWITTER];
543 $lrdd = self::hostMeta($host);
545 if (is_bool($lrdd)) {
549 $path_parts = explode("/", trim($parts["path"], "/"));
551 while (!$lrdd && (sizeof($path_parts) > 1)) {
552 $host .= "/".array_shift($path_parts);
553 $lrdd = self::hostMeta($host);
556 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
557 return self::feed($uri);
559 $nick = array_pop($path_parts);
561 // Mastodon uses a "@" as prefix for usernames in their url format
562 $nick = ltrim($nick, '@');
564 $addr = $nick."@".$host;
565 } elseif (strstr($uri, '@')) {
566 // If the URI starts with "mailto:" then jump directly to the mail detection
567 if (strpos($uri, 'mailto:') !== false) {
568 $uri = str_replace('mailto:', '', $uri);
569 return self::mail($uri, $uid);
572 if ($network == NETWORK_MAIL) {
573 return self::mail($uri, $uid);
575 // Remove "acct:" from the URI
576 $uri = str_replace('acct:', '', $uri);
578 $host = substr($uri, strpos($uri, '@') + 1);
579 $nick = substr($uri, 0, strpos($uri, '@'));
581 if (strpos($uri, '@twitter.com')) {
582 return ["network" => NETWORK_TWITTER];
584 $lrdd = self::hostMeta($host);
586 if (is_bool($lrdd)) {
591 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
592 return self::mail($uri, $uid);
596 logger("Uri ".$uri." was not detectable", LOGGER_DEBUG);
602 /// @todo Do we need the prefix "acct:" or "acct://"?
604 foreach ($lrdd as $type => $template) {
609 // At first try it with the given uri
610 $path = str_replace('{uri}', urlencode($uri), $template);
611 $webfinger = self::webfinger($path, $type);
613 // Fix possible problems with GNU Social probing to wrong scheme
614 $webfinger = self::fixOStatus($webfinger, $template, $type);
616 // We cannot be sure that the detected address was correct, so we don't use the values
617 if ($webfinger && ($uri != $addr)) {
622 // Try webfinger with the address (user@domain.tld)
624 $path = str_replace('{uri}', urlencode($addr), $template);
625 $webfinger = self::webfinger($path, $type);
628 // Mastodon needs to have it with "acct:"
630 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
631 $webfinger = self::webfinger($path, $type);
636 return self::feed($uri);
641 logger("Probing ".$uri, LOGGER_DEBUG);
643 if (in_array($network, ["", NETWORK_DFRN])) {
644 $result = self::dfrn($webfinger);
646 if ((!$result && ($network == "")) || ($network == NETWORK_DIASPORA)) {
647 $result = self::diaspora($webfinger);
649 if ((!$result && ($network == "")) || ($network == NETWORK_OSTATUS)) {
650 $result = self::ostatus($webfinger);
652 if ((!$result && ($network == "")) || ($network == NETWORK_PUMPIO)) {
653 $result = self::pumpio($webfinger);
655 if ((!$result && ($network == "")) || ($network == NETWORK_FEED)) {
656 $result = self::feed($uri);
658 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
659 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
660 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
661 $result["nick"] = $nick;
664 if (empty($result["addr"]) && ($addr != "")) {
665 $result["addr"] = $addr;
669 logger($uri." is ".$result["network"], LOGGER_DEBUG);
671 if (empty($result["baseurl"])) {
672 $pos = strpos($result["url"], $host);
674 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
682 * @brief Perform a webfinger request.
684 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
686 * @param string $url Address that should be probed
687 * @param string $type type
689 * @return array webfinger data
691 private static function webfinger($url, $type)
693 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
696 $ret = Network::zFetchURL($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
697 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
700 $data = $ret['body'];
702 $webfinger = json_decode($data, true);
703 if (is_array($webfinger)) {
704 if (!isset($webfinger["links"])) {
705 logger("No json webfinger links for ".$url, LOGGER_DEBUG);
711 // If it is not JSON, maybe it is XML
712 $xrd = parse_xml_string($data, false);
713 if (!is_object($xrd)) {
714 logger("No webfinger data retrievable for ".$url, LOGGER_DEBUG);
718 $xrd_arr = XML::elementToArray($xrd);
719 if (!isset($xrd_arr["xrd"]["link"])) {
720 logger("No XML webfinger links for ".$url, LOGGER_DEBUG);
726 if (!empty($xrd_arr["xrd"]["subject"])) {
727 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
730 if (!empty($xrd_arr["xrd"]["alias"])) {
731 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
734 $webfinger["links"] = [];
736 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
737 if (!empty($data["@attributes"])) {
738 $attributes = $data["@attributes"];
739 } elseif ($value == "@attributes") {
745 $webfinger["links"][] = $attributes;
751 * @brief Poll the Friendica specific noscrape page.
753 * "noscrape" is a faster alternative to fetch the data from the hcard.
754 * This functionality was originally created for the directory.
756 * @param string $noscrape_url Link to the noscrape page
757 * @param array $data The already fetched data
759 * @return array noscrape data
761 private static function pollNoscrape($noscrape_url, $data)
763 $ret = Network::zFetchURL($noscrape_url);
764 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
767 $content = $ret['body'];
769 logger("Empty body for ".$noscrape_url, LOGGER_DEBUG);
773 $json = json_decode($content, true);
774 if (!is_array($json)) {
775 logger("No json data for ".$noscrape_url, LOGGER_DEBUG);
779 if (!empty($json["fn"])) {
780 $data["name"] = $json["fn"];
783 if (!empty($json["addr"])) {
784 $data["addr"] = $json["addr"];
787 if (!empty($json["nick"])) {
788 $data["nick"] = $json["nick"];
791 if (!empty($json["guid"])) {
792 $data["guid"] = $json["guid"];
795 if (!empty($json["comm"])) {
796 $data["community"] = $json["comm"];
799 if (!empty($json["tags"])) {
800 $keywords = implode(" ", $json["tags"]);
801 if ($keywords != "") {
802 $data["keywords"] = $keywords;
806 $location = Profile::formatLocation($json);
808 $data["location"] = $location;
811 if (!empty($json["about"])) {
812 $data["about"] = $json["about"];
815 if (!empty($json["key"])) {
816 $data["pubkey"] = $json["key"];
819 if (!empty($json["photo"])) {
820 $data["photo"] = $json["photo"];
823 if (!empty($json["dfrn-request"])) {
824 $data["request"] = $json["dfrn-request"];
827 if (!empty($json["dfrn-confirm"])) {
828 $data["confirm"] = $json["dfrn-confirm"];
831 if (!empty($json["dfrn-notify"])) {
832 $data["notify"] = $json["dfrn-notify"];
835 if (!empty($json["dfrn-poll"])) {
836 $data["poll"] = $json["dfrn-poll"];
843 * @brief Check for valid DFRN data
845 * @param array $data DFRN data
847 * @return int Number of errors
849 public static function validDfrn($data)
852 if (!isset($data['key'])) {
855 if (!isset($data['dfrn-request'])) {
858 if (!isset($data['dfrn-confirm'])) {
861 if (!isset($data['dfrn-notify'])) {
864 if (!isset($data['dfrn-poll'])) {
871 * @brief Fetch data from a DFRN profile page and via "noscrape"
873 * @param string $profile_link Link to the profile page
875 * @return array profile data
877 public static function profile($profile_link)
881 logger("Check profile ".$profile_link, LOGGER_DEBUG);
883 // Fetch data via noscrape - this is faster
884 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
885 $data = self::pollNoscrape($noscrape_url, $data);
887 if (!isset($data["notify"])
888 || !isset($data["confirm"])
889 || !isset($data["request"])
890 || !isset($data["poll"])
891 || !isset($data["poco"])
892 || !isset($data["name"])
893 || !isset($data["photo"])
895 $data = self::pollHcard($profile_link, $data, true);
899 $prof_data["addr"] = $data["addr"];
900 $prof_data["nick"] = $data["nick"];
901 $prof_data["dfrn-request"] = $data["request"];
902 $prof_data["dfrn-confirm"] = $data["confirm"];
903 $prof_data["dfrn-notify"] = $data["notify"];
904 $prof_data["dfrn-poll"] = $data["poll"];
905 $prof_data["dfrn-poco"] = $data["poco"];
906 $prof_data["photo"] = $data["photo"];
907 $prof_data["fn"] = $data["name"];
908 $prof_data["key"] = $data["pubkey"];
910 logger("Result for profile ".$profile_link.": ".print_r($prof_data, true), LOGGER_DEBUG);
916 * @brief Check for DFRN contact
918 * @param array $webfinger Webfinger data
920 * @return array DFRN data
922 private static function dfrn($webfinger)
926 foreach ($webfinger["links"] as $link) {
927 if (($link["rel"] == NAMESPACE_DFRN) && ($link["href"] != "")) {
928 $data["network"] = NETWORK_DFRN;
929 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
930 $data["poll"] = $link["href"];
931 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
932 $data["url"] = $link["href"];
933 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
934 $hcard_url = $link["href"];
935 } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
936 $data["poco"] = $link["href"];
937 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && ($link["href"] != "")) {
938 $data["photo"] = $link["href"];
939 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
940 $data["baseurl"] = trim($link["href"], '/');
941 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
942 $data["guid"] = $link["href"];
943 } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
944 $data["pubkey"] = base64_decode($link["href"]);
946 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
947 if (strstr($data["pubkey"], 'RSA ')) {
948 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
953 if (is_array($webfinger["aliases"])) {
954 foreach ($webfinger["aliases"] as $alias) {
955 if (normalise_link($alias) != normalise_link($data["url"]) && ! strstr($alias, "@")) {
956 $data["alias"] = $alias;
957 } elseif (substr($alias, 0, 5) == 'acct:') {
958 $data["addr"] = substr($alias, 5);
963 if (!isset($data["network"]) || ($hcard_url == "")) {
967 // Fetch data via noscrape - this is faster
968 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
969 $data = self::pollNoscrape($noscrape_url, $data);
971 if (isset($data["notify"])
972 && isset($data["confirm"])
973 && isset($data["request"])
974 && isset($data["poll"])
975 && isset($data["name"])
976 && isset($data["photo"])
981 $data = self::pollHcard($hcard_url, $data, true);
987 * @brief Poll the hcard page (Diaspora and Friendica specific)
989 * @param string $hcard_url Link to the hcard page
990 * @param array $data The already fetched data
991 * @param boolean $dfrn Poll DFRN specific data
993 * @return array hcard data
995 private static function pollHcard($hcard_url, $data, $dfrn = false)
997 $ret = Network::zFetchURL($hcard_url);
998 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1001 $content = $ret['body'];
1006 $doc = new DOMDocument();
1007 if (!@$doc->loadHTML($content)) {
1011 $xpath = new DomXPath($doc);
1013 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1014 if (!is_object($vcards)) {
1018 if ($vcards->length > 0) {
1019 $vcard = $vcards->item(0);
1021 // We have to discard the guid from the hcard in favour of the guid from lrdd
1022 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1023 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1024 if (($search->length > 0) && ($data["guid"] == "")) {
1025 $data["guid"] = $search->item(0)->nodeValue;
1028 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1029 if ($search->length > 0) {
1030 $data["nick"] = $search->item(0)->nodeValue;
1033 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1034 if ($search->length > 0) {
1035 $data["name"] = $search->item(0)->nodeValue;
1038 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1039 if ($search->length > 0) {
1040 $data["searchable"] = $search->item(0)->nodeValue;
1043 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1044 if ($search->length > 0) {
1045 $data["pubkey"] = $search->item(0)->nodeValue;
1046 if (strstr($data["pubkey"], 'RSA ')) {
1047 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1051 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1052 if ($search->length > 0) {
1053 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1058 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1059 foreach ($photos as $photo) {
1061 foreach ($photo->attributes as $attribute) {
1062 $attr[$attribute->name] = trim($attribute->value);
1065 if (isset($attr["src"]) && isset($attr["width"])) {
1066 $avatar[$attr["width"]] = $attr["src"];
1069 // We don't have a width. So we just take everything that we got.
1070 // This is a Hubzilla workaround which doesn't send a width.
1071 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1072 $avatar[] = $attr["src"];
1076 if (sizeof($avatar)) {
1078 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1082 // Poll DFRN specific data
1083 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1084 if ($search->length > 0) {
1085 foreach ($search as $link) {
1086 //$data["request"] = $search->item(0)->nodeValue;
1088 foreach ($link->attributes as $attribute) {
1089 $attr[$attribute->name] = trim($attribute->value);
1092 $data[substr($attr["rel"], 5)] = $attr["href"];
1096 // Older Friendica versions had used the "uid" field differently than newer versions
1097 if ($data["nick"] == $data["guid"]) {
1098 unset($data["guid"]);
1107 * @brief Check for Diaspora contact
1109 * @param array $webfinger Webfinger data
1111 * @return array Diaspora data
1113 private static function diaspora($webfinger)
1117 foreach ($webfinger["links"] as $link) {
1118 if (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
1119 $hcard_url = $link["href"];
1120 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
1121 $data["baseurl"] = trim($link["href"], '/');
1122 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
1123 $data["guid"] = $link["href"];
1124 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
1125 $data["url"] = $link["href"];
1126 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1127 $data["poll"] = $link["href"];
1128 } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
1129 $data["poco"] = $link["href"];
1130 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1131 $data["notify"] = $link["href"];
1132 } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
1133 $data["pubkey"] = base64_decode($link["href"]);
1135 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1136 if (strstr($data["pubkey"], 'RSA ')) {
1137 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1142 if (!isset($data["url"]) || ($hcard_url == "")) {
1146 if (is_array($webfinger["aliases"])) {
1147 foreach ($webfinger["aliases"] as $alias) {
1148 if (normalise_link($alias) != normalise_link($data["url"]) && ! strstr($alias, "@")) {
1149 $data["alias"] = $alias;
1150 } elseif (substr($alias, 0, 5) == 'acct:') {
1151 $data["addr"] = substr($alias, 5);
1156 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1157 $data["addr"] = substr($webfinger["subject"], 5);
1160 // Fetch further information from the hcard
1161 $data = self::pollHcard($hcard_url, $data);
1167 if (isset($data["url"])
1168 && isset($data["guid"])
1169 && isset($data["baseurl"])
1170 && isset($data["pubkey"])
1171 && ($hcard_url != "")
1173 $data["network"] = NETWORK_DIASPORA;
1175 // The Diaspora handle must always be lowercase
1176 $data["addr"] = strtolower($data["addr"]);
1178 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1179 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1180 $data["batch"] = $data["baseurl"] . "/receive/public";
1189 * @brief Check for OStatus contact
1191 * @param array $webfinger Webfinger data
1192 * @param bool $short Short detection mode
1194 * @return array|bool OStatus data or "false" on error or "true" on short mode
1196 private static function ostatus($webfinger, $short = false)
1200 if (is_array($webfinger["aliases"])) {
1201 foreach ($webfinger["aliases"] as $alias) {
1202 if (strstr($alias, "@") && !strstr(normalise_link($alias), "http://")) {
1203 $data["addr"] = str_replace('acct:', '', $alias);
1208 if (is_string($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1209 && !strstr(normalise_link($webfinger["subject"]), "http://")
1211 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1215 if (is_array($webfinger["links"])) {
1216 foreach ($webfinger["links"] as $link) {
1217 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1218 && ($link["type"] == "text/html")
1219 && ($link["href"] != "")
1221 $data["url"] = $link["href"];
1222 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1223 $data["notify"] = $link["href"];
1224 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1225 $data["poll"] = $link["href"];
1226 } elseif (($link["rel"] == "magic-public-key") && ($link["href"] != "")) {
1227 $pubkey = $link["href"];
1229 if (substr($pubkey, 0, 5) === 'data:') {
1230 if (strstr($pubkey, ',')) {
1231 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1233 $pubkey = substr($pubkey, 5);
1235 } elseif (normalise_link($pubkey) == 'http://') {
1236 $ret = Network::zFetchURL($pubkey);
1237 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1240 $pubkey = $ret['body'];
1243 $key = explode(".", $pubkey);
1245 if (sizeof($key) >= 3) {
1246 $m = base64url_decode($key[1]);
1247 $e = base64url_decode($key[2]);
1248 $data["pubkey"] = Crypto::meToPem($m, $e);
1254 if (isset($data["notify"]) && isset($data["pubkey"])
1255 && isset($data["poll"])
1256 && isset($data["url"])
1258 $data["network"] = NETWORK_OSTATUS;
1267 // Fetch all additional data from the feed
1268 $ret = Network::zFetchURL($data["poll"]);
1269 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1272 $feed = $ret['body'];
1273 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1278 if ($feed_data["header"]["author-name"] != "") {
1279 $data["name"] = $feed_data["header"]["author-name"];
1281 if ($feed_data["header"]["author-nick"] != "") {
1282 $data["nick"] = $feed_data["header"]["author-nick"];
1284 if ($feed_data["header"]["author-avatar"] != "") {
1285 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1287 if ($feed_data["header"]["author-id"] != "") {
1288 $data["alias"] = $feed_data["header"]["author-id"];
1290 if ($feed_data["header"]["author-location"] != "") {
1291 $data["location"] = $feed_data["header"]["author-location"];
1293 if ($feed_data["header"]["author-about"] != "") {
1294 $data["about"] = $feed_data["header"]["author-about"];
1296 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1297 // So we take the value that we just fetched, although the other one worked as well
1298 if ($feed_data["header"]["author-link"] != "") {
1299 $data["url"] = $feed_data["header"]["author-link"];
1302 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1303 $data['url'] = $data["alias"];
1304 $data["alias"] = '';
1307 /// @todo Fetch location and "about" from the feed as well
1312 * @brief Fetch data from a pump.io profile page
1314 * @param string $profile_link Link to the profile page
1316 * @return array profile data
1318 private static function pumpioProfileData($profile_link)
1320 $doc = new DOMDocument();
1321 if (!@$doc->loadHTMLFile($profile_link)) {
1325 $xpath = new DomXPath($doc);
1329 // This is ugly - but pump.io doesn't seem to know a better way for it
1330 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1331 $pos = strpos($data["name"], chr(10));
1333 $data["name"] = trim(substr($data["name"], 0, $pos));
1336 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1338 foreach ($avatar->attributes as $attribute) {
1339 if ($attribute->name == "src") {
1340 $data["photo"] = trim($attribute->value);
1345 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
1346 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
1352 * @brief Check for pump.io contact
1354 * @param array $webfinger Webfinger data
1356 * @return array pump.io data
1358 private static function pumpio($webfinger)
1361 foreach ($webfinger["links"] as $link) {
1362 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1363 && ($link["type"] == "text/html")
1364 && ($link["href"] != "")
1366 $data["url"] = $link["href"];
1367 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1368 $data["notify"] = $link["href"];
1369 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1370 $data["poll"] = $link["href"];
1371 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1372 $data["dialback"] = $link["href"];
1375 if (isset($data["poll"]) && isset($data["notify"])
1376 && isset($data["dialback"])
1377 && isset($data["url"])
1379 // by now we use these fields only for the network type detection
1380 // So we unset all data that isn't used at the moment
1381 unset($data["dialback"]);
1383 $data["network"] = NETWORK_PUMPIO;
1388 $profile_data = self::pumpioProfileData($data["url"]);
1390 if (!$profile_data) {
1394 $data = array_merge($data, $profile_data);
1400 * @brief Check page for feed link
1402 * @param string $url Page link
1404 * @return string feed link
1406 private static function getFeedLink($url)
1408 $doc = new DOMDocument();
1410 if (!@$doc->loadHTMLFile($url)) {
1414 $xpath = new DomXPath($doc);
1416 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1417 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1418 if (!is_object($feeds)) {
1422 if ($feeds->length == 0) {
1428 foreach ($feeds as $feed) {
1430 foreach ($feed->attributes as $attribute) {
1431 $attr[$attribute->name] = trim($attribute->value);
1434 if ($feed_url == "") {
1435 $feed_url = $attr["href"];
1443 * @brief Check for feed contact
1445 * @param string $url Profile link
1446 * @param boolean $probe Do a probe if the page contains a feed link
1448 * @return array feed data
1450 private static function feed($url, $probe = true)
1452 $ret = Network::zFetchURL($url);
1453 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1456 $feed = $ret['body'];
1457 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1464 $feed_url = self::getFeedLink($url);
1470 return self::feed($feed_url, false);
1473 if ($feed_data["header"]["author-name"] != "") {
1474 $data["name"] = $feed_data["header"]["author-name"];
1477 if ($feed_data["header"]["author-nick"] != "") {
1478 $data["nick"] = $feed_data["header"]["author-nick"];
1481 if ($feed_data["header"]["author-avatar"] != "") {
1482 $data["photo"] = $feed_data["header"]["author-avatar"];
1485 if ($feed_data["header"]["author-id"] != "") {
1486 $data["alias"] = $feed_data["header"]["author-id"];
1489 $data["url"] = $url;
1490 $data["poll"] = $url;
1492 if ($feed_data["header"]["author-link"] != "") {
1493 $data["baseurl"] = $feed_data["header"]["author-link"];
1495 $data["baseurl"] = $data["url"];
1498 $data["network"] = NETWORK_FEED;
1504 * @brief Check for mail contact
1506 * @param string $uri Profile link
1507 * @param integer $uid User ID
1509 * @return array mail data
1511 private static function mail($uri, $uid)
1513 if (!validate_email($uri)) {
1518 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1520 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1522 if (DBM::is_result($x) && DBM::is_result($r)) {
1523 $mailbox = Email::constructMailboxName($r[0]);
1525 openssl_private_decrypt(hex2bin($r[0]['pass']), $password, $x[0]['prvkey']);
1526 $mbox = Email::connect($mailbox, $r[0]['user'], $password);
1532 $msgs = Email::poll($mbox, $uri);
1533 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1535 if (!count($msgs)) {
1540 $phost = substr($uri, strpos($uri, '@') + 1);
1543 $data["addr"] = $uri;
1544 $data["network"] = NETWORK_MAIL;
1545 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1546 $data["nick"] = $data["name"];
1547 $data["photo"] = avatar_img($uri);
1548 $data["url"] = 'mailto:'.$uri;
1549 $data["notify"] = 'smtp '.random_string();
1550 $data["poll"] = 'email '.random_string();
1552 $x = Email::messageMeta($mbox, $msgs[0]);
1553 if (stristr($x[0]->from, $uri)) {
1554 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1555 } elseif (stristr($x[0]->to, $uri)) {
1556 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1559 foreach ($adr as $feadr) {
1560 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1561 &&(strcasecmp($feadr->host, $phost) == 0)
1562 && (strlen($feadr->personal))
1564 $personal = imap_mime_header_decode($feadr->personal);
1566 foreach ($personal as $perspart) {
1567 if ($perspart->charset != "default") {
1568 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1570 $data["name"] .= $perspart->text;
1574 $data["name"] = notags($data["name"]);
1578 if (!empty($mbox)) {
1586 * @brief Mix two paths together to possibly fix missing parts
1588 * @param string $avatar Path to the avatar
1589 * @param string $base Another path that is hopefully complete
1591 * @return string fixed avatar path
1593 public static function fixAvatar($avatar, $base)
1595 $base_parts = parse_url($base);
1597 // Remove all parts that could create a problem
1598 unset($base_parts['path']);
1599 unset($base_parts['query']);
1600 unset($base_parts['fragment']);
1602 $avatar_parts = parse_url($avatar);
1605 $parts = array_merge($base_parts, $avatar_parts);
1607 // And put them together again
1608 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1609 $host = isset($parts['host']) ? $parts['host'] : '';
1610 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1611 $path = isset($parts['path']) ? $parts['path'] : '';
1612 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1613 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1615 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1617 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);