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 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
73 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
77 $xrd = parse_xml_string($xml, false);
82 $links = xml::element_to_array($xrd);
83 if (!isset($links["xrd"]["link"]))
88 foreach ($links["xrd"]["link"] AS $value => $link) {
89 if (isset($link["@attributes"]))
90 $attributes = $link["@attributes"];
91 elseif ($value == "@attributes")
96 if (($attributes["rel"] == "lrdd") AND
97 ($attributes["type"] == "application/xrd+xml"))
98 $xrd_data["lrdd-xml"] = $attributes["template"];
99 elseif (($attributes["rel"] == "lrdd") AND
100 ($attributes["type"] == "application/json"))
101 $xrd_data["lrdd-json"] = $attributes["template"];
102 elseif ($attributes["rel"] == "lrdd")
103 $xrd_data["lrdd"] = $attributes["template"];
109 * @brief Perform Webfinger lookup and return DFRN data
111 * Given an email style address, perform webfinger lookup and
112 * return the resulting DFRN profile URL, or if no DFRN profile URL
113 * is located, returns an OStatus subscription template (prefixed
114 * with the string 'stat:' to identify it as on OStatus template).
115 * If this isn't an email style address just return $webbie.
116 * Return an empty string if email-style addresses but webfinger fails,
117 * or if the resultant personal XRD doesn't contain a supported
118 * subscription/friend-request attribute.
120 * amended 7/9/2011 to return an hcard which could save potentially loading
121 * a lengthy content page to scrape dfrn attributes
123 * @param string $webbie Address that should be probed
124 * @param string $hcard Link to the hcard - is returned by reference
126 * @return string profile link
129 public static function webfinger_dfrn($webbie, &$hcard) {
133 $links = self::lrdd($webbie);
134 logger('webfinger_dfrn: '.$webbie.':'.print_r($links,true), LOGGER_DATA);
136 foreach ($links as $link) {
137 if ($link['@attributes']['rel'] === NAMESPACE_DFRN)
138 $profile_link = $link['@attributes']['href'];
139 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) AND ($profile_link == ""))
140 $profile_link = 'stat:'.$link['@attributes']['template'];
141 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
142 $hcard = $link['@attributes']['href'];
145 return $profile_link;
149 * @brief Check an URI for LRDD data
151 * this is a replacement for the "lrdd" function in include/network.php.
152 * It isn't used in this class and has some redundancies in the code.
153 * When time comes we can check the existing calls for "lrdd" if we can rework them.
155 * @param string $uri Address that should be probed
157 * @return array uri data
159 public static function lrdd($uri) {
161 $lrdd = self::xrd($uri);
164 $parts = @parse_url($uri);
168 $host = $parts["host"];
170 $path_parts = explode("/", trim($parts["path"], "/"));
173 $lrdd = self::xrd($host);
174 $host .= "/".array_shift($path_parts);
175 } while (!$lrdd AND (sizeof($path_parts) > 0));
181 foreach ($lrdd AS $key => $link) {
185 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json")))
188 $path = str_replace('{uri}', urlencode($uri), $link);
189 $webfinger = self::webfinger($path);
191 if (!$webfinger AND (strstr($uri, "@"))) {
192 $path = str_replace('{uri}', urlencode("acct:".$uri), $link);
193 $webfinger = self::webfinger($path);
197 if (!is_array($webfinger["links"]))
202 foreach ($webfinger["links"] AS $link)
203 $data[] = array("@attributes" => $link);
205 if (is_array($webfinger["aliases"]))
206 foreach ($webfinger["aliases"] AS $alias)
207 $data[] = array("@attributes" =>
208 array("rel" => "alias",
215 * @brief Fetch information (protocol endpoints and user information) about a given uri
217 * @param string $uri Address that should be probed
218 * @param string $network Test for this specific network
219 * @param integer $uid User ID for the probe (only used for mails)
220 * @param boolean $cache Use cached values?
222 * @return array uri data
224 public static function uri($uri, $network = "", $uid = 0, $cache = true) {
227 $result = Cache::get("probe_url:".$network.":".$uri);
228 if (!is_null($result)) {
236 $data = self::detect($uri, $network, $uid);
238 if (!isset($data["url"]))
241 if ($data["photo"] != "")
242 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
244 $data["photo"] = App::get_baseurl().'/images/person-175.jpg';
246 if (!isset($data["name"]) OR ($data["name"] == "")) {
247 if (isset($data["nick"]))
248 $data["name"] = $data["nick"];
250 if ($data["name"] == "")
251 $data["name"] = $data["url"];
254 if (!isset($data["nick"]) OR ($data["nick"] == "")) {
255 $data["nick"] = strtolower($data["name"]);
257 if (strpos($data['nick'], ' '))
258 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
261 if (!isset($data["network"]))
262 $data["network"] = NETWORK_PHANTOM;
264 $data = self::rearrange_data($data);
266 // Only store into the cache if the value seems to be valid
267 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
268 Cache::set("probe_url:".$network.":".$uri, $data, CACHE_DAY);
270 /// @todo temporary fix - we need a real contact update function that updates only changing fields
271 /// The biggest problem is the avatar picture that could have a reduced image size.
272 /// It should only be updated if the existing picture isn't existing anymore.
273 if (($data['network'] != NETWORK_FEED) AND ($mode == PROBE_NORMAL) AND
274 $data["name"] AND $data["nick"] AND $data["url"] AND $data["addr"] AND $data["poll"])
275 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `url` = '%s', `addr` = '%s',
276 `notify` = '%s', `poll` = '%s', `alias` = '%s', `success_update` = '%s'
277 WHERE `nurl` = '%s' AND NOT `self` AND `uid` = 0",
278 dbesc($data["name"]),
279 dbesc($data["nick"]),
281 dbesc($data["addr"]),
282 dbesc($data["notify"]),
283 dbesc($data["poll"]),
284 dbesc($data["alias"]),
285 dbesc(datetime_convert()),
286 dbesc(normalise_link($data['url']))
293 * @brief Fetch information (protocol endpoints and user information) about a given uri
295 * This function is only called by the "uri" function that adds caching and rearranging of data.
297 * @param string $uri Address that should be probed
298 * @param string $network Test for this specific network
299 * @param integer $uid User ID for the probe (only used for mails)
301 * @return array uri data
303 private function detect($uri, $network, $uid) {
304 if (strstr($uri, '@')) {
305 // If the URI starts with "mailto:" then jump directly to the mail detection
306 if (strpos($url,'mailto:') !== false) {
307 $uri = str_replace('mailto:', '', $url);
308 return self::mail($uri, $uid);
311 if ($network == NETWORK_MAIL)
312 return self::mail($uri, $uid);
314 // Remove "acct:" from the URI
315 $uri = str_replace('acct:', '', $uri);
317 $host = substr($uri,strpos($uri, '@') + 1);
318 $nick = substr($uri,0, strpos($uri, '@'));
320 if (strpos($uri, '@twitter.com'))
321 return array("network" => NETWORK_TWITTER);
323 $lrdd = self::xrd($host);
326 return self::mail($uri, $uid);
330 $parts = parse_url($uri);
331 if (!isset($parts["scheme"]) OR
332 !isset($parts["host"]) OR
333 !isset($parts["path"]))
337 $host = $parts["host"];
339 if ($host == 'twitter.com')
340 return array("network" => NETWORK_TWITTER);
342 $lrdd = self::xrd($host);
344 $path_parts = explode("/", trim($parts["path"], "/"));
346 while (!$lrdd AND (sizeof($path_parts) > 1)) {
347 $host .= "/".array_shift($path_parts);
348 $lrdd = self::xrd($host);
351 return self::feed($uri);
353 $nick = array_pop($path_parts);
354 $addr = $nick."@".$host;
358 /// @todo Do we need the prefix "acct:" or "acct://"?
360 foreach ($lrdd AS $key => $link) {
364 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json")))
367 // Try webfinger with the address (user@domain.tld)
368 $path = str_replace('{uri}', urlencode($addr), $link);
369 $webfinger = self::webfinger($path);
371 // Mastodon needs to have it with "acct:"
373 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
374 $webfinger = self::webfinger($path);
377 // If webfinger wasn't successful then try it with the URL - possibly in the format https://...
378 if (!$webfinger AND ($uri != $addr)) {
379 $path = str_replace('{uri}', urlencode($uri), $link);
380 $webfinger = self::webfinger($path);
382 // Since the detection with the address wasn't successful, we delete it.
391 return self::feed($uri);
395 logger("Probing ".$uri, LOGGER_DEBUG);
397 if (in_array($network, array("", NETWORK_DFRN)))
398 $result = self::dfrn($webfinger);
399 if ((!$result AND ($network == "")) OR ($network == NETWORK_DIASPORA))
400 $result = self::diaspora($webfinger);
401 if ((!$result AND ($network == "")) OR ($network == NETWORK_OSTATUS))
402 $result = self::ostatus($webfinger);
403 if ((!$result AND ($network == "")) OR ($network == NETWORK_PUMPIO))
404 $result = self::pumpio($webfinger);
405 if ((!$result AND ($network == "")) OR ($network == NETWORK_FEED))
406 $result = self::feed($uri);
408 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
409 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
410 if ((!isset($result["nick"]) OR ($result["nick"] == "") OR (strstr($result["nick"], " "))) AND ($nick != ""))
411 $result["nick"] = $nick;
413 if ((!isset($result["addr"]) OR ($result["addr"] == "")) AND ($addr != ""))
414 $result["addr"] = $addr;
417 logger($uri." is ".$result["network"], LOGGER_DEBUG);
419 if (!isset($result["baseurl"]) OR ($result["baseurl"] == "")) {
420 $pos = strpos($result["url"], $host);
422 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
429 * @brief Perform a webfinger request.
431 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
433 * @param string $url Address that should be probed
435 * @return array webfinger data
437 private function webfinger($url) {
439 $xrd_timeout = Config::get('system','xrd_timeout', 20);
442 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
443 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
446 $data = $ret['body'];
448 $xrd = parse_xml_string($data, false);
450 if (!is_object($xrd)) {
451 // If it is not XML, maybe it is JSON
452 $webfinger = json_decode($data, true);
454 if (!isset($webfinger["links"]))
460 $xrd_arr = xml::element_to_array($xrd);
461 if (!isset($xrd_arr["xrd"]["link"]))
464 $webfinger = array();
466 if (isset($xrd_arr["xrd"]["subject"]))
467 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
469 if (isset($xrd_arr["xrd"]["alias"]))
470 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
472 $webfinger["links"] = array();
474 foreach ($xrd_arr["xrd"]["link"] AS $value => $data) {
475 if (isset($data["@attributes"]))
476 $attributes = $data["@attributes"];
477 elseif ($value == "@attributes")
482 $webfinger["links"][] = $attributes;
488 * @brief Poll the Friendica specific noscrape page.
490 * "noscrape" is a faster alternative to fetch the data from the hcard.
491 * This functionality was originally created for the directory.
493 * @param string $noscrape Link to the noscrape page
494 * @param array $data The already fetched data
496 * @return array noscrape data
498 private function poll_noscrape($noscrape, $data) {
499 $ret = z_fetch_url($noscrape);
500 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
503 $content = $ret['body'];
508 $json = json_decode($content, true);
509 if (!is_array($json))
512 if (isset($json["fn"]))
513 $data["name"] = $json["fn"];
515 if (isset($json["addr"]))
516 $data["addr"] = $json["addr"];
518 if (isset($json["nick"]))
519 $data["nick"] = $json["nick"];
521 if (isset($json["comm"]))
522 $data["community"] = $json["comm"];
524 if (isset($json["tags"])) {
525 $keywords = implode(" ", $json["tags"]);
527 $data["keywords"] = $keywords;
530 $location = formatted_location($json);
532 $data["location"] = $location;
534 if (isset($json["about"]))
535 $data["about"] = $json["about"];
537 if (isset($json["key"]))
538 $data["pubkey"] = $json["key"];
540 if (isset($json["photo"]))
541 $data["photo"] = $json["photo"];
543 if (isset($json["dfrn-request"]))
544 $data["request"] = $json["dfrn-request"];
546 if (isset($json["dfrn-confirm"]))
547 $data["confirm"] = $json["dfrn-confirm"];
549 if (isset($json["dfrn-notify"]))
550 $data["notify"] = $json["dfrn-notify"];
552 if (isset($json["dfrn-poll"]))
553 $data["poll"] = $json["dfrn-poll"];
559 * @brief Check for valid DFRN data
561 * @param array $data DFRN data
563 * @return int Number of errors
565 public static function valid_dfrn($data) {
567 if(!isset($data['key']))
569 if(!isset($data['dfrn-request']))
571 if(!isset($data['dfrn-confirm']))
573 if(!isset($data['dfrn-notify']))
575 if(!isset($data['dfrn-poll']))
581 * @brief Fetch data from a DFRN profile page and via "noscrape"
583 * @param string $profile Link to the profile page
585 * @return array profile data
587 public static function profile($profile) {
591 logger("Check profile ".$profile, LOGGER_DEBUG);
593 // Fetch data via noscrape - this is faster
594 $noscrape = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile);
595 $data = self::poll_noscrape($noscrape, $data);
597 if (!isset($data["notify"]) OR !isset($data["confirm"]) OR
598 !isset($data["request"]) OR !isset($data["poll"]) OR
599 !isset($data["poco"]) OR !isset($data["name"]) OR
600 !isset($data["photo"]))
601 $data = self::poll_hcard($profile, $data, true);
603 $prof_data = array();
604 $prof_data["addr"] = $data["addr"];
605 $prof_data["nick"] = $data["nick"];
606 $prof_data["dfrn-request"] = $data["request"];
607 $prof_data["dfrn-confirm"] = $data["confirm"];
608 $prof_data["dfrn-notify"] = $data["notify"];
609 $prof_data["dfrn-poll"] = $data["poll"];
610 $prof_data["dfrn-poco"] = $data["poco"];
611 $prof_data["photo"] = $data["photo"];
612 $prof_data["fn"] = $data["name"];
613 $prof_data["key"] = $data["pubkey"];
615 logger("Result for profile ".$profile.": ".print_r($prof_data, true), LOGGER_DEBUG);
621 * @brief Check for DFRN contact
623 * @param array $webfinger Webfinger data
625 * @return array DFRN data
627 private function dfrn($webfinger) {
631 foreach ($webfinger["links"] AS $link) {
632 if (($link["rel"] == NAMESPACE_DFRN) AND ($link["href"] != ""))
633 $data["network"] = NETWORK_DFRN;
634 elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
635 $data["poll"] = $link["href"];
636 elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
637 ($link["type"] == "text/html") AND ($link["href"] != ""))
638 $data["url"] = $link["href"];
639 elseif (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != ""))
640 $hcard = $link["href"];
641 elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != ""))
642 $data["poco"] = $link["href"];
643 elseif (($link["rel"] == "http://webfinger.net/rel/avatar") AND ($link["href"] != ""))
644 $data["photo"] = $link["href"];
646 elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != ""))
647 $data["baseurl"] = trim($link["href"], '/');
648 elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != ""))
649 $data["guid"] = $link["href"];
650 elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
651 $data["pubkey"] = base64_decode($link["href"]);
653 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
654 if (strstr($data["pubkey"], 'RSA '))
655 $data["pubkey"] = rsatopem($data["pubkey"]);
659 if (!isset($data["network"]) OR ($hcard == ""))
662 // Fetch data via noscrape - this is faster
663 $noscrape = str_replace("/hcard/", "/noscrape/", $hcard);
664 $data = self::poll_noscrape($noscrape, $data);
666 if (isset($data["notify"]) AND isset($data["confirm"]) AND isset($data["request"]) AND
667 isset($data["poll"]) AND isset($data["name"]) AND isset($data["photo"]))
670 $data = self::poll_hcard($hcard, $data, true);
676 * @brief Poll the hcard page (Diaspora and Friendica specific)
678 * @param string $hcard Link to the hcard page
679 * @param array $data The already fetched data
680 * @param boolean $dfrn Poll DFRN specific data
682 * @return array hcard data
684 private function poll_hcard($hcard, $data, $dfrn = false) {
685 $ret = z_fetch_url($hcard);
686 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
689 $content = $ret['body'];
694 $doc = new DOMDocument();
695 if (!@$doc->loadHTML($content))
698 $xpath = new DomXPath($doc);
700 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
701 if (!is_object($vcards))
704 if ($vcards->length > 0) {
705 $vcard = $vcards->item(0);
707 // We have to discard the guid from the hcard in favour of the guid from lrdd
708 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
709 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
710 if (($search->length > 0) AND ($data["guid"] == ""))
711 $data["guid"] = $search->item(0)->nodeValue;
713 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
714 if ($search->length > 0)
715 $data["nick"] = $search->item(0)->nodeValue;
717 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
718 if ($search->length > 0)
719 $data["name"] = $search->item(0)->nodeValue;
721 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
722 if ($search->length > 0)
723 $data["searchable"] = $search->item(0)->nodeValue;
725 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
726 if ($search->length > 0) {
727 $data["pubkey"] = $search->item(0)->nodeValue;
728 if (strstr($data["pubkey"], 'RSA '))
729 $data["pubkey"] = rsatopem($data["pubkey"]);
732 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
733 if ($search->length > 0)
734 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
738 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
739 foreach ($photos AS $photo) {
741 foreach ($photo->attributes as $attribute) {
742 $attr[$attribute->name] = trim($attribute->value);
745 if (isset($attr["src"]) AND isset($attr["width"])) {
746 $avatar[$attr["width"]] = $attr["src"];
749 // We don't have a width. So we just take everything that we got.
750 // This is a Hubzilla workaround which doesn't send a width.
751 if ((sizeof($avatar) == 0) AND isset($attr["src"])) {
752 $avatar[] = $attr["src"];
756 if (sizeof($avatar)) {
758 $data["photo"] = array_pop($avatar);
762 // Poll DFRN specific data
763 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
764 if ($search->length > 0) {
765 foreach ($search AS $link) {
766 //$data["request"] = $search->item(0)->nodeValue;
768 foreach ($link->attributes as $attribute)
769 $attr[$attribute->name] = trim($attribute->value);
771 $data[substr($attr["rel"], 5)] = $attr["href"];
775 // Older Friendica versions had used the "uid" field differently than newer versions
776 if ($data["nick"] == $data["guid"])
777 unset($data["guid"]);
785 * @brief Check for Diaspora contact
787 * @param array $webfinger Webfinger data
789 * @return array Diaspora data
791 private function diaspora($webfinger) {
795 foreach ($webfinger["links"] AS $link) {
796 if (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != ""))
797 $hcard = $link["href"];
798 elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != ""))
799 $data["baseurl"] = trim($link["href"], '/');
800 elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != ""))
801 $data["guid"] = $link["href"];
802 elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
803 ($link["type"] == "text/html") AND ($link["href"] != ""))
804 $data["url"] = $link["href"];
805 elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
806 $data["poll"] = $link["href"];
807 elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != ""))
808 $data["poco"] = $link["href"];
809 elseif (($link["rel"] == "salmon") AND ($link["href"] != ""))
810 $data["notify"] = $link["href"];
811 elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
812 $data["pubkey"] = base64_decode($link["href"]);
814 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
815 if (strstr($data["pubkey"], 'RSA '))
816 $data["pubkey"] = rsatopem($data["pubkey"]);
820 if (!isset($data["url"]) OR ($hcard == ""))
823 if (is_array($webfinger["aliases"]))
824 foreach ($webfinger["aliases"] AS $alias)
825 if (normalise_link($alias) != normalise_link($data["url"]) AND !strstr($alias, "@"))
826 $data["alias"] = $alias;
828 // Fetch further information from the hcard
829 $data = self::poll_hcard($hcard, $data);
834 if (isset($data["url"]) AND isset($data["guid"]) AND isset($data["baseurl"]) AND
835 isset($data["pubkey"]) AND ($hcard != "")) {
836 $data["network"] = NETWORK_DIASPORA;
838 // The Diaspora handle must always be lowercase
839 $data["addr"] = strtolower($data["addr"]);
841 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
842 $data["notify"] = $data["baseurl"]."/receive/users/".$data["guid"];
843 $data["batch"] = $data["baseurl"]."/receive/public";
851 * @brief Check for OStatus contact
853 * @param array $webfinger Webfinger data
855 * @return array OStatus data
857 private function ostatus($webfinger) {
860 if (is_array($webfinger["aliases"]))
861 foreach($webfinger["aliases"] AS $alias)
862 if (strstr($alias, "@"))
863 $data["addr"] = str_replace('acct:', '', $alias);
865 if (is_string($webfinger["subject"]) AND strstr($webfinger["subject"], "@"))
866 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
869 foreach ($webfinger["links"] AS $link) {
870 if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
871 ($link["type"] == "text/html") AND ($link["href"] != ""))
872 $data["url"] = $link["href"];
873 elseif (($link["rel"] == "salmon") AND ($link["href"] != ""))
874 $data["notify"] = $link["href"];
875 elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
876 $data["poll"] = $link["href"];
877 elseif (($link["rel"] == "magic-public-key") AND ($link["href"] != "")) {
878 $pubkey = $link["href"];
880 if (substr($pubkey, 0, 5) === 'data:') {
881 if (strstr($pubkey, ','))
882 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
884 $pubkey = substr($pubkey, 5);
885 } elseif (normalise_link($pubkey) == 'http://') {
886 $ret = z_fetch_url($pubkey);
887 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
890 $pubkey = $ret['body'];
893 $key = explode(".", $pubkey);
895 if (sizeof($key) >= 3) {
896 $m = base64url_decode($key[1]);
897 $e = base64url_decode($key[2]);
898 $data["pubkey"] = metopem($m,$e);
904 if (isset($data["notify"]) AND isset($data["pubkey"]) AND
905 isset($data["poll"]) AND isset($data["url"])) {
906 $data["network"] = NETWORK_OSTATUS;
910 // Fetch all additional data from the feed
911 $ret = z_fetch_url($data["poll"]);
912 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
915 $feed = $ret['body'];
916 $feed_data = feed_import($feed,$dummy1,$dummy2, $dummy3, true);
920 if ($feed_data["header"]["author-name"] != "")
921 $data["name"] = $feed_data["header"]["author-name"];
923 if ($feed_data["header"]["author-nick"] != "")
924 $data["nick"] = $feed_data["header"]["author-nick"];
926 if ($feed_data["header"]["author-avatar"] != "")
927 $data["photo"] = $feed_data["header"]["author-avatar"];
929 if ($feed_data["header"]["author-id"] != "")
930 $data["alias"] = $feed_data["header"]["author-id"];
932 if ($feed_data["header"]["author-location"] != "")
933 $data["location"] = $feed_data["header"]["author-location"];
935 if ($feed_data["header"]["author-about"] != "")
936 $data["about"] = $feed_data["header"]["author-about"];
938 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
939 // So we take the value that we just fetched, although the other one worked as well
940 if ($feed_data["header"]["author-link"] != "")
941 $data["url"] = $feed_data["header"]["author-link"];
943 /// @todo Fetch location and "about" from the feed as well
948 * @brief Fetch data from a pump.io profile page
950 * @param string $profile Link to the profile page
952 * @return array profile data
954 private function pumpio_profile_data($profile) {
956 $doc = new DOMDocument();
957 if (!@$doc->loadHTMLFile($profile))
960 $xpath = new DomXPath($doc);
964 // This is ugly - but pump.io doesn't seem to know a better way for it
965 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
966 $pos = strpos($data["name"], chr(10));
968 $data["name"] = trim(substr($data["name"], 0, $pos));
970 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
972 foreach ($avatar->attributes as $attribute)
973 if ($attribute->name == "src")
974 $data["photo"] = trim($attribute->value);
976 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
977 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
983 * @brief Check for pump.io contact
985 * @param array $webfinger Webfinger data
987 * @return array pump.io data
989 private function pumpio($webfinger) {
992 foreach ($webfinger["links"] AS $link) {
993 if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
994 ($link["type"] == "text/html") AND ($link["href"] != ""))
995 $data["url"] = $link["href"];
996 elseif (($link["rel"] == "activity-inbox") AND ($link["href"] != ""))
997 $data["notify"] = $link["href"];
998 elseif (($link["rel"] == "activity-outbox") AND ($link["href"] != ""))
999 $data["poll"] = $link["href"];
1000 elseif (($link["rel"] == "dialback") AND ($link["href"] != ""))
1001 $data["dialback"] = $link["href"];
1003 if (isset($data["poll"]) AND isset($data["notify"]) AND
1004 isset($data["dialback"]) AND isset($data["url"])) {
1006 // by now we use these fields only for the network type detection
1007 // So we unset all data that isn't used at the moment
1008 unset($data["dialback"]);
1010 $data["network"] = NETWORK_PUMPIO;
1014 $profile_data = self::pumpio_profile_data($data["url"]);
1019 $data = array_merge($data, $profile_data);
1025 * @brief Check page for feed link
1027 * @param string $url Page link
1029 * @return string feed link
1031 private function get_feed_link($url) {
1032 $doc = new DOMDocument();
1034 if (!@$doc->loadHTMLFile($url))
1037 $xpath = new DomXPath($doc);
1039 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1040 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1041 if (!is_object($feeds))
1044 if ($feeds->length == 0)
1049 foreach ($feeds AS $feed) {
1051 foreach ($feed->attributes as $attribute)
1052 $attr[$attribute->name] = trim($attribute->value);
1054 if ($feed_url == "")
1055 $feed_url = $attr["href"];
1062 * @brief Check for feed contact
1064 * @param string $url Profile link
1065 * @param boolean $probe Do a probe if the page contains a feed link
1067 * @return array feed data
1069 private function feed($url, $probe = true) {
1070 $ret = z_fetch_url($url);
1071 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1074 $feed = $ret['body'];
1075 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1081 $feed_url = self::get_feed_link($url);
1086 return self::feed($feed_url, false);
1089 if ($feed_data["header"]["author-name"] != "")
1090 $data["name"] = $feed_data["header"]["author-name"];
1092 if ($feed_data["header"]["author-nick"] != "")
1093 $data["nick"] = $feed_data["header"]["author-nick"];
1095 if ($feed_data["header"]["author-avatar"] != "")
1096 $data["photo"] = $feed_data["header"]["author-avatar"];
1098 if ($feed_data["header"]["author-id"] != "")
1099 $data["alias"] = $feed_data["header"]["author-id"];
1101 $data["url"] = $url;
1102 $data["poll"] = $url;
1104 if ($feed_data["header"]["author-link"] != "")
1105 $data["baseurl"] = $feed_data["header"]["author-link"];
1107 $data["baseurl"] = $data["url"];
1109 $data["network"] = NETWORK_FEED;
1115 * @brief Check for mail contact
1117 * @param string $uri Profile link
1118 * @param integer $uid User ID
1120 * @return array mail data
1122 private function mail($uri, $uid) {
1124 if (!validate_email($uri))
1127 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1129 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1131 if (dbm::is_result($x) && dbm::is_result($r)) {
1132 $mailbox = construct_mailbox_name($r[0]);
1134 openssl_private_decrypt(hex2bin($r[0]['pass']), $password,$x[0]['prvkey']);
1135 $mbox = email_connect($mailbox,$r[0]['user'], $password);
1140 $msgs = email_poll($mbox, $uri);
1141 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1148 $data["addr"] = $uri;
1149 $data["network"] = NETWORK_MAIL;
1150 $data["name"] = substr($uri, 0, strpos($uri,'@'));
1151 $data["nick"] = $data["name"];
1152 $data["photo"] = avatar_img($uri);
1154 $phost = substr($uri, strpos($uri,'@') + 1);
1155 $data["url"] = 'http://'.$phost."/".$data["nick"];
1156 $data["notify"] = 'smtp '.random_string();
1157 $data["poll"] = 'email '.random_string();
1159 $x = email_msg_meta($mbox, $msgs[0]);
1160 if(stristr($x[0]->from, $uri))
1161 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1162 elseif(stristr($x[0]->to, $uri))
1163 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1165 foreach($adr as $feadr) {
1166 if((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1167 &&(strcasecmp($feadr->host, $phost) == 0)
1168 && (strlen($feadr->personal))) {
1170 $personal = imap_mime_header_decode($feadr->personal);
1172 foreach($personal as $perspart)
1173 if ($perspart->charset != "default")
1174 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1176 $data["name"] .= $perspart->text;
1178 $data["name"] = notags($data["name"]);