3 * @file include/Probe.php
4 * @brief Functions for probing URL
8 use \Friendica\Core\Config;
9 use \Friendica\Core\PConfig;
11 require_once("include/feed.php");
12 require_once('include/email.php');
13 require_once('include/network.php');
16 * @brief This class contain functions for probing URL
22 * @brief Rearrange the array so that it always has the same order
24 * @param array $data Unordered data
26 * @return array Ordered data
28 private function rearrange_data($data) {
29 $fields = array("name", "nick", "guid", "url", "addr", "alias",
30 "photo", "community", "keywords", "location", "about",
31 "batch", "notify", "poll", "request", "confirm", "poco",
32 "priority", "network", "pubkey", "baseurl");
35 foreach ($fields AS $field)
36 if (isset($data[$field]))
37 $newdata[$field] = $data[$field];
39 $newdata[$field] = "";
41 // We don't use the "priority" field anymore and replace it with a dummy.
42 $newdata["priority"] = 0;
48 * @brief Probes for XRD data
51 * 'lrdd' => Link to LRDD endpoint
52 * 'lrdd-xml' => Link to LRDD endpoint in XML format
53 * 'lrdd-json' => Link to LRDD endpoint in JSON format
55 private function xrd($host) {
57 $ssl_url = "https://".$host."/.well-known/host-meta";
58 $url = "http://".$host."/.well-known/host-meta";
60 $xrd_timeout = Config::get('system','xrd_timeout', 20);
63 $ret = z_fetch_url($ssl_url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
64 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
69 $xrd = parse_xml_string($xml, false);
71 if (!is_object($xrd)) {
72 $xml = fetch_url($url, false, $redirects, $xrd_timeout, "application/xrd+xml");
73 $xrd = parse_xml_string($xml, false);
78 $links = xml::element_to_array($xrd);
79 if (!isset($links["xrd"]["link"]))
84 foreach ($links["xrd"]["link"] AS $value => $link) {
85 if (isset($link["@attributes"]))
86 $attributes = $link["@attributes"];
87 elseif ($value == "@attributes")
92 if (($attributes["rel"] == "lrdd") AND
93 ($attributes["type"] == "application/xrd+xml"))
94 $xrd_data["lrdd-xml"] = $attributes["template"];
95 elseif (($attributes["rel"] == "lrdd") AND
96 ($attributes["type"] == "application/json"))
97 $xrd_data["lrdd-json"] = $attributes["template"];
98 elseif ($attributes["rel"] == "lrdd")
99 $xrd_data["lrdd"] = $attributes["template"];
105 * @brief Perform Webfinger lookup and return DFRN data
107 * Given an email style address, perform webfinger lookup and
108 * return the resulting DFRN profile URL, or if no DFRN profile URL
109 * is located, returns an OStatus subscription template (prefixed
110 * with the string 'stat:' to identify it as on OStatus template).
111 * If this isn't an email style address just return $webbie.
112 * Return an empty string if email-style addresses but webfinger fails,
113 * or if the resultant personal XRD doesn't contain a supported
114 * subscription/friend-request attribute.
116 * amended 7/9/2011 to return an hcard which could save potentially loading
117 * a lengthy content page to scrape dfrn attributes
119 * @param string $webbie Address that should be probed
120 * @param string $hcard Link to the hcard - is returned by reference
122 * @return string profile link
125 public static function webfinger_dfrn($webbie, &$hcard) {
129 $links = self::lrdd($webbie);
130 logger('webfinger_dfrn: '.$webbie.':'.print_r($links,true), LOGGER_DATA);
132 foreach ($links as $link) {
133 if ($link['@attributes']['rel'] === NAMESPACE_DFRN)
134 $profile_link = $link['@attributes']['href'];
135 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) AND ($profile_link == ""))
136 $profile_link = 'stat:'.$link['@attributes']['template'];
137 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
138 $hcard = $link['@attributes']['href'];
141 return $profile_link;
145 * @brief Check an URI for LRDD data
147 * this is a replacement for the "lrdd" function in include/network.php.
148 * It isn't used in this class and has some redundancies in the code.
149 * When time comes we can check the existing calls for "lrdd" if we can rework them.
151 * @param string $uri Address that should be probed
153 * @return array uri data
155 public static function lrdd($uri) {
157 $lrdd = self::xrd($uri);
160 $parts = @parse_url($uri);
164 $host = $parts["host"];
166 $path_parts = explode("/", trim($parts["path"], "/"));
169 $lrdd = self::xrd($host);
170 $host .= "/".array_shift($path_parts);
171 } while (!$lrdd AND (sizeof($path_parts) > 0));
177 foreach ($lrdd AS $key => $link) {
181 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json")))
184 $path = str_replace('{uri}', urlencode($uri), $link);
185 $webfinger = self::webfinger($path);
187 if (!$webfinger AND (strstr($uri, "@"))) {
188 $path = str_replace('{uri}', urlencode("acct:".$uri), $link);
189 $webfinger = self::webfinger($path);
193 if (!is_array($webfinger["links"]))
198 foreach ($webfinger["links"] AS $link)
199 $data[] = array("@attributes" => $link);
201 if (is_array($webfinger["aliases"]))
202 foreach ($webfinger["aliases"] AS $alias)
203 $data[] = array("@attributes" =>
204 array("rel" => "alias",
211 * @brief Fetch information (protocol endpoints and user information) about a given uri
213 * @param string $uri Address that should be probed
214 * @param string $network Test for this specific network
215 * @param integer $uid User ID for the probe (only used for mails)
216 * @param boolean $cache Use cached values?
218 * @return array uri data
220 public static function uri($uri, $network = "", $uid = 0, $cache = true) {
223 $result = Cache::get("probe_url:".$network.":".$uri);
224 if (!is_null($result)) {
232 $data = self::detect($uri, $network, $uid);
234 if (!isset($data["url"]))
237 if ($data["photo"] != "")
238 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
240 $data["photo"] = App::get_baseurl().'/images/person-175.jpg';
242 if (!isset($data["name"]) OR ($data["name"] == "")) {
243 if (isset($data["nick"]))
244 $data["name"] = $data["nick"];
246 if ($data["name"] == "")
247 $data["name"] = $data["url"];
250 if (!isset($data["nick"]) OR ($data["nick"] == "")) {
251 $data["nick"] = strtolower($data["name"]);
253 if (strpos($data['nick'], ' '))
254 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
257 if (!isset($data["network"]))
258 $data["network"] = NETWORK_PHANTOM;
260 $data = self::rearrange_data($data);
262 // Only store into the cache if the value seems to be valid
263 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
264 Cache::set("probe_url:".$network.":".$uri, $data, CACHE_DAY);
266 /// @todo temporary fix - we need a real contact update function that updates only changing fields
267 /// The biggest problem is the avatar picture that could have a reduced image size.
268 /// It should only be updated if the existing picture isn't existing anymore.
269 if (($data['network'] != NETWORK_FEED) AND ($mode == PROBE_NORMAL) AND
270 $data["name"] AND $data["nick"] AND $data["url"] AND $data["addr"] AND $data["poll"])
271 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `url` = '%s', `addr` = '%s',
272 `notify` = '%s', `poll` = '%s', `alias` = '%s', `success_update` = '%s'
273 WHERE `nurl` = '%s' AND NOT `self` AND `uid` = 0",
274 dbesc($data["name"]),
275 dbesc($data["nick"]),
277 dbesc($data["addr"]),
278 dbesc($data["notify"]),
279 dbesc($data["poll"]),
280 dbesc($data["alias"]),
281 dbesc(datetime_convert()),
282 dbesc(normalise_link($data['url']))
289 * @brief Fetch information (protocol endpoints and user information) about a given uri
291 * This function is only called by the "uri" function that adds caching and rearranging of data.
293 * @param string $uri Address that should be probed
294 * @param string $network Test for this specific network
295 * @param integer $uid User ID for the probe (only used for mails)
297 * @return array uri data
299 private function detect($uri, $network, $uid) {
300 if (strstr($uri, '@')) {
301 // If the URI starts with "mailto:" then jump directly to the mail detection
302 if (strpos($url,'mailto:') !== false) {
303 $uri = str_replace('mailto:', '', $url);
304 return self::mail($uri, $uid);
307 if ($network == NETWORK_MAIL)
308 return self::mail($uri, $uid);
310 // Remove "acct:" from the URI
311 $uri = str_replace('acct:', '', $uri);
313 $host = substr($uri,strpos($uri, '@') + 1);
314 $nick = substr($uri,0, strpos($uri, '@'));
316 if (strpos($uri, '@twitter.com'))
317 return array("network" => NETWORK_TWITTER);
319 $lrdd = self::xrd($host);
322 return self::mail($uri, $uid);
326 $parts = parse_url($uri);
327 if (!isset($parts["scheme"]) OR
328 !isset($parts["host"]) OR
329 !isset($parts["path"]))
333 $host = $parts["host"];
335 if ($host == 'twitter.com')
336 return array("network" => NETWORK_TWITTER);
338 $lrdd = self::xrd($host);
340 $path_parts = explode("/", trim($parts["path"], "/"));
342 while (!$lrdd AND (sizeof($path_parts) > 1)) {
343 $host .= "/".array_shift($path_parts);
344 $lrdd = self::xrd($host);
347 return self::feed($uri);
349 $nick = array_pop($path_parts);
350 $addr = $nick."@".$host;
354 /// @todo Do we need the prefix "acct:" or "acct://"?
356 foreach ($lrdd AS $key => $link) {
360 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json")))
363 // Try webfinger with the address (user@domain.tld)
364 $path = str_replace('{uri}', urlencode($addr), $link);
365 $webfinger = self::webfinger($path);
367 // Mastodon needs to have it with "acct:"
369 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
370 $webfinger = self::webfinger($path);
373 // If webfinger wasn't successful then try it with the URL - possibly in the format https://...
374 if (!$webfinger AND ($uri != $addr)) {
375 $path = str_replace('{uri}', urlencode($uri), $link);
376 $webfinger = self::webfinger($path);
378 // Since the detection with the address wasn't successful, we delete it.
387 return self::feed($uri);
391 logger("Probing ".$uri, LOGGER_DEBUG);
393 if (in_array($network, array("", NETWORK_DFRN)))
394 $result = self::dfrn($webfinger);
395 if ((!$result AND ($network == "")) OR ($network == NETWORK_DIASPORA))
396 $result = self::diaspora($webfinger);
397 if ((!$result AND ($network == "")) OR ($network == NETWORK_OSTATUS))
398 $result = self::ostatus($webfinger);
399 if ((!$result AND ($network == "")) OR ($network == NETWORK_PUMPIO))
400 $result = self::pumpio($webfinger);
401 if ((!$result AND ($network == "")) OR ($network == NETWORK_FEED))
402 $result = self::feed($uri);
404 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
405 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
406 if ((!isset($result["nick"]) OR ($result["nick"] == "") OR (strstr($result["nick"], " "))) AND ($nick != ""))
407 $result["nick"] = $nick;
409 if ((!isset($result["addr"]) OR ($result["addr"] == "")) AND ($addr != ""))
410 $result["addr"] = $addr;
413 logger($uri." is ".$result["network"], LOGGER_DEBUG);
415 if (!isset($result["baseurl"]) OR ($result["baseurl"] == "")) {
416 $pos = strpos($result["url"], $host);
418 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
425 * @brief Perform a webfinger request.
427 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
429 * @param string $url Address that should be probed
431 * @return array webfinger data
433 private function webfinger($url) {
435 $xrd_timeout = Config::get('system','xrd_timeout', 20);
438 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
439 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
442 $data = $ret['body'];
444 $xrd = parse_xml_string($data, false);
446 if (!is_object($xrd)) {
447 // If it is not XML, maybe it is JSON
448 $webfinger = json_decode($data, true);
450 if (!isset($webfinger["links"]))
456 $xrd_arr = xml::element_to_array($xrd);
457 if (!isset($xrd_arr["xrd"]["link"]))
460 $webfinger = array();
462 if (isset($xrd_arr["xrd"]["subject"]))
463 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
465 if (isset($xrd_arr["xrd"]["alias"]))
466 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
468 $webfinger["links"] = array();
470 foreach ($xrd_arr["xrd"]["link"] AS $value => $data) {
471 if (isset($data["@attributes"]))
472 $attributes = $data["@attributes"];
473 elseif ($value == "@attributes")
478 $webfinger["links"][] = $attributes;
484 * @brief Poll the Friendica specific noscrape page.
486 * "noscrape" is a faster alternative to fetch the data from the hcard.
487 * This functionality was originally created for the directory.
489 * @param string $noscrape Link to the noscrape page
490 * @param array $data The already fetched data
492 * @return array noscrape data
494 private function poll_noscrape($noscrape, $data) {
495 $ret = z_fetch_url($noscrape);
496 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
499 $content = $ret['body'];
504 $json = json_decode($content, true);
505 if (!is_array($json))
508 if (isset($json["fn"]))
509 $data["name"] = $json["fn"];
511 if (isset($json["addr"]))
512 $data["addr"] = $json["addr"];
514 if (isset($json["nick"]))
515 $data["nick"] = $json["nick"];
517 if (isset($json["comm"]))
518 $data["community"] = $json["comm"];
520 if (isset($json["tags"])) {
521 $keywords = implode(" ", $json["tags"]);
523 $data["keywords"] = $keywords;
526 $location = formatted_location($json);
528 $data["location"] = $location;
530 if (isset($json["about"]))
531 $data["about"] = $json["about"];
533 if (isset($json["key"]))
534 $data["pubkey"] = $json["key"];
536 if (isset($json["photo"]))
537 $data["photo"] = $json["photo"];
539 if (isset($json["dfrn-request"]))
540 $data["request"] = $json["dfrn-request"];
542 if (isset($json["dfrn-confirm"]))
543 $data["confirm"] = $json["dfrn-confirm"];
545 if (isset($json["dfrn-notify"]))
546 $data["notify"] = $json["dfrn-notify"];
548 if (isset($json["dfrn-poll"]))
549 $data["poll"] = $json["dfrn-poll"];
555 * @brief Check for valid DFRN data
557 * @param array $data DFRN data
559 * @return int Number of errors
561 public static function valid_dfrn($data) {
563 if(!isset($data['key']))
565 if(!isset($data['dfrn-request']))
567 if(!isset($data['dfrn-confirm']))
569 if(!isset($data['dfrn-notify']))
571 if(!isset($data['dfrn-poll']))
577 * @brief Fetch data from a DFRN profile page and via "noscrape"
579 * @param string $profile Link to the profile page
581 * @return array profile data
583 public static function profile($profile) {
587 logger("Check profile ".$profile, LOGGER_DEBUG);
589 // Fetch data via noscrape - this is faster
590 $noscrape = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile);
591 $data = self::poll_noscrape($noscrape, $data);
593 if (!isset($data["notify"]) OR !isset($data["confirm"]) OR
594 !isset($data["request"]) OR !isset($data["poll"]) OR
595 !isset($data["poco"]) OR !isset($data["name"]) OR
596 !isset($data["photo"]))
597 $data = self::poll_hcard($profile, $data, true);
599 $prof_data = array();
600 $prof_data["addr"] = $data["addr"];
601 $prof_data["nick"] = $data["nick"];
602 $prof_data["dfrn-request"] = $data["request"];
603 $prof_data["dfrn-confirm"] = $data["confirm"];
604 $prof_data["dfrn-notify"] = $data["notify"];
605 $prof_data["dfrn-poll"] = $data["poll"];
606 $prof_data["dfrn-poco"] = $data["poco"];
607 $prof_data["photo"] = $data["photo"];
608 $prof_data["fn"] = $data["name"];
609 $prof_data["key"] = $data["pubkey"];
611 logger("Result for profile ".$profile.": ".print_r($prof_data, true), LOGGER_DEBUG);
617 * @brief Check for DFRN contact
619 * @param array $webfinger Webfinger data
621 * @return array DFRN data
623 private function dfrn($webfinger) {
627 foreach ($webfinger["links"] AS $link) {
628 if (($link["rel"] == NAMESPACE_DFRN) AND ($link["href"] != ""))
629 $data["network"] = NETWORK_DFRN;
630 elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
631 $data["poll"] = $link["href"];
632 elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
633 ($link["type"] == "text/html") AND ($link["href"] != ""))
634 $data["url"] = $link["href"];
635 elseif (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != ""))
636 $hcard = $link["href"];
637 elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != ""))
638 $data["poco"] = $link["href"];
639 elseif (($link["rel"] == "http://webfinger.net/rel/avatar") AND ($link["href"] != ""))
640 $data["photo"] = $link["href"];
642 elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != ""))
643 $data["baseurl"] = trim($link["href"], '/');
644 elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != ""))
645 $data["guid"] = $link["href"];
646 elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
647 $data["pubkey"] = base64_decode($link["href"]);
649 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
650 if (strstr($data["pubkey"], 'RSA '))
651 $data["pubkey"] = rsatopem($data["pubkey"]);
655 if (!isset($data["network"]) OR ($hcard == ""))
658 // Fetch data via noscrape - this is faster
659 $noscrape = str_replace("/hcard/", "/noscrape/", $hcard);
660 $data = self::poll_noscrape($noscrape, $data);
662 if (isset($data["notify"]) AND isset($data["confirm"]) AND isset($data["request"]) AND
663 isset($data["poll"]) AND isset($data["name"]) AND isset($data["photo"]))
666 $data = self::poll_hcard($hcard, $data, true);
672 * @brief Poll the hcard page (Diaspora and Friendica specific)
674 * @param string $hcard Link to the hcard page
675 * @param array $data The already fetched data
676 * @param boolean $dfrn Poll DFRN specific data
678 * @return array hcard data
680 private function poll_hcard($hcard, $data, $dfrn = false) {
681 $ret = z_fetch_url($hcard);
682 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
685 $content = $ret['body'];
690 $doc = new DOMDocument();
691 if (!@$doc->loadHTML($content))
694 $xpath = new DomXPath($doc);
696 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
697 if (!is_object($vcards))
700 if ($vcards->length > 0) {
701 $vcard = $vcards->item(0);
703 // We have to discard the guid from the hcard in favour of the guid from lrdd
704 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
705 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
706 if (($search->length > 0) AND ($data["guid"] == ""))
707 $data["guid"] = $search->item(0)->nodeValue;
709 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
710 if ($search->length > 0)
711 $data["nick"] = $search->item(0)->nodeValue;
713 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
714 if ($search->length > 0)
715 $data["name"] = $search->item(0)->nodeValue;
717 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
718 if ($search->length > 0)
719 $data["searchable"] = $search->item(0)->nodeValue;
721 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
722 if ($search->length > 0) {
723 $data["pubkey"] = $search->item(0)->nodeValue;
724 if (strstr($data["pubkey"], 'RSA '))
725 $data["pubkey"] = rsatopem($data["pubkey"]);
728 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
729 if ($search->length > 0)
730 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
734 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
735 foreach ($photos AS $photo) {
737 foreach ($photo->attributes as $attribute) {
738 $attr[$attribute->name] = trim($attribute->value);
741 if (isset($attr["src"]) AND isset($attr["width"])) {
742 $avatar[$attr["width"]] = $attr["src"];
745 // We don't have a width. So we just take everything that we got.
746 // This is a Hubzilla workaround which doesn't send a width.
747 if ((sizeof($avatar) == 0) AND isset($attr["src"])) {
748 $avatar[] = $attr["src"];
752 if (sizeof($avatar)) {
754 $data["photo"] = array_pop($avatar);
758 // Poll DFRN specific data
759 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
760 if ($search->length > 0) {
761 foreach ($search AS $link) {
762 //$data["request"] = $search->item(0)->nodeValue;
764 foreach ($link->attributes as $attribute)
765 $attr[$attribute->name] = trim($attribute->value);
767 $data[substr($attr["rel"], 5)] = $attr["href"];
771 // Older Friendica versions had used the "uid" field differently than newer versions
772 if ($data["nick"] == $data["guid"])
773 unset($data["guid"]);
781 * @brief Check for Diaspora contact
783 * @param array $webfinger Webfinger data
785 * @return array Diaspora data
787 private function diaspora($webfinger) {
791 foreach ($webfinger["links"] AS $link) {
792 if (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != ""))
793 $hcard = $link["href"];
794 elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != ""))
795 $data["baseurl"] = trim($link["href"], '/');
796 elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != ""))
797 $data["guid"] = $link["href"];
798 elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
799 ($link["type"] == "text/html") AND ($link["href"] != ""))
800 $data["url"] = $link["href"];
801 elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
802 $data["poll"] = $link["href"];
803 elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != ""))
804 $data["poco"] = $link["href"];
805 elseif (($link["rel"] == "salmon") AND ($link["href"] != ""))
806 $data["notify"] = $link["href"];
807 elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
808 $data["pubkey"] = base64_decode($link["href"]);
810 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
811 if (strstr($data["pubkey"], 'RSA '))
812 $data["pubkey"] = rsatopem($data["pubkey"]);
816 if (!isset($data["url"]) OR ($hcard == ""))
819 if (is_array($webfinger["aliases"]))
820 foreach ($webfinger["aliases"] AS $alias)
821 if (normalise_link($alias) != normalise_link($data["url"]) AND !strstr($alias, "@"))
822 $data["alias"] = $alias;
824 // Fetch further information from the hcard
825 $data = self::poll_hcard($hcard, $data);
830 if (isset($data["url"]) AND isset($data["guid"]) AND isset($data["baseurl"]) AND
831 isset($data["pubkey"]) AND ($hcard != "")) {
832 $data["network"] = NETWORK_DIASPORA;
834 // The Diaspora handle must always be lowercase
835 $data["addr"] = strtolower($data["addr"]);
837 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
838 $data["notify"] = $data["baseurl"]."/receive/users/".$data["guid"];
839 $data["batch"] = $data["baseurl"]."/receive/public";
847 * @brief Check for OStatus contact
849 * @param array $webfinger Webfinger data
851 * @return array OStatus data
853 private function ostatus($webfinger) {
856 if (is_array($webfinger["aliases"]))
857 foreach($webfinger["aliases"] AS $alias)
858 if (strstr($alias, "@"))
859 $data["addr"] = str_replace('acct:', '', $alias);
861 if (is_string($webfinger["subject"]) AND strstr($webfinger["subject"], "@"))
862 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
865 foreach ($webfinger["links"] AS $link) {
866 if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
867 ($link["type"] == "text/html") AND ($link["href"] != ""))
868 $data["url"] = $link["href"];
869 elseif (($link["rel"] == "salmon") AND ($link["href"] != ""))
870 $data["notify"] = $link["href"];
871 elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
872 $data["poll"] = $link["href"];
873 elseif (($link["rel"] == "magic-public-key") AND ($link["href"] != "")) {
874 $pubkey = $link["href"];
876 if (substr($pubkey, 0, 5) === 'data:') {
877 if (strstr($pubkey, ','))
878 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
880 $pubkey = substr($pubkey, 5);
881 } elseif (normalise_link($pubkey) == 'http://')
882 $pubkey = fetch_url($pubkey);
884 $key = explode(".", $pubkey);
886 if (sizeof($key) >= 3) {
887 $m = base64url_decode($key[1]);
888 $e = base64url_decode($key[2]);
889 $data["pubkey"] = metopem($m,$e);
895 if (isset($data["notify"]) AND isset($data["pubkey"]) AND
896 isset($data["poll"]) AND isset($data["url"])) {
897 $data["network"] = NETWORK_OSTATUS;
901 // Fetch all additional data from the feed
902 $feed = fetch_url($data["poll"]);
903 $feed_data = feed_import($feed,$dummy1,$dummy2, $dummy3, true);
907 if ($feed_data["header"]["author-name"] != "")
908 $data["name"] = $feed_data["header"]["author-name"];
910 if ($feed_data["header"]["author-nick"] != "")
911 $data["nick"] = $feed_data["header"]["author-nick"];
913 if ($feed_data["header"]["author-avatar"] != "")
914 $data["photo"] = $feed_data["header"]["author-avatar"];
916 if ($feed_data["header"]["author-id"] != "")
917 $data["alias"] = $feed_data["header"]["author-id"];
919 if ($feed_data["header"]["author-location"] != "")
920 $data["location"] = $feed_data["header"]["author-location"];
922 if ($feed_data["header"]["author-about"] != "")
923 $data["about"] = $feed_data["header"]["author-about"];
925 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
926 // So we take the value that we just fetched, although the other one worked as well
927 if ($feed_data["header"]["author-link"] != "")
928 $data["url"] = $feed_data["header"]["author-link"];
930 /// @todo Fetch location and "about" from the feed as well
935 * @brief Fetch data from a pump.io profile page
937 * @param string $profile Link to the profile page
939 * @return array profile data
941 private function pumpio_profile_data($profile) {
943 $doc = new DOMDocument();
944 if (!@$doc->loadHTMLFile($profile))
947 $xpath = new DomXPath($doc);
951 // This is ugly - but pump.io doesn't seem to know a better way for it
952 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
953 $pos = strpos($data["name"], chr(10));
955 $data["name"] = trim(substr($data["name"], 0, $pos));
957 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
959 foreach ($avatar->attributes as $attribute)
960 if ($attribute->name == "src")
961 $data["photo"] = trim($attribute->value);
963 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
964 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
970 * @brief Check for pump.io contact
972 * @param array $webfinger Webfinger data
974 * @return array pump.io data
976 private function pumpio($webfinger) {
979 foreach ($webfinger["links"] AS $link) {
980 if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
981 ($link["type"] == "text/html") AND ($link["href"] != ""))
982 $data["url"] = $link["href"];
983 elseif (($link["rel"] == "activity-inbox") AND ($link["href"] != ""))
984 $data["notify"] = $link["href"];
985 elseif (($link["rel"] == "activity-outbox") AND ($link["href"] != ""))
986 $data["poll"] = $link["href"];
987 elseif (($link["rel"] == "dialback") AND ($link["href"] != ""))
988 $data["dialback"] = $link["href"];
990 if (isset($data["poll"]) AND isset($data["notify"]) AND
991 isset($data["dialback"]) AND isset($data["url"])) {
993 // by now we use these fields only for the network type detection
994 // So we unset all data that isn't used at the moment
995 unset($data["dialback"]);
997 $data["network"] = NETWORK_PUMPIO;
1001 $profile_data = self::pumpio_profile_data($data["url"]);
1006 $data = array_merge($data, $profile_data);
1012 * @brief Check page for feed link
1014 * @param string $url Page link
1016 * @return string feed link
1018 private function get_feed_link($url) {
1019 $doc = new DOMDocument();
1021 if (!@$doc->loadHTMLFile($url))
1024 $xpath = new DomXPath($doc);
1026 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1027 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1028 if (!is_object($feeds))
1031 if ($feeds->length == 0)
1036 foreach ($feeds AS $feed) {
1038 foreach ($feed->attributes as $attribute)
1039 $attr[$attribute->name] = trim($attribute->value);
1041 if ($feed_url == "")
1042 $feed_url = $attr["href"];
1049 * @brief Check for feed contact
1051 * @param string $url Profile link
1052 * @param boolean $probe Do a probe if the page contains a feed link
1054 * @return array feed data
1056 private function feed($url, $probe = true) {
1057 $ret = z_fetch_url($url);
1058 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1061 $feed = $ret['body'];
1062 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1068 $feed_url = self::get_feed_link($url);
1073 return self::feed($feed_url, false);
1076 if ($feed_data["header"]["author-name"] != "")
1077 $data["name"] = $feed_data["header"]["author-name"];
1079 if ($feed_data["header"]["author-nick"] != "")
1080 $data["nick"] = $feed_data["header"]["author-nick"];
1082 if ($feed_data["header"]["author-avatar"] != "")
1083 $data["photo"] = $feed_data["header"]["author-avatar"];
1085 if ($feed_data["header"]["author-id"] != "")
1086 $data["alias"] = $feed_data["header"]["author-id"];
1088 $data["url"] = $url;
1089 $data["poll"] = $url;
1091 if ($feed_data["header"]["author-link"] != "")
1092 $data["baseurl"] = $feed_data["header"]["author-link"];
1094 $data["baseurl"] = $data["url"];
1096 $data["network"] = NETWORK_FEED;
1102 * @brief Check for mail contact
1104 * @param string $uri Profile link
1105 * @param integer $uid User ID
1107 * @return array mail data
1109 private function mail($uri, $uid) {
1111 if (!validate_email($uri))
1114 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1116 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1118 if (dbm::is_result($x) && dbm::is_result($r)) {
1119 $mailbox = construct_mailbox_name($r[0]);
1121 openssl_private_decrypt(hex2bin($r[0]['pass']), $password,$x[0]['prvkey']);
1122 $mbox = email_connect($mailbox,$r[0]['user'], $password);
1127 $msgs = email_poll($mbox, $uri);
1128 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1135 $data["addr"] = $uri;
1136 $data["network"] = NETWORK_MAIL;
1137 $data["name"] = substr($uri, 0, strpos($uri,'@'));
1138 $data["nick"] = $data["name"];
1139 $data["photo"] = avatar_img($uri);
1141 $phost = substr($uri, strpos($uri,'@') + 1);
1142 $data["url"] = 'http://'.$phost."/".$data["nick"];
1143 $data["notify"] = 'smtp '.random_string();
1144 $data["poll"] = 'email '.random_string();
1146 $x = email_msg_meta($mbox, $msgs[0]);
1147 if(stristr($x[0]->from, $uri))
1148 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1149 elseif(stristr($x[0]->to, $uri))
1150 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1152 foreach($adr as $feadr) {
1153 if((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1154 &&(strcasecmp($feadr->host, $phost) == 0)
1155 && (strlen($feadr->personal))) {
1157 $personal = imap_mime_header_decode($feadr->personal);
1159 foreach($personal as $perspart)
1160 if ($perspart->charset != "default")
1161 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1163 $data["name"] .= $perspart->text;
1165 $data["name"] = notags($data["name"]);