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\XML;
27 require_once 'include/dba.php';
28 require_once 'include/network.php';
31 * @brief This class contain functions for probing URL
36 private static $baseurl;
39 * @brief Rearrange the array so that it always has the same order
41 * @param array $data Unordered data
43 * @return array Ordered data
45 private static function rearrangeData($data)
47 $fields = array("name", "nick", "guid", "url", "addr", "alias",
48 "photo", "community", "keywords", "location", "about",
49 "batch", "notify", "poll", "request", "confirm", "poco",
50 "priority", "network", "pubkey", "baseurl");
53 foreach ($fields as $field) {
54 if (isset($data[$field])) {
55 $newdata[$field] = $data[$field];
57 $newdata[$field] = "";
61 // We don't use the "priority" field anymore and replace it with a dummy.
62 $newdata["priority"] = 0;
68 * @brief Check if the hostname belongs to the own server
70 * @param string $host The hostname that is to be checked
72 * @return bool Does the testes hostname belongs to the own server?
74 private static function ownHost($host)
76 $own_host = get_app()->get_hostname();
78 $parts = parse_url($host);
80 if (!isset($parts['scheme'])) {
81 $parts = parse_url('http://'.$host);
84 if (!isset($parts['host'])) {
87 return $parts['host'] == $own_host;
91 * @brief Probes for webfinger path via "host-meta"
93 * @param string $host The host part of an url
95 * @return array with template and type of the webfinger template for JSON or XML
97 private static function hostMeta($host)
99 // Reset the static variable
102 $ssl_url = "https://".$host."/.well-known/host-meta";
103 $url = "http://".$host."/.well-known/host-meta";
105 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
108 logger("Probing for ".$host, LOGGER_DEBUG);
110 $ret = z_fetch_url($ssl_url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
111 if ($ret['success']) {
113 $xrd = parse_xml_string($xml, false);
114 $host_url = 'https://'.$host;
117 if (!is_object($xrd)) {
118 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
119 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
120 logger("Probing timeout for ".$url, LOGGER_DEBUG);
124 $xrd = parse_xml_string($xml, false);
125 $host_url = 'http://'.$host;
127 if (!is_object($xrd)) {
128 logger("No xrd object found for ".$host, LOGGER_DEBUG);
132 $links = XML::elementToArray($xrd);
133 if (!isset($links["xrd"]["link"])) {
134 logger("No xrd data found for ".$host, LOGGER_DEBUG);
139 // The following webfinger path is defined in RFC 7033 https://tools.ietf.org/html/rfc7033
140 // Problem is that Hubzilla currently doesn't provide all data in the JSON webfinger
141 // compared to the XML webfinger. So this is commented out by now.
142 // $lrdd = array("application/jrd+json" => $host_url.'/.well-known/webfinger?resource={uri}');
144 foreach ($links["xrd"]["link"] as $value => $link) {
145 if (!empty($link["@attributes"])) {
146 $attributes = $link["@attributes"];
147 } elseif ($value == "@attributes") {
153 if (($attributes["rel"] == "lrdd") && !empty($attributes["template"])) {
154 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
156 $lrdd[$type] = $attributes["template"];
160 self::$baseurl = "http://".$host;
162 logger("Probing successful for ".$host, LOGGER_DEBUG);
168 * @brief Perform Webfinger lookup and return DFRN data
170 * Given an email style address, perform webfinger lookup and
171 * return the resulting DFRN profile URL, or if no DFRN profile URL
172 * is located, returns an OStatus subscription template (prefixed
173 * with the string 'stat:' to identify it as on OStatus template).
174 * If this isn't an email style address just return $webbie.
175 * Return an empty string if email-style addresses but webfinger fails,
176 * or if the resultant personal XRD doesn't contain a supported
177 * subscription/friend-request attribute.
179 * amended 7/9/2011 to return an hcard which could save potentially loading
180 * a lengthy content page to scrape dfrn attributes
182 * @param string $webbie Address that should be probed
183 * @param string $hcard_url Link to the hcard - is returned by reference
185 * @return string profile link
187 public static function webfingerDfrn($webbie, &$hcard_url)
191 $links = self::lrdd($webbie);
192 logger('webfingerDfrn: '.$webbie.':'.print_r($links, true), LOGGER_DATA);
194 foreach ($links as $link) {
195 if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
196 $profile_link = $link['@attributes']['href'];
198 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) && ($profile_link == "")) {
199 $profile_link = 'stat:'.$link['@attributes']['template'];
201 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
202 $hcard_url = $link['@attributes']['href'];
206 return $profile_link;
210 * @brief Check an URI for LRDD data
212 * this is a replacement for the "lrdd" function in include/network.php.
213 * It isn't used in this class and has some redundancies in the code.
214 * When time comes we can check the existing calls for "lrdd" if we can rework them.
216 * @param string $uri Address that should be probed
218 * @return array uri data
220 public static function lrdd($uri)
222 $lrdd = self::hostMeta($uri);
225 if (is_bool($lrdd)) {
230 $parts = @parse_url($uri);
235 $host = $parts["host"];
236 if (!empty($parts["port"])) {
237 $host .= ':'.$parts["port"];
240 $path_parts = explode("/", trim($parts["path"], "/"));
242 $nick = array_pop($path_parts);
245 $lrdd = self::hostMeta($host);
246 $host .= "/".array_shift($path_parts);
247 } while (!$lrdd && (sizeof($path_parts) > 0));
251 logger("No lrdd data found for ".$uri, LOGGER_DEBUG);
255 foreach ($lrdd as $type => $template) {
260 $path = str_replace('{uri}', urlencode($uri), $template);
261 $webfinger = self::webfinger($path, $type);
263 if (!$webfinger && (strstr($uri, "@"))) {
264 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
265 $webfinger = self::webfinger($path, $type);
268 // Special treatment for Mastodon
269 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
270 // But the webfinger for this format fails.
271 if (!$webfinger && !empty($nick)) {
272 // Mastodon uses a "@" as prefix for usernames in their url format
273 $nick = ltrim($nick, '@');
275 $addr = $nick."@".$host;
277 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
278 $webfinger = self::webfinger($path, $type);
282 if (!is_array($webfinger["links"])) {
283 logger("No webfinger links found for ".$uri, LOGGER_DEBUG);
289 foreach ($webfinger["links"] as $link) {
290 $data[] = array("@attributes" => $link);
293 if (is_array($webfinger["aliases"])) {
294 foreach ($webfinger["aliases"] as $alias) {
295 $data[] = array("@attributes" =>
296 array("rel" => "alias",
305 * @brief Fetch information (protocol endpoints and user information) about a given uri
307 * @param string $uri Address that should be probed
308 * @param string $network Test for this specific network
309 * @param integer $uid User ID for the probe (only used for mails)
310 * @param boolean $cache Use cached values?
312 * @return array uri data
314 public static function uri($uri, $network = "", $uid = -1, $cache = true)
317 $result = Cache::get("Probe::uri:".$network.":".$uri);
318 if (!is_null($result)) {
327 $data = self::detect($uri, $network, $uid);
329 if (!isset($data["url"])) {
333 if (x($data, "photo")) {
334 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
336 $data["photo"] = System::baseUrl().'/images/person-175.jpg';
339 if (empty($data["name"])) {
340 if (!empty($data["nick"])) {
341 $data["name"] = $data["nick"];
344 if (!x($data, "name")) {
345 $data["name"] = $data["url"];
349 if (empty($data["nick"])) {
350 $data["nick"] = strtolower($data["name"]);
352 if (strpos($data['nick'], ' ')) {
353 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
357 if (self::$baseurl != "") {
358 $data["baseurl"] = self::$baseurl;
361 if (!isset($data["network"])) {
362 $data["network"] = NETWORK_PHANTOM;
365 $data = self::rearrangeData($data);
367 // Only store into the cache if the value seems to be valid
368 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
369 Cache::set("Probe::uri:".$network.":".$uri, $data, CACHE_DAY);
371 /// @todo temporary fix - we need a real contact update function that updates only changing fields
372 /// The biggest problem is the avatar picture that could have a reduced image size.
373 /// It should only be updated if the existing picture isn't existing anymore.
374 /// We only update the contact when it is no probing for a specific network.
375 if (($data['network'] != NETWORK_FEED)
383 $fields = array('name' => $data['name'],
384 'nick' => $data['nick'],
385 'url' => $data['url'],
386 'addr' => $data['addr'],
387 'photo' => $data['photo'],
388 'keywords' => $data['keywords'],
389 'location' => $data['location'],
390 'about' => $data['about'],
391 'notify' => $data['notify'],
392 'network' => $data['network'],
393 'server_url' => $data['baseurl']);
395 $fieldnames = array();
397 foreach ($fields as $key => $val) {
399 unset($fields[$key]);
401 $fieldnames[] = $key;
405 $fields['updated'] = DBM::date();
407 $condition = array('nurl' => normalise_link($data["url"]));
409 $old_fields = dba::selectFirst('gcontact', $fieldnames, $condition);
411 dba::update('gcontact', $fields, $condition, $old_fields);
413 $fields = array('name' => $data['name'],
414 'nick' => $data['nick'],
415 'url' => $data['url'],
416 'addr' => $data['addr'],
417 'alias' => $data['alias'],
418 'keywords' => $data['keywords'],
419 'location' => $data['location'],
420 'about' => $data['about'],
421 'batch' => $data['batch'],
422 'notify' => $data['notify'],
423 'poll' => $data['poll'],
424 'request' => $data['request'],
425 'confirm' => $data['confirm'],
426 'poco' => $data['poco'],
427 'network' => $data['network'],
428 'success_update' => DBM::date());
430 $fieldnames = array();
432 foreach ($fields as $key => $val) {
434 unset($fields[$key]);
436 $fieldnames[] = $key;
440 $condition = array('nurl' => normalise_link($data["url"]), 'self' => false, 'uid' => 0);
442 $old_fields = dba::selectFirst('contact', $fieldnames, $condition);
444 dba::update('contact', $fields, $condition, $old_fields);
452 * @brief Switch the scheme of an url between http and https
454 * @param string $url URL
456 * @return string switched URL
458 private static function switchScheme($url)
460 $parts = parse_url($url);
462 if (!isset($parts['scheme'])) {
466 if ($parts['scheme'] == 'http') {
467 $url = str_replace('http://', 'https://', $url);
468 } elseif ($parts['scheme'] == 'https') {
469 $url = str_replace('https://', 'http://', $url);
476 * @brief Checks if a profile url should be OStatus but only provides partial information
478 * @param array $webfinger Webfinger data
479 * @param string $lrdd Path template for webfinger request
480 * @param string $type type
482 * @return array fixed webfinger data
484 private static function fixOStatus($webfinger, $lrdd, $type)
486 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
493 foreach ($webfinger['links'] as $link) {
494 if ($link['rel'] == NAMESPACE_OSTATUSSUB) {
497 if ($link['rel'] == 'magic-public-key') {
502 if (!$is_ostatus || $has_key) {
506 $url = self::switchScheme($webfinger['subject']);
507 $path = str_replace('{uri}', urlencode($url), $lrdd);
508 $webfinger2 = self::webfinger($path, $type);
510 // Is the new webfinger detectable as OStatus?
511 if (self::ostatus($webfinger2, true)) {
512 $webfinger = $webfinger2;
519 * @brief Fetch information (protocol endpoints and user information) about a given uri
521 * This function is only called by the "uri" function that adds caching and rearranging of data.
523 * @param string $uri Address that should be probed
524 * @param string $network Test for this specific network
525 * @param integer $uid User ID for the probe (only used for mails)
527 * @return array uri data
529 private static function detect($uri, $network, $uid)
531 $parts = parse_url($uri);
533 if (!empty($parts["scheme"]) && !empty($parts["host"]) && !empty($parts["path"])) {
534 $host = $parts["host"];
535 if (!empty($parts["port"])) {
536 $host .= ':'.$parts["port"];
539 if ($host == 'twitter.com') {
540 return array("network" => NETWORK_TWITTER);
542 $lrdd = self::hostMeta($host);
544 if (is_bool($lrdd)) {
548 $path_parts = explode("/", trim($parts["path"], "/"));
550 while (!$lrdd && (sizeof($path_parts) > 1)) {
551 $host .= "/".array_shift($path_parts);
552 $lrdd = self::hostMeta($host);
555 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
556 return self::feed($uri);
558 $nick = array_pop($path_parts);
560 // Mastodon uses a "@" as prefix for usernames in their url format
561 $nick = ltrim($nick, '@');
563 $addr = $nick."@".$host;
564 } elseif (strstr($uri, '@')) {
565 // If the URI starts with "mailto:" then jump directly to the mail detection
566 if (strpos($uri, 'mailto:') !== false) {
567 $uri = str_replace('mailto:', '', $uri);
568 return self::mail($uri, $uid);
571 if ($network == NETWORK_MAIL) {
572 return self::mail($uri, $uid);
574 // Remove "acct:" from the URI
575 $uri = str_replace('acct:', '', $uri);
577 $host = substr($uri, strpos($uri, '@') + 1);
578 $nick = substr($uri, 0, strpos($uri, '@'));
580 if (strpos($uri, '@twitter.com')) {
581 return array("network" => NETWORK_TWITTER);
583 $lrdd = self::hostMeta($host);
585 if (is_bool($lrdd)) {
590 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
591 return self::mail($uri, $uid);
595 logger("Uri ".$uri." was not detectable", LOGGER_DEBUG);
601 /// @todo Do we need the prefix "acct:" or "acct://"?
603 foreach ($lrdd as $type => $template) {
608 // At first try it with the given uri
609 $path = str_replace('{uri}', urlencode($uri), $template);
610 $webfinger = self::webfinger($path, $type);
612 // Fix possible problems with GNU Social probing to wrong scheme
613 $webfinger = self::fixOStatus($webfinger, $template, $type);
615 // We cannot be sure that the detected address was correct, so we don't use the values
616 if ($webfinger && ($uri != $addr)) {
621 // Try webfinger with the address (user@domain.tld)
623 $path = str_replace('{uri}', urlencode($addr), $template);
624 $webfinger = self::webfinger($path, $type);
627 // Mastodon needs to have it with "acct:"
629 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
630 $webfinger = self::webfinger($path, $type);
635 return self::feed($uri);
640 logger("Probing ".$uri, LOGGER_DEBUG);
642 if (in_array($network, array("", NETWORK_DFRN))) {
643 $result = self::dfrn($webfinger);
645 if ((!$result && ($network == "")) || ($network == NETWORK_DIASPORA)) {
646 $result = self::diaspora($webfinger);
648 if ((!$result && ($network == "")) || ($network == NETWORK_OSTATUS)) {
649 $result = self::ostatus($webfinger);
651 if ((!$result && ($network == "")) || ($network == NETWORK_PUMPIO)) {
652 $result = self::pumpio($webfinger);
654 if ((!$result && ($network == "")) || ($network == NETWORK_FEED)) {
655 $result = self::feed($uri);
657 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
658 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
659 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
660 $result["nick"] = $nick;
663 if (empty($result["addr"]) && ($addr != "")) {
664 $result["addr"] = $addr;
668 logger($uri." is ".$result["network"], LOGGER_DEBUG);
670 if (empty($result["baseurl"])) {
671 $pos = strpos($result["url"], $host);
673 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
681 * @brief Perform a webfinger request.
683 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
685 * @param string $url Address that should be probed
686 * @param string $type type
688 * @return array webfinger data
690 private static function webfinger($url, $type)
692 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
695 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => $type));
696 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
699 $data = $ret['body'];
701 $webfinger = json_decode($data, true);
702 if (is_array($webfinger)) {
703 if (!isset($webfinger["links"])) {
704 logger("No json webfinger links for ".$url, LOGGER_DEBUG);
710 // If it is not JSON, maybe it is XML
711 $xrd = parse_xml_string($data, false);
712 if (!is_object($xrd)) {
713 logger("No webfinger data retrievable for ".$url, LOGGER_DEBUG);
717 $xrd_arr = XML::elementToArray($xrd);
718 if (!isset($xrd_arr["xrd"]["link"])) {
719 logger("No XML webfinger links for ".$url, LOGGER_DEBUG);
723 $webfinger = array();
725 if (!empty($xrd_arr["xrd"]["subject"])) {
726 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
729 if (!empty($xrd_arr["xrd"]["alias"])) {
730 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
733 $webfinger["links"] = array();
735 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
736 if (!empty($data["@attributes"])) {
737 $attributes = $data["@attributes"];
738 } elseif ($value == "@attributes") {
744 $webfinger["links"][] = $attributes;
750 * @brief Poll the Friendica specific noscrape page.
752 * "noscrape" is a faster alternative to fetch the data from the hcard.
753 * This functionality was originally created for the directory.
755 * @param string $noscrape_url Link to the noscrape page
756 * @param array $data The already fetched data
758 * @return array noscrape data
760 private static function pollNoscrape($noscrape_url, $data)
762 $ret = z_fetch_url($noscrape_url);
763 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
766 $content = $ret['body'];
768 logger("Empty body for ".$noscrape_url, LOGGER_DEBUG);
772 $json = json_decode($content, true);
773 if (!is_array($json)) {
774 logger("No json data for ".$noscrape_url, LOGGER_DEBUG);
778 if (!empty($json["fn"])) {
779 $data["name"] = $json["fn"];
782 if (!empty($json["addr"])) {
783 $data["addr"] = $json["addr"];
786 if (!empty($json["nick"])) {
787 $data["nick"] = $json["nick"];
790 if (!empty($json["guid"])) {
791 $data["guid"] = $json["guid"];
794 if (!empty($json["comm"])) {
795 $data["community"] = $json["comm"];
798 if (!empty($json["tags"])) {
799 $keywords = implode(" ", $json["tags"]);
800 if ($keywords != "") {
801 $data["keywords"] = $keywords;
805 $location = Profile::formatLocation($json);
807 $data["location"] = $location;
810 if (!empty($json["about"])) {
811 $data["about"] = $json["about"];
814 if (!empty($json["key"])) {
815 $data["pubkey"] = $json["key"];
818 if (!empty($json["photo"])) {
819 $data["photo"] = $json["photo"];
822 if (!empty($json["dfrn-request"])) {
823 $data["request"] = $json["dfrn-request"];
826 if (!empty($json["dfrn-confirm"])) {
827 $data["confirm"] = $json["dfrn-confirm"];
830 if (!empty($json["dfrn-notify"])) {
831 $data["notify"] = $json["dfrn-notify"];
834 if (!empty($json["dfrn-poll"])) {
835 $data["poll"] = $json["dfrn-poll"];
842 * @brief Check for valid DFRN data
844 * @param array $data DFRN data
846 * @return int Number of errors
848 public static function validDfrn($data)
851 if (!isset($data['key'])) {
854 if (!isset($data['dfrn-request'])) {
857 if (!isset($data['dfrn-confirm'])) {
860 if (!isset($data['dfrn-notify'])) {
863 if (!isset($data['dfrn-poll'])) {
870 * @brief Fetch data from a DFRN profile page and via "noscrape"
872 * @param string $profile_link Link to the profile page
874 * @return array profile data
876 public static function profile($profile_link)
880 logger("Check profile ".$profile_link, LOGGER_DEBUG);
882 // Fetch data via noscrape - this is faster
883 $noscrape_url = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile_link);
884 $data = self::pollNoscrape($noscrape_url, $data);
886 if (!isset($data["notify"])
887 || !isset($data["confirm"])
888 || !isset($data["request"])
889 || !isset($data["poll"])
890 || !isset($data["poco"])
891 || !isset($data["name"])
892 || !isset($data["photo"])
894 $data = self::pollHcard($profile_link, $data, true);
897 $prof_data = array();
898 $prof_data["addr"] = $data["addr"];
899 $prof_data["nick"] = $data["nick"];
900 $prof_data["dfrn-request"] = $data["request"];
901 $prof_data["dfrn-confirm"] = $data["confirm"];
902 $prof_data["dfrn-notify"] = $data["notify"];
903 $prof_data["dfrn-poll"] = $data["poll"];
904 $prof_data["dfrn-poco"] = $data["poco"];
905 $prof_data["photo"] = $data["photo"];
906 $prof_data["fn"] = $data["name"];
907 $prof_data["key"] = $data["pubkey"];
909 logger("Result for profile ".$profile_link.": ".print_r($prof_data, true), LOGGER_DEBUG);
915 * @brief Check for DFRN contact
917 * @param array $webfinger Webfinger data
919 * @return array DFRN data
921 private static function dfrn($webfinger)
925 foreach ($webfinger["links"] as $link) {
926 if (($link["rel"] == NAMESPACE_DFRN) && ($link["href"] != "")) {
927 $data["network"] = NETWORK_DFRN;
928 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
929 $data["poll"] = $link["href"];
930 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
931 $data["url"] = $link["href"];
932 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
933 $hcard_url = $link["href"];
934 } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
935 $data["poco"] = $link["href"];
936 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && ($link["href"] != "")) {
937 $data["photo"] = $link["href"];
938 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
939 $data["baseurl"] = trim($link["href"], '/');
940 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
941 $data["guid"] = $link["href"];
942 } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
943 $data["pubkey"] = base64_decode($link["href"]);
945 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
946 if (strstr($data["pubkey"], 'RSA ')) {
947 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
952 if (is_array($webfinger["aliases"])) {
953 foreach ($webfinger["aliases"] as $alias) {
954 if (normalise_link($alias) != normalise_link($data["url"]) && ! strstr($alias, "@")) {
955 $data["alias"] = $alias;
956 } elseif (substr($alias, 0, 5) == 'acct:') {
957 $data["addr"] = substr($alias, 5);
962 if (!isset($data["network"]) || ($hcard_url == "")) {
966 // Fetch data via noscrape - this is faster
967 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
968 $data = self::pollNoscrape($noscrape_url, $data);
970 if (isset($data["notify"])
971 && isset($data["confirm"])
972 && isset($data["request"])
973 && isset($data["poll"])
974 && isset($data["name"])
975 && isset($data["photo"])
980 $data = self::pollHcard($hcard_url, $data, true);
986 * @brief Poll the hcard page (Diaspora and Friendica specific)
988 * @param string $hcard_url Link to the hcard page
989 * @param array $data The already fetched data
990 * @param boolean $dfrn Poll DFRN specific data
992 * @return array hcard data
994 private static function pollHcard($hcard_url, $data, $dfrn = false)
996 $ret = z_fetch_url($hcard_url);
997 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1000 $content = $ret['body'];
1005 $doc = new DOMDocument();
1006 if (!@$doc->loadHTML($content)) {
1010 $xpath = new DomXPath($doc);
1012 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1013 if (!is_object($vcards)) {
1017 if ($vcards->length > 0) {
1018 $vcard = $vcards->item(0);
1020 // We have to discard the guid from the hcard in favour of the guid from lrdd
1021 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1022 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1023 if (($search->length > 0) && ($data["guid"] == "")) {
1024 $data["guid"] = $search->item(0)->nodeValue;
1027 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1028 if ($search->length > 0) {
1029 $data["nick"] = $search->item(0)->nodeValue;
1032 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1033 if ($search->length > 0) {
1034 $data["name"] = $search->item(0)->nodeValue;
1037 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1038 if ($search->length > 0) {
1039 $data["searchable"] = $search->item(0)->nodeValue;
1042 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1043 if ($search->length > 0) {
1044 $data["pubkey"] = $search->item(0)->nodeValue;
1045 if (strstr($data["pubkey"], 'RSA ')) {
1046 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1050 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1051 if ($search->length > 0) {
1052 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1057 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1058 foreach ($photos as $photo) {
1060 foreach ($photo->attributes as $attribute) {
1061 $attr[$attribute->name] = trim($attribute->value);
1064 if (isset($attr["src"]) && isset($attr["width"])) {
1065 $avatar[$attr["width"]] = $attr["src"];
1068 // We don't have a width. So we just take everything that we got.
1069 // This is a Hubzilla workaround which doesn't send a width.
1070 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1071 $avatar[] = $attr["src"];
1075 if (sizeof($avatar)) {
1077 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1081 // Poll DFRN specific data
1082 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1083 if ($search->length > 0) {
1084 foreach ($search as $link) {
1085 //$data["request"] = $search->item(0)->nodeValue;
1087 foreach ($link->attributes as $attribute) {
1088 $attr[$attribute->name] = trim($attribute->value);
1091 $data[substr($attr["rel"], 5)] = $attr["href"];
1095 // Older Friendica versions had used the "uid" field differently than newer versions
1096 if ($data["nick"] == $data["guid"]) {
1097 unset($data["guid"]);
1106 * @brief Check for Diaspora contact
1108 * @param array $webfinger Webfinger data
1110 * @return array Diaspora data
1112 private static function diaspora($webfinger)
1116 foreach ($webfinger["links"] as $link) {
1117 if (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
1118 $hcard_url = $link["href"];
1119 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
1120 $data["baseurl"] = trim($link["href"], '/');
1121 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
1122 $data["guid"] = $link["href"];
1123 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
1124 $data["url"] = $link["href"];
1125 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1126 $data["poll"] = $link["href"];
1127 } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
1128 $data["poco"] = $link["href"];
1129 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1130 $data["notify"] = $link["href"];
1131 } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
1132 $data["pubkey"] = base64_decode($link["href"]);
1134 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1135 if (strstr($data["pubkey"], 'RSA ')) {
1136 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1141 if (!isset($data["url"]) || ($hcard_url == "")) {
1145 if (is_array($webfinger["aliases"])) {
1146 foreach ($webfinger["aliases"] as $alias) {
1147 if (normalise_link($alias) != normalise_link($data["url"]) && ! strstr($alias, "@")) {
1148 $data["alias"] = $alias;
1149 } elseif (substr($alias, 0, 5) == 'acct:') {
1150 $data["addr"] = substr($alias, 5);
1155 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1156 $data["addr"] = substr($webfinger["subject"], 5);
1159 // Fetch further information from the hcard
1160 $data = self::pollHcard($hcard_url, $data);
1166 if (isset($data["url"])
1167 && isset($data["guid"])
1168 && isset($data["baseurl"])
1169 && isset($data["pubkey"])
1170 && ($hcard_url != "")
1172 $data["network"] = NETWORK_DIASPORA;
1174 // The Diaspora handle must always be lowercase
1175 $data["addr"] = strtolower($data["addr"]);
1177 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1178 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1179 $data["batch"] = $data["baseurl"] . "/receive/public";
1188 * @brief Check for OStatus contact
1190 * @param array $webfinger Webfinger data
1191 * @param bool $short Short detection mode
1193 * @return array|bool OStatus data or "false" on error or "true" on short mode
1195 private static function ostatus($webfinger, $short = false)
1199 if (is_array($webfinger["aliases"])) {
1200 foreach ($webfinger["aliases"] as $alias) {
1201 if (strstr($alias, "@") && !strstr(normalise_link($alias), "http://")) {
1202 $data["addr"] = str_replace('acct:', '', $alias);
1207 if (is_string($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1208 && !strstr(normalise_link($webfinger["subject"]), "http://")
1210 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1214 if (is_array($webfinger["links"])) {
1215 foreach ($webfinger["links"] as $link) {
1216 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1217 && ($link["type"] == "text/html")
1218 && ($link["href"] != "")
1220 $data["url"] = $link["href"];
1221 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1222 $data["notify"] = $link["href"];
1223 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1224 $data["poll"] = $link["href"];
1225 } elseif (($link["rel"] == "magic-public-key") && ($link["href"] != "")) {
1226 $pubkey = $link["href"];
1228 if (substr($pubkey, 0, 5) === 'data:') {
1229 if (strstr($pubkey, ',')) {
1230 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1232 $pubkey = substr($pubkey, 5);
1234 } elseif (normalise_link($pubkey) == 'http://') {
1235 $ret = z_fetch_url($pubkey);
1236 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1239 $pubkey = $ret['body'];
1242 $key = explode(".", $pubkey);
1244 if (sizeof($key) >= 3) {
1245 $m = base64url_decode($key[1]);
1246 $e = base64url_decode($key[2]);
1247 $data["pubkey"] = Crypto::meToPem($m, $e);
1253 if (isset($data["notify"]) && isset($data["pubkey"])
1254 && isset($data["poll"])
1255 && isset($data["url"])
1257 $data["network"] = NETWORK_OSTATUS;
1266 // Fetch all additional data from the feed
1267 $ret = z_fetch_url($data["poll"]);
1268 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1271 $feed = $ret['body'];
1272 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1277 if ($feed_data["header"]["author-name"] != "") {
1278 $data["name"] = $feed_data["header"]["author-name"];
1280 if ($feed_data["header"]["author-nick"] != "") {
1281 $data["nick"] = $feed_data["header"]["author-nick"];
1283 if ($feed_data["header"]["author-avatar"] != "") {
1284 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1286 if ($feed_data["header"]["author-id"] != "") {
1287 $data["alias"] = $feed_data["header"]["author-id"];
1289 if ($feed_data["header"]["author-location"] != "") {
1290 $data["location"] = $feed_data["header"]["author-location"];
1292 if ($feed_data["header"]["author-about"] != "") {
1293 $data["about"] = $feed_data["header"]["author-about"];
1295 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1296 // So we take the value that we just fetched, although the other one worked as well
1297 if ($feed_data["header"]["author-link"] != "") {
1298 $data["url"] = $feed_data["header"]["author-link"];
1301 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1302 $data['url'] = $data["alias"];
1303 $data["alias"] = '';
1306 /// @todo Fetch location and "about" from the feed as well
1311 * @brief Fetch data from a pump.io profile page
1313 * @param string $profile_link Link to the profile page
1315 * @return array profile data
1317 private static function pumpioProfileData($profile_link)
1319 $doc = new DOMDocument();
1320 if (!@$doc->loadHTMLFile($profile_link)) {
1324 $xpath = new DomXPath($doc);
1328 // This is ugly - but pump.io doesn't seem to know a better way for it
1329 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1330 $pos = strpos($data["name"], chr(10));
1332 $data["name"] = trim(substr($data["name"], 0, $pos));
1335 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1337 foreach ($avatar->attributes as $attribute) {
1338 if ($attribute->name == "src") {
1339 $data["photo"] = trim($attribute->value);
1344 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
1345 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
1351 * @brief Check for pump.io contact
1353 * @param array $webfinger Webfinger data
1355 * @return array pump.io data
1357 private static function pumpio($webfinger)
1360 foreach ($webfinger["links"] as $link) {
1361 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1362 && ($link["type"] == "text/html")
1363 && ($link["href"] != "")
1365 $data["url"] = $link["href"];
1366 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1367 $data["notify"] = $link["href"];
1368 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1369 $data["poll"] = $link["href"];
1370 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1371 $data["dialback"] = $link["href"];
1374 if (isset($data["poll"]) && isset($data["notify"])
1375 && isset($data["dialback"])
1376 && isset($data["url"])
1378 // by now we use these fields only for the network type detection
1379 // So we unset all data that isn't used at the moment
1380 unset($data["dialback"]);
1382 $data["network"] = NETWORK_PUMPIO;
1387 $profile_data = self::pumpioProfileData($data["url"]);
1389 if (!$profile_data) {
1393 $data = array_merge($data, $profile_data);
1399 * @brief Check page for feed link
1401 * @param string $url Page link
1403 * @return string feed link
1405 private static function getFeedLink($url)
1407 $doc = new DOMDocument();
1409 if (!@$doc->loadHTMLFile($url)) {
1413 $xpath = new DomXPath($doc);
1415 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1416 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1417 if (!is_object($feeds)) {
1421 if ($feeds->length == 0) {
1427 foreach ($feeds as $feed) {
1429 foreach ($feed->attributes as $attribute) {
1430 $attr[$attribute->name] = trim($attribute->value);
1433 if ($feed_url == "") {
1434 $feed_url = $attr["href"];
1442 * @brief Check for feed contact
1444 * @param string $url Profile link
1445 * @param boolean $probe Do a probe if the page contains a feed link
1447 * @return array feed data
1449 private static function feed($url, $probe = true)
1451 $ret = z_fetch_url($url);
1452 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1455 $feed = $ret['body'];
1456 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1463 $feed_url = self::getFeedLink($url);
1469 return self::feed($feed_url, false);
1472 if ($feed_data["header"]["author-name"] != "") {
1473 $data["name"] = $feed_data["header"]["author-name"];
1476 if ($feed_data["header"]["author-nick"] != "") {
1477 $data["nick"] = $feed_data["header"]["author-nick"];
1480 if ($feed_data["header"]["author-avatar"] != "") {
1481 $data["photo"] = $feed_data["header"]["author-avatar"];
1484 if ($feed_data["header"]["author-id"] != "") {
1485 $data["alias"] = $feed_data["header"]["author-id"];
1488 $data["url"] = $url;
1489 $data["poll"] = $url;
1491 if ($feed_data["header"]["author-link"] != "") {
1492 $data["baseurl"] = $feed_data["header"]["author-link"];
1494 $data["baseurl"] = $data["url"];
1497 $data["network"] = NETWORK_FEED;
1503 * @brief Check for mail contact
1505 * @param string $uri Profile link
1506 * @param integer $uid User ID
1508 * @return array mail data
1510 private static function mail($uri, $uid)
1512 if (!validate_email($uri)) {
1517 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1519 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1521 if (DBM::is_result($x) && DBM::is_result($r)) {
1522 $mailbox = Email::constructMailboxName($r[0]);
1524 openssl_private_decrypt(hex2bin($r[0]['pass']), $password, $x[0]['prvkey']);
1525 $mbox = Email::connect($mailbox, $r[0]['user'], $password);
1531 $msgs = Email::poll($mbox, $uri);
1532 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1534 if (!count($msgs)) {
1539 $phost = substr($uri, strpos($uri, '@') + 1);
1542 $data["addr"] = $uri;
1543 $data["network"] = NETWORK_MAIL;
1544 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1545 $data["nick"] = $data["name"];
1546 $data["photo"] = avatar_img($uri);
1547 $data["url"] = 'mailto:'.$uri;
1548 $data["notify"] = 'smtp '.random_string();
1549 $data["poll"] = 'email '.random_string();
1551 $x = Email::messageMeta($mbox, $msgs[0]);
1552 if (stristr($x[0]->from, $uri)) {
1553 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1554 } elseif (stristr($x[0]->to, $uri)) {
1555 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1558 foreach ($adr as $feadr) {
1559 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1560 &&(strcasecmp($feadr->host, $phost) == 0)
1561 && (strlen($feadr->personal))
1563 $personal = imap_mime_header_decode($feadr->personal);
1565 foreach ($personal as $perspart) {
1566 if ($perspart->charset != "default") {
1567 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1569 $data["name"] .= $perspart->text;
1573 $data["name"] = notags($data["name"]);
1577 if (!empty($mbox)) {
1585 * @brief Mix two paths together to possibly fix missing parts
1587 * @param string $avatar Path to the avatar
1588 * @param string $base Another path that is hopefully complete
1590 * @return string fixed avatar path
1592 public static function fixAvatar($avatar, $base)
1594 $base_parts = parse_url($base);
1596 // Remove all parts that could create a problem
1597 unset($base_parts['path']);
1598 unset($base_parts['query']);
1599 unset($base_parts['fragment']);
1601 $avatar_parts = parse_url($avatar);
1604 $parts = array_merge($base_parts, $avatar_parts);
1606 // And put them together again
1607 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1608 $host = isset($parts['host']) ? $parts['host'] : '';
1609 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1610 $path = isset($parts['path']) ? $parts['path'] : '';
1611 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1612 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1614 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1616 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);