3 namespace Friendica\Network;
6 * @file src/Network/Probe.php
7 * @brief Functions for probing URL
12 use Friendica\Core\System;
13 use Friendica\Core\Config;
23 require_once 'include/feed.php';
24 require_once 'include/email.php';
25 require_once 'include/network.php';
28 * @brief This class contain functions for probing URL
33 private static $baseurl;
36 * @brief Rearrange the array so that it always has the same order
38 * @param array $data Unordered data
40 * @return array Ordered data
42 private static function rearrangeData($data) {
43 $fields = array("name", "nick", "guid", "url", "addr", "alias",
44 "photo", "community", "keywords", "location", "about",
45 "batch", "notify", "poll", "request", "confirm", "poco",
46 "priority", "network", "pubkey", "baseurl");
49 foreach ($fields as $field) {
50 if (isset($data[$field])) {
51 $newdata[$field] = $data[$field];
53 $newdata[$field] = "";
57 // We don't use the "priority" field anymore and replace it with a dummy.
58 $newdata["priority"] = 0;
64 * @brief Check if the hostname belongs to the own server
66 * @param string $host The hostname that is to be checked
68 * @return bool Does the testes hostname belongs to the own server?
70 private static function ownHost($host) {
71 $own_host = get_app()->get_hostname();
73 $parts = parse_url($host);
75 if (!isset($parts['scheme'])) {
76 $parts = parse_url('http://'.$host);
79 if (!isset($parts['host'])) {
82 return $parts['host'] == $own_host;
86 * @brief Probes for XRD data
88 * @param string $host The host part of an url
91 * 'lrdd' => Link to LRDD endpoint
92 * 'lrdd-xml' => Link to LRDD endpoint in XML format
93 * 'lrdd-json' => Link to LRDD endpoint in JSON format
95 private static function xrd($host) {
97 // Reset the static variable
100 $ssl_url = "https://".$host."/.well-known/host-meta";
101 $url = "http://".$host."/.well-known/host-meta";
103 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
106 logger("Probing for ".$host, LOGGER_DEBUG);
108 $ret = z_fetch_url($ssl_url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
109 if ($ret['success']) {
111 $xrd = parse_xml_string($xml, false);
114 if (!is_object($xrd)) {
115 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
116 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
117 logger("Probing timeout for ".$url, LOGGER_DEBUG);
121 $xrd = parse_xml_string($xml, false);
123 if (!is_object($xrd)) {
124 logger("No xrd object found for ".$host, LOGGER_DEBUG);
128 $links = xml::element_to_array($xrd);
129 if (!isset($links["xrd"]["link"])) {
130 logger("No xrd data found for ".$host, LOGGER_DEBUG);
136 foreach ($links["xrd"]["link"] as $value => $link) {
137 if (!empty($link["@attributes"])) {
138 $attributes = $link["@attributes"];
139 } elseif ($value == "@attributes") {
145 if (($attributes["rel"] == "lrdd")
146 && ($attributes["type"] == "application/xrd+xml")
148 $xrd_data["lrdd-xml"] = $attributes["template"];
149 } elseif (($attributes["rel"] == "lrdd")
150 && ($attributes["type"] == "application/json")
152 $xrd_data["lrdd-json"] = $attributes["template"];
153 } elseif ($attributes["rel"] == "lrdd") {
154 $xrd_data["lrdd"] = $attributes["template"];
158 self::$baseurl = "http://".$host;
160 logger("Probing successful for ".$host, LOGGER_DEBUG);
166 * @brief Perform Webfinger lookup and return DFRN data
168 * Given an email style address, perform webfinger lookup and
169 * return the resulting DFRN profile URL, or if no DFRN profile URL
170 * is located, returns an OStatus subscription template (prefixed
171 * with the string 'stat:' to identify it as on OStatus template).
172 * If this isn't an email style address just return $webbie.
173 * Return an empty string if email-style addresses but webfinger fails,
174 * or if the resultant personal XRD doesn't contain a supported
175 * subscription/friend-request attribute.
177 * amended 7/9/2011 to return an hcard which could save potentially loading
178 * a lengthy content page to scrape dfrn attributes
180 * @param string $webbie Address that should be probed
181 * @param string $hcard_url Link to the hcard - is returned by reference
183 * @return string profile link
185 public static function webfingerDfrn($webbie, &$hcard_url) {
189 $links = self::lrdd($webbie);
190 logger('webfingerDfrn: '.$webbie.':'.print_r($links, true), LOGGER_DATA);
192 foreach ($links as $link) {
193 if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
194 $profile_link = $link['@attributes']['href'];
196 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) && ($profile_link == "")) {
197 $profile_link = 'stat:'.$link['@attributes']['template'];
199 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
200 $hcard_url = $link['@attributes']['href'];
204 return $profile_link;
208 * @brief Check an URI for LRDD data
210 * this is a replacement for the "lrdd" function in include/network.php.
211 * It isn't used in this class and has some redundancies in the code.
212 * When time comes we can check the existing calls for "lrdd" if we can rework them.
214 * @param string $uri Address that should be probed
216 * @return array uri data
218 public static function lrdd($uri) {
220 $lrdd = self::xrd($uri);
223 if (is_bool($lrdd)) {
228 $parts = @parse_url($uri);
233 $host = $parts["host"];
234 if (!empty($parts["port"])) {
235 $host .= ':'.$parts["port"];
238 $path_parts = explode("/", trim($parts["path"], "/"));
240 $nick = array_pop($path_parts);
243 $lrdd = self::xrd($host);
244 $host .= "/".array_shift($path_parts);
245 } while (!$lrdd && (sizeof($path_parts) > 0));
249 logger("No lrdd data found for ".$uri, LOGGER_DEBUG);
253 foreach ($lrdd as $key => $link) {
258 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
262 $path = str_replace('{uri}', urlencode($uri), $link);
263 $webfinger = self::webfinger($path);
265 if (!$webfinger && (strstr($uri, "@"))) {
266 $path = str_replace('{uri}', urlencode("acct:".$uri), $link);
267 $webfinger = self::webfinger($path);
270 // Special treatment for Mastodon
271 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
272 // But the webfinger for this format fails.
273 if (!$webfinger && !empty($nick)) {
274 // Mastodon uses a "@" as prefix for usernames in their url format
275 $nick = ltrim($nick, '@');
277 $addr = $nick."@".$host;
279 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
280 $webfinger = self::webfinger($path);
284 if (!is_array($webfinger["links"])) {
285 logger("No webfinger links found for ".$uri, LOGGER_DEBUG);
291 foreach ($webfinger["links"] as $link) {
292 $data[] = array("@attributes" => $link);
295 if (is_array($webfinger["aliases"])) {
296 foreach ($webfinger["aliases"] as $alias) {
297 $data[] = array("@attributes" =>
298 array("rel" => "alias",
307 * @brief Fetch information (protocol endpoints and user information) about a given uri
309 * @param string $uri Address that should be probed
310 * @param string $network Test for this specific network
311 * @param integer $uid User ID for the probe (only used for mails)
312 * @param boolean $cache Use cached values?
314 * @return array uri data
316 public static function uri($uri, $network = "", $uid = 0, $cache = true) {
319 $result = Cache::get("probe_url:".$network.":".$uri);
320 if (!is_null($result)) {
329 $data = self::detect($uri, $network, $uid);
331 if (!isset($data["url"])) {
335 if ($data["photo"] != "") {
336 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
338 $data["photo"] = System::baseUrl().'/images/person-175.jpg';
341 if (empty($data["name"])) {
342 if (!empty($data["nick"])) {
343 $data["name"] = $data["nick"];
346 if ($data["name"] == "") {
347 $data["name"] = $data["url"];
351 if (empty($data["nick"])) {
352 $data["nick"] = strtolower($data["name"]);
354 if (strpos($data['nick'], ' ')) {
355 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
359 if (self::$baseurl != "") {
360 $data["baseurl"] = self::$baseurl;
363 if (!isset($data["network"])) {
364 $data["network"] = NETWORK_PHANTOM;
367 $data = self::rearrangeData($data);
369 // Only store into the cache if the value seems to be valid
370 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
371 Cache::set("probe_url:".$network.":".$uri, $data, CACHE_DAY);
373 /// @todo temporary fix - we need a real contact update function that updates only changing fields
374 /// The biggest problem is the avatar picture that could have a reduced image size.
375 /// It should only be updated if the existing picture isn't existing anymore.
376 /// We only update the contact when it is no probing for a specific network.
377 if (($data['network'] != NETWORK_FEED)
385 $fields = array('name' => $data['name'],
386 'nick' => $data['nick'],
387 'url' => $data['url'],
388 'addr' => $data['addr'],
389 'photo' => $data['photo'],
390 'keywords' => $data['keywords'],
391 'location' => $data['location'],
392 'about' => $data['about'],
393 'notify' => $data['notify'],
394 'network' => $data['network'],
395 'server_url' => $data['baseurl']);
397 $fieldnames = array();
399 foreach ($fields AS $key => $val) {
401 unset($fields[$key]);
403 $fieldnames[] = $key;
407 $fields['updated'] = dbm::date();
409 $condition = array('nurl' => normalise_link($data["url"]));
411 $old_fields = dba::select('gcontact', $fieldnames, $condition, array('limit' => 1));
413 dba::update('gcontact', $fields, $condition, $old_fields);
415 $fields = array('name' => $data['name'],
416 'nick' => $data['nick'],
417 'url' => $data['url'],
418 'addr' => $data['addr'],
419 'alias' => $data['alias'],
420 'keywords' => $data['keywords'],
421 'location' => $data['location'],
422 'about' => $data['about'],
423 'batch' => $data['batch'],
424 'notify' => $data['notify'],
425 'poll' => $data['poll'],
426 'request' => $data['request'],
427 'confirm' => $data['confirm'],
428 'poco' => $data['poco'],
429 'network' => $data['network'],
430 'success_update' => dbm::date());
432 $fieldnames = array();
434 foreach ($fields AS $key => $val) {
436 unset($fields[$key]);
438 $fieldnames[] = $key;
442 $condition = array('nurl' => normalise_link($data["url"]), 'self' => false, 'uid' => 0);
444 $old_fields = dba::select('contact', $fieldnames, $condition, array('limit' => 1));
446 dba::update('contact', $fields, $condition, $old_fields);
454 * @brief Switch the scheme of an url between http and https
456 * @param string $url URL
458 * @return string switched URL
460 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
482 * @return array fixed webfinger data
484 private static function fixOstatus($webfinger, $lrdd) {
485 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
492 foreach ($webfinger['links'] as $link) {
493 if ($link['rel'] == NAMESPACE_OSTATUSSUB) {
496 if ($link['rel'] == 'magic-public-key') {
501 if (!$is_ostatus || $has_key) {
505 $url = self::switchScheme($webfinger['subject']);
506 $path = str_replace('{uri}', urlencode($url), $lrdd);
507 $webfinger2 = self::webfinger($path);
509 // Is the new webfinger detectable as OStatus?
510 if (self::ostatus($webfinger2, true)) {
511 $webfinger = $webfinger2;
518 * @brief Fetch information (protocol endpoints and user information) about a given uri
520 * This function is only called by the "uri" function that adds caching and rearranging of data.
522 * @param string $uri Address that should be probed
523 * @param string $network Test for this specific network
524 * @param integer $uid User ID for the probe (only used for mails)
526 * @return array uri data
528 private static function detect($uri, $network, $uid) {
529 $parts = parse_url($uri);
531 if (!empty($parts["scheme"]) && !empty($parts["host"]) && !empty($parts["path"])) {
532 $host = $parts["host"];
533 if (!empty($parts["port"])) {
534 $host .= ':'.$parts["port"];
537 if ($host == 'twitter.com') {
538 return array("network" => NETWORK_TWITTER);
540 $lrdd = self::xrd($host);
542 if (is_bool($lrdd)) {
546 $path_parts = explode("/", trim($parts["path"], "/"));
548 while (!$lrdd && (sizeof($path_parts) > 1)) {
549 $host .= "/".array_shift($path_parts);
550 $lrdd = self::xrd($host);
553 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
554 return self::feed($uri);
556 $nick = array_pop($path_parts);
558 // Mastodon uses a "@" as prefix for usernames in their url format
559 $nick = ltrim($nick, '@');
561 $addr = $nick."@".$host;
563 } elseif (strstr($uri, '@')) {
564 // If the URI starts with "mailto:" then jump directly to the mail detection
565 if (strpos($uri, 'mailto:') !== false) {
566 $uri = str_replace('mailto:', '', $uri);
567 return self::mail($uri, $uid);
570 if ($network == NETWORK_MAIL) {
571 return self::mail($uri, $uid);
573 // Remove "acct:" from the URI
574 $uri = str_replace('acct:', '', $uri);
576 $host = substr($uri, strpos($uri, '@') + 1);
577 $nick = substr($uri, 0, strpos($uri, '@'));
579 if (strpos($uri, '@twitter.com')) {
580 return array("network" => NETWORK_TWITTER);
582 $lrdd = self::xrd($host);
584 if (is_bool($lrdd)) {
589 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
590 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 $key => $link) {
607 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
610 // At first try it with the given uri
611 $path = str_replace('{uri}', urlencode($uri), $link);
612 $webfinger = self::webfinger($path);
614 // Fix possible problems with GNU Social probing to wrong scheme
615 $webfinger = self::fixOstatus($webfinger, $link);
617 // We cannot be sure that the detected address was correct, so we don't use the values
618 if ($webfinger && ($uri != $addr)) {
623 // Try webfinger with the address (user@domain.tld)
625 $path = str_replace('{uri}', urlencode($addr), $link);
626 $webfinger = self::webfinger($path);
629 // Mastodon needs to have it with "acct:"
631 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
632 $webfinger = self::webfinger($path);
636 return self::feed($uri);
641 logger("Probing ".$uri, LOGGER_DEBUG);
643 if (in_array($network, array("", 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
688 * @return array webfinger data
690 private static function webfinger($url) {
692 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
695 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
696 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
699 $data = $ret['body'];
701 // This is a bugfix for this issue: https://github.com/redmatrix/hubzilla/issues/851
702 // $data = str_replace('&url=', '&url=', $data);
703 // we have to decide if we want to create a workaround - or we wait for an update
705 $xrd = parse_xml_string($data, false);
707 if (!is_object($xrd)) {
708 // If it is not XML, maybe it is JSON
709 $webfinger = json_decode($data, true);
711 if (!isset($webfinger["links"])) {
712 logger("No json webfinger links for ".$url, LOGGER_DEBUG);
719 $xrd_arr = xml::element_to_array($xrd);
720 if (!isset($xrd_arr["xrd"]["link"])) {
721 logger("No XML webfinger links for ".$url, LOGGER_DEBUG);
725 $webfinger = array();
727 if (!empty($xrd_arr["xrd"]["subject"])) {
728 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
731 if (!empty($xrd_arr["xrd"]["alias"])) {
732 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
735 $webfinger["links"] = array();
737 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
738 if (!empty($data["@attributes"])) {
739 $attributes = $data["@attributes"];
740 } elseif ($value == "@attributes") {
746 $webfinger["links"][] = $attributes;
752 * @brief Poll the Friendica specific noscrape page.
754 * "noscrape" is a faster alternative to fetch the data from the hcard.
755 * This functionality was originally created for the directory.
757 * @param string $noscrape_url Link to the noscrape page
758 * @param array $data The already fetched data
760 * @return array noscrape data
762 private static function pollNoscrape($noscrape_url, $data) {
763 $ret = z_fetch_url($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["comm"])) {
792 $data["community"] = $json["comm"];
795 if (!empty($json["tags"])) {
796 $keywords = implode(" ", $json["tags"]);
797 if ($keywords != "") {
798 $data["keywords"] = $keywords;
802 $location = formatted_location($json);
804 $data["location"] = $location;
807 if (!empty($json["about"])) {
808 $data["about"] = $json["about"];
811 if (!empty($json["key"])) {
812 $data["pubkey"] = $json["key"];
815 if (!empty($json["photo"])) {
816 $data["photo"] = $json["photo"];
819 if (!empty($json["dfrn-request"])) {
820 $data["request"] = $json["dfrn-request"];
823 if (!empty($json["dfrn-confirm"])) {
824 $data["confirm"] = $json["dfrn-confirm"];
827 if (!empty($json["dfrn-notify"])) {
828 $data["notify"] = $json["dfrn-notify"];
831 if (!empty($json["dfrn-poll"])) {
832 $data["poll"] = $json["dfrn-poll"];
839 * @brief Check for valid DFRN data
841 * @param array $data DFRN data
843 * @return int Number of errors
845 public static function validDfrn($data) {
847 if (!isset($data['key'])) {
850 if (!isset($data['dfrn-request'])) {
853 if (!isset($data['dfrn-confirm'])) {
856 if (!isset($data['dfrn-notify'])) {
859 if (!isset($data['dfrn-poll'])) {
866 * @brief Fetch data from a DFRN profile page and via "noscrape"
868 * @param string $profile_link Link to the profile page
870 * @return array profile data
872 public static function profile($profile_link) {
876 logger("Check profile ".$profile_link, LOGGER_DEBUG);
878 // Fetch data via noscrape - this is faster
879 $noscrape_url = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile_link);
880 $data = self::pollNoscrape($noscrape_url, $data);
882 if (!isset($data["notify"])
883 || !isset($data["confirm"])
884 || !isset($data["request"])
885 || !isset($data["poll"])
886 || !isset($data["poco"])
887 || !isset($data["name"])
888 || !isset($data["photo"])
890 $data = self::pollHcard($profile_link, $data, true);
893 $prof_data = array();
894 $prof_data["addr"] = $data["addr"];
895 $prof_data["nick"] = $data["nick"];
896 $prof_data["dfrn-request"] = $data["request"];
897 $prof_data["dfrn-confirm"] = $data["confirm"];
898 $prof_data["dfrn-notify"] = $data["notify"];
899 $prof_data["dfrn-poll"] = $data["poll"];
900 $prof_data["dfrn-poco"] = $data["poco"];
901 $prof_data["photo"] = $data["photo"];
902 $prof_data["fn"] = $data["name"];
903 $prof_data["key"] = $data["pubkey"];
905 logger("Result for profile ".$profile_link.": ".print_r($prof_data, true), LOGGER_DEBUG);
911 * @brief Check for DFRN contact
913 * @param array $webfinger Webfinger data
915 * @return array DFRN data
917 private static function dfrn($webfinger) {
921 foreach ($webfinger["links"] as $link) {
922 if (($link["rel"] == NAMESPACE_DFRN) && ($link["href"] != "")) {
923 $data["network"] = NETWORK_DFRN;
924 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
925 $data["poll"] = $link["href"];
926 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
927 $data["url"] = $link["href"];
928 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
929 $hcard_url = $link["href"];
930 } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
931 $data["poco"] = $link["href"];
932 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && ($link["href"] != "")) {
933 $data["photo"] = $link["href"];
934 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
935 $data["baseurl"] = trim($link["href"], '/');
936 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
937 $data["guid"] = $link["href"];
938 } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
939 $data["pubkey"] = base64_decode($link["href"]);
941 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
942 if (strstr($data["pubkey"], 'RSA ')) {
943 $data["pubkey"] = rsatopem($data["pubkey"]);
948 if (is_array($webfinger["aliases"])) {
949 foreach ($webfinger["aliases"] as $alias) {
950 if (substr($alias, 0, 5) == 'acct:') {
951 $data["addr"] = substr($alias, 5);
956 if (!isset($data["network"]) || ($hcard_url == "")) {
960 // Fetch data via noscrape - this is faster
961 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
962 $data = self::pollNoscrape($noscrape_url, $data);
964 if (isset($data["notify"])
965 && isset($data["confirm"])
966 && isset($data["request"])
967 && isset($data["poll"])
968 && isset($data["name"])
969 && isset($data["photo"])
974 $data = self::pollHcard($hcard_url, $data, true);
980 * @brief Poll the hcard page (Diaspora and Friendica specific)
982 * @param string $hcard_url Link to the hcard page
983 * @param array $data The already fetched data
984 * @param boolean $dfrn Poll DFRN specific data
986 * @return array hcard data
988 private static function pollHcard($hcard_url, $data, $dfrn = false) {
989 $ret = z_fetch_url($hcard_url);
990 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
993 $content = $ret['body'];
998 $doc = new DOMDocument();
999 if (!@$doc->loadHTML($content)) {
1003 $xpath = new DomXPath($doc);
1005 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1006 if (!is_object($vcards)) {
1010 if ($vcards->length > 0) {
1011 $vcard = $vcards->item(0);
1013 // We have to discard the guid from the hcard in favour of the guid from lrdd
1014 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1015 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1016 if (($search->length > 0) && ($data["guid"] == "")) {
1017 $data["guid"] = $search->item(0)->nodeValue;
1020 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1021 if ($search->length > 0) {
1022 $data["nick"] = $search->item(0)->nodeValue;
1025 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1026 if ($search->length > 0) {
1027 $data["name"] = $search->item(0)->nodeValue;
1030 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1031 if ($search->length > 0) {
1032 $data["searchable"] = $search->item(0)->nodeValue;
1035 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1036 if ($search->length > 0) {
1037 $data["pubkey"] = $search->item(0)->nodeValue;
1038 if (strstr($data["pubkey"], 'RSA ')) {
1039 $data["pubkey"] = rsatopem($data["pubkey"]);
1043 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1044 if ($search->length > 0) {
1045 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1050 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1051 foreach ($photos as $photo) {
1053 foreach ($photo->attributes as $attribute) {
1054 $attr[$attribute->name] = trim($attribute->value);
1057 if (isset($attr["src"]) && isset($attr["width"])) {
1058 $avatar[$attr["width"]] = $attr["src"];
1061 // We don't have a width. So we just take everything that we got.
1062 // This is a Hubzilla workaround which doesn't send a width.
1063 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1064 $avatar[] = $attr["src"];
1068 if (sizeof($avatar)) {
1070 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1074 // Poll DFRN specific data
1075 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1076 if ($search->length > 0) {
1077 foreach ($search as $link) {
1078 //$data["request"] = $search->item(0)->nodeValue;
1080 foreach ($link->attributes as $attribute) {
1081 $attr[$attribute->name] = trim($attribute->value);
1084 $data[substr($attr["rel"], 5)] = $attr["href"];
1088 // Older Friendica versions had used the "uid" field differently than newer versions
1089 if ($data["nick"] == $data["guid"]) {
1090 unset($data["guid"]);
1099 * @brief Check for Diaspora contact
1101 * @param array $webfinger Webfinger data
1103 * @return array Diaspora data
1105 private static function diaspora($webfinger) {
1109 foreach ($webfinger["links"] as $link) {
1110 if (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
1111 $hcard_url = $link["href"];
1112 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
1113 $data["baseurl"] = trim($link["href"], '/');
1114 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
1115 $data["guid"] = $link["href"];
1116 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
1117 $data["url"] = $link["href"];
1118 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1119 $data["poll"] = $link["href"];
1120 } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
1121 $data["poco"] = $link["href"];
1122 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1123 $data["notify"] = $link["href"];
1124 } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
1125 $data["pubkey"] = base64_decode($link["href"]);
1127 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1128 if (strstr($data["pubkey"], 'RSA ')) {
1129 $data["pubkey"] = rsatopem($data["pubkey"]);
1134 if (!isset($data["url"]) || ($hcard_url == "")) {
1138 if (is_array($webfinger["aliases"])) {
1139 foreach ($webfinger["aliases"] as $alias) {
1140 if (normalise_link($alias) != normalise_link($data["url"]) && ! strstr($alias, "@")) {
1141 $data["alias"] = $alias;
1146 // Fetch further information from the hcard
1147 $data = self::pollHcard($hcard_url, $data);
1153 if (isset($data["url"])
1154 && isset($data["guid"])
1155 && isset($data["baseurl"])
1156 && isset($data["pubkey"])
1157 && ($hcard_url != "")
1159 $data["network"] = NETWORK_DIASPORA;
1161 // The Diaspora handle must always be lowercase
1162 $data["addr"] = strtolower($data["addr"]);
1164 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1165 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1166 $data["batch"] = $data["baseurl"] . "/receive/public";
1175 * @brief Check for OStatus contact
1177 * @param array $webfinger Webfinger data
1178 * @param bool $short Short detection mode
1180 * @return array|bool OStatus data or "false" on error or "true" on short mode
1182 private static function ostatus($webfinger, $short = false) {
1184 if (is_array($webfinger["aliases"])) {
1185 foreach ($webfinger["aliases"] as $alias) {
1186 if (strstr($alias, "@")) {
1187 $data["addr"] = str_replace('acct:', '', $alias);
1192 if (is_string($webfinger["subject"]) && strstr($webfinger["subject"], "@")) {
1193 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1196 if (is_array($webfinger["links"])) {
1197 foreach ($webfinger["links"] as $link) {
1198 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1199 && ($link["type"] == "text/html")
1200 && ($link["href"] != "")
1202 $data["url"] = $link["href"];
1203 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1204 $data["notify"] = $link["href"];
1205 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1206 $data["poll"] = $link["href"];
1207 } elseif (($link["rel"] == "magic-public-key") && ($link["href"] != "")) {
1208 $pubkey = $link["href"];
1210 if (substr($pubkey, 0, 5) === 'data:') {
1211 if (strstr($pubkey, ',')) {
1212 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1214 $pubkey = substr($pubkey, 5);
1216 } elseif (normalise_link($pubkey) == 'http://') {
1217 $ret = z_fetch_url($pubkey);
1218 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1221 $pubkey = $ret['body'];
1224 $key = explode(".", $pubkey);
1226 if (sizeof($key) >= 3) {
1227 $m = base64url_decode($key[1]);
1228 $e = base64url_decode($key[2]);
1229 $data["pubkey"] = metopem($m, $e);
1235 if (isset($data["notify"]) && isset($data["pubkey"])
1236 && isset($data["poll"])
1237 && isset($data["url"])
1239 $data["network"] = NETWORK_OSTATUS;
1248 // Fetch all additional data from the feed
1249 $ret = z_fetch_url($data["poll"]);
1250 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1253 $feed = $ret['body'];
1254 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1259 if ($feed_data["header"]["author-name"] != "") {
1260 $data["name"] = $feed_data["header"]["author-name"];
1262 if ($feed_data["header"]["author-nick"] != "") {
1263 $data["nick"] = $feed_data["header"]["author-nick"];
1265 if ($feed_data["header"]["author-avatar"] != "") {
1266 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1268 if ($feed_data["header"]["author-id"] != "") {
1269 $data["alias"] = $feed_data["header"]["author-id"];
1271 if ($feed_data["header"]["author-location"] != "") {
1272 $data["location"] = $feed_data["header"]["author-location"];
1274 if ($feed_data["header"]["author-about"] != "") {
1275 $data["about"] = $feed_data["header"]["author-about"];
1277 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1278 // So we take the value that we just fetched, although the other one worked as well
1279 if ($feed_data["header"]["author-link"] != "") {
1280 $data["url"] = $feed_data["header"]["author-link"];
1283 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1284 $data['url'] = $data["alias"];
1285 $data["alias"] = '';
1288 /// @todo Fetch location and "about" from the feed as well
1293 * @brief Fetch data from a pump.io profile page
1295 * @param string $profile_link Link to the profile page
1297 * @return array profile data
1299 private static function pumpioProfileData($profile_link) {
1301 $doc = new DOMDocument();
1302 if (!@$doc->loadHTMLFile($profile_link)) {
1306 $xpath = new DomXPath($doc);
1310 // This is ugly - but pump.io doesn't seem to know a better way for it
1311 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1312 $pos = strpos($data["name"], chr(10));
1314 $data["name"] = trim(substr($data["name"], 0, $pos));
1317 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1319 foreach ($avatar->attributes as $attribute) {
1320 if ($attribute->name == "src") {
1321 $data["photo"] = trim($attribute->value);
1326 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
1327 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
1333 * @brief Check for pump.io contact
1335 * @param array $webfinger Webfinger data
1337 * @return array pump.io data
1339 private static function pumpio($webfinger) {
1342 foreach ($webfinger["links"] as $link) {
1343 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1344 && ($link["type"] == "text/html")
1345 && ($link["href"] != "")
1347 $data["url"] = $link["href"];
1348 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1349 $data["notify"] = $link["href"];
1350 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1351 $data["poll"] = $link["href"];
1352 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1353 $data["dialback"] = $link["href"];
1356 if (isset($data["poll"]) && isset($data["notify"])
1357 && isset($data["dialback"])
1358 && isset($data["url"])
1360 // by now we use these fields only for the network type detection
1361 // So we unset all data that isn't used at the moment
1362 unset($data["dialback"]);
1364 $data["network"] = NETWORK_PUMPIO;
1369 $profile_data = self::pumpioProfileData($data["url"]);
1371 if (!$profile_data) {
1375 $data = array_merge($data, $profile_data);
1381 * @brief Check page for feed link
1383 * @param string $url Page link
1385 * @return string feed link
1387 private static function getFeedLink($url) {
1388 $doc = new DOMDocument();
1390 if (!@$doc->loadHTMLFile($url)) {
1394 $xpath = new DomXPath($doc);
1396 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1397 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1398 if (!is_object($feeds)) {
1402 if ($feeds->length == 0) {
1408 foreach ($feeds as $feed) {
1410 foreach ($feed->attributes as $attribute) {
1411 $attr[$attribute->name] = trim($attribute->value);
1414 if ($feed_url == "") {
1415 $feed_url = $attr["href"];
1423 * @brief Check for feed contact
1425 * @param string $url Profile link
1426 * @param boolean $probe Do a probe if the page contains a feed link
1428 * @return array feed data
1430 private static function feed($url, $probe = true) {
1431 $ret = z_fetch_url($url);
1432 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1435 $feed = $ret['body'];
1436 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1443 $feed_url = self::getFeedLink($url);
1449 return self::feed($feed_url, false);
1452 if ($feed_data["header"]["author-name"] != "") {
1453 $data["name"] = $feed_data["header"]["author-name"];
1456 if ($feed_data["header"]["author-nick"] != "") {
1457 $data["nick"] = $feed_data["header"]["author-nick"];
1460 if ($feed_data["header"]["author-avatar"] != "") {
1461 $data["photo"] = $feed_data["header"]["author-avatar"];
1464 if ($feed_data["header"]["author-id"] != "") {
1465 $data["alias"] = $feed_data["header"]["author-id"];
1468 $data["url"] = $url;
1469 $data["poll"] = $url;
1471 if ($feed_data["header"]["author-link"] != "") {
1472 $data["baseurl"] = $feed_data["header"]["author-link"];
1474 $data["baseurl"] = $data["url"];
1477 $data["network"] = NETWORK_FEED;
1483 * @brief Check for mail contact
1485 * @param string $uri Profile link
1486 * @param integer $uid User ID
1488 * @return array mail data
1490 private static function mail($uri, $uid) {
1492 if (!validate_email($uri)) {
1496 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1498 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1500 if (dbm::is_result($x) && dbm::is_result($r)) {
1501 $mailbox = construct_mailbox_name($r[0]);
1503 openssl_private_decrypt(hex2bin($r[0]['pass']), $password, $x[0]['prvkey']);
1504 $mbox = email_connect($mailbox, $r[0]['user'], $password);
1510 $msgs = email_poll($mbox, $uri);
1511 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1513 if (!count($msgs)) {
1517 $phost = substr($uri, strpos($uri, '@') + 1);
1520 $data["addr"] = $uri;
1521 $data["network"] = NETWORK_MAIL;
1522 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1523 $data["nick"] = $data["name"];
1524 $data["photo"] = avatar_img($uri);
1525 $data["url"] = 'http://'.$phost."/".$data["nick"];
1526 $data["notify"] = 'smtp '.random_string();
1527 $data["poll"] = 'email '.random_string();
1529 $x = email_msg_meta($mbox, $msgs[0]);
1530 if (stristr($x[0]->from, $uri)) {
1531 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1532 } elseif (stristr($x[0]->to, $uri)) {
1533 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1536 foreach ($adr as $feadr) {
1537 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1538 &&(strcasecmp($feadr->host, $phost) == 0)
1539 && (strlen($feadr->personal))
1541 $personal = imap_mime_header_decode($feadr->personal);
1543 foreach ($personal as $perspart) {
1544 if ($perspart->charset != "default") {
1545 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1547 $data["name"] .= $perspart->text;
1551 $data["name"] = notags($data["name"]);
1561 * @brief Mix two paths together to possibly fix missing parts
1563 * @param string $avatar Path to the avatar
1564 * @param string $base Another path that is hopefully complete
1566 * @return string fixed avatar path
1568 public static function fixAvatar($avatar, $base) {
1569 $base_parts = parse_url($base);
1571 // Remove all parts that could create a problem
1572 unset($base_parts['path']);
1573 unset($base_parts['query']);
1574 unset($base_parts['fragment']);
1576 $avatar_parts = parse_url($avatar);
1579 $parts = array_merge($base_parts, $avatar_parts);
1581 // And put them together again
1582 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1583 $host = isset($parts['host']) ? $parts['host'] : '';
1584 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1585 $path = isset($parts['path']) ? $parts['path'] : '';
1586 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1587 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1589 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1591 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);