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
21 private static $baseurl;
24 * @brief Rearrange the array so that it always has the same order
26 * @param array $data Unordered data
28 * @return array Ordered data
30 private function rearrange_data($data) {
31 $fields = array("name", "nick", "guid", "url", "addr", "alias",
32 "photo", "community", "keywords", "location", "about",
33 "batch", "notify", "poll", "request", "confirm", "poco",
34 "priority", "network", "pubkey", "baseurl");
37 foreach ($fields AS $field)
38 if (isset($data[$field]))
39 $newdata[$field] = $data[$field];
41 $newdata[$field] = "";
43 // We don't use the "priority" field anymore and replace it with a dummy.
44 $newdata["priority"] = 0;
50 * @brief Probes for XRD data
53 * 'lrdd' => Link to LRDD endpoint
54 * 'lrdd-xml' => Link to LRDD endpoint in XML format
55 * 'lrdd-json' => Link to LRDD endpoint in JSON format
57 private function xrd($host) {
59 // Reset the static variable
62 $ssl_url = "https://".$host."/.well-known/host-meta";
63 $url = "http://".$host."/.well-known/host-meta";
65 $xrd_timeout = Config::get('system','xrd_timeout', 20);
68 $ret = z_fetch_url($ssl_url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
69 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
74 $xrd = parse_xml_string($xml, false);
76 if (!is_object($xrd)) {
77 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
78 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
82 $xrd = parse_xml_string($xml, false);
87 $links = xml::element_to_array($xrd);
88 if (!isset($links["xrd"]["link"]))
93 foreach ($links["xrd"]["link"] AS $value => $link) {
94 if (isset($link["@attributes"]))
95 $attributes = $link["@attributes"];
96 elseif ($value == "@attributes")
101 if (($attributes["rel"] == "lrdd") AND
102 ($attributes["type"] == "application/xrd+xml"))
103 $xrd_data["lrdd-xml"] = $attributes["template"];
104 elseif (($attributes["rel"] == "lrdd") AND
105 ($attributes["type"] == "application/json"))
106 $xrd_data["lrdd-json"] = $attributes["template"];
107 elseif ($attributes["rel"] == "lrdd")
108 $xrd_data["lrdd"] = $attributes["template"];
111 self::$baseurl = "http://".$host;
117 * @brief Perform Webfinger lookup and return DFRN data
119 * Given an email style address, perform webfinger lookup and
120 * return the resulting DFRN profile URL, or if no DFRN profile URL
121 * is located, returns an OStatus subscription template (prefixed
122 * with the string 'stat:' to identify it as on OStatus template).
123 * If this isn't an email style address just return $webbie.
124 * Return an empty string if email-style addresses but webfinger fails,
125 * or if the resultant personal XRD doesn't contain a supported
126 * subscription/friend-request attribute.
128 * amended 7/9/2011 to return an hcard which could save potentially loading
129 * a lengthy content page to scrape dfrn attributes
131 * @param string $webbie Address that should be probed
132 * @param string $hcard Link to the hcard - is returned by reference
134 * @return string profile link
137 public static function webfinger_dfrn($webbie, &$hcard) {
141 $links = self::lrdd($webbie);
142 logger('webfinger_dfrn: '.$webbie.':'.print_r($links,true), LOGGER_DATA);
144 foreach ($links as $link) {
145 if ($link['@attributes']['rel'] === NAMESPACE_DFRN)
146 $profile_link = $link['@attributes']['href'];
147 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) AND ($profile_link == ""))
148 $profile_link = 'stat:'.$link['@attributes']['template'];
149 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
150 $hcard = $link['@attributes']['href'];
153 return $profile_link;
157 * @brief Check an URI for LRDD data
159 * this is a replacement for the "lrdd" function in include/network.php.
160 * It isn't used in this class and has some redundancies in the code.
161 * When time comes we can check the existing calls for "lrdd" if we can rework them.
163 * @param string $uri Address that should be probed
165 * @return array uri data
167 public static function lrdd($uri) {
169 $lrdd = self::xrd($uri);
172 $parts = @parse_url($uri);
176 $host = $parts["host"];
178 $path_parts = explode("/", trim($parts["path"], "/"));
180 $nick = array_pop($path_parts);
183 $lrdd = self::xrd($host);
184 $host .= "/".array_shift($path_parts);
185 } while (!$lrdd AND (sizeof($path_parts) > 0));
191 foreach ($lrdd AS $key => $link) {
195 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json")))
198 $path = str_replace('{uri}', urlencode($uri), $link);
199 $webfinger = self::webfinger($path);
201 if (!$webfinger AND (strstr($uri, "@"))) {
202 $path = str_replace('{uri}', urlencode("acct:".$uri), $link);
203 $webfinger = self::webfinger($path);
206 // Special treatment for Mastodon
207 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
208 // But the webfinger for this format fails.
209 if (!$webfinger AND isset($nick)) {
210 // Mastodon uses a "@" as prefix for usernames in their url format
211 $nick = ltrim($nick, '@');
213 $addr = $nick."@".$host;
215 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
216 $webfinger = self::webfinger($path);
220 if (!is_array($webfinger["links"]))
225 foreach ($webfinger["links"] AS $link)
226 $data[] = array("@attributes" => $link);
228 if (is_array($webfinger["aliases"]))
229 foreach ($webfinger["aliases"] AS $alias)
230 $data[] = array("@attributes" =>
231 array("rel" => "alias",
238 * @brief Fetch information (protocol endpoints and user information) about a given uri
240 * @param string $uri Address that should be probed
241 * @param string $network Test for this specific network
242 * @param integer $uid User ID for the probe (only used for mails)
243 * @param boolean $cache Use cached values?
245 * @return array uri data
247 public static function uri($uri, $network = "", $uid = 0, $cache = true) {
250 $result = Cache::get("probe_url:".$network.":".$uri);
251 if (!is_null($result)) {
259 $data = self::detect($uri, $network, $uid);
261 if (!isset($data["url"]))
264 if ($data["photo"] != "")
265 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
267 $data["photo"] = App::get_baseurl().'/images/person-175.jpg';
269 if (!isset($data["name"]) OR ($data["name"] == "")) {
270 if (isset($data["nick"]))
271 $data["name"] = $data["nick"];
273 if ($data["name"] == "")
274 $data["name"] = $data["url"];
277 if (!isset($data["nick"]) OR ($data["nick"] == "")) {
278 $data["nick"] = strtolower($data["name"]);
280 if (strpos($data['nick'], ' '))
281 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
284 if (self::$baseurl != "") {
285 $data["baseurl"] = self::$baseurl;
288 if (!isset($data["network"])) {
289 $data["network"] = NETWORK_PHANTOM;
292 $data = self::rearrange_data($data);
294 // Only store into the cache if the value seems to be valid
295 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
296 Cache::set("probe_url:".$network.":".$uri, $data, CACHE_DAY);
298 /// @todo temporary fix - we need a real contact update function that updates only changing fields
299 /// The biggest problem is the avatar picture that could have a reduced image size.
300 /// It should only be updated if the existing picture isn't existing anymore.
301 if (($data['network'] != NETWORK_FEED) AND ($mode == PROBE_NORMAL) AND
302 $data["name"] AND $data["nick"] AND $data["url"] AND $data["addr"] AND $data["poll"])
303 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `url` = '%s', `addr` = '%s',
304 `notify` = '%s', `poll` = '%s', `alias` = '%s', `success_update` = '%s'
305 WHERE `nurl` = '%s' AND NOT `self` AND `uid` = 0",
306 dbesc($data["name"]),
307 dbesc($data["nick"]),
309 dbesc($data["addr"]),
310 dbesc($data["notify"]),
311 dbesc($data["poll"]),
312 dbesc($data["alias"]),
313 dbesc(datetime_convert()),
314 dbesc(normalise_link($data['url']))
322 * @brief Fetch information (protocol endpoints and user information) about a given uri
324 * This function is only called by the "uri" function that adds caching and rearranging of data.
326 * @param string $uri Address that should be probed
327 * @param string $network Test for this specific network
328 * @param integer $uid User ID for the probe (only used for mails)
330 * @return array uri data
332 private function detect($uri, $network, $uid) {
333 $parts = parse_url($uri);
335 if (isset($parts["scheme"]) AND isset($parts["host"]) AND isset($parts["path"])) {
338 $host = $parts["host"];
340 if ($host == 'twitter.com') {
341 return array("network" => NETWORK_TWITTER);
343 $lrdd = self::xrd($host);
345 $path_parts = explode("/", trim($parts["path"], "/"));
347 while (!$lrdd AND (sizeof($path_parts) > 1)) {
348 $host .= "/".array_shift($path_parts);
349 $lrdd = self::xrd($host);
352 return self::feed($uri);
354 $nick = array_pop($path_parts);
356 // Mastodon uses a "@" as prefix for usernames in their url format
357 $nick = ltrim($nick, '@');
359 $addr = $nick."@".$host;
360 } elseif (strstr($uri, '@')) {
361 // If the URI starts with "mailto:" then jump directly to the mail detection
362 if (strpos($url,'mailto:') !== false) {
363 $uri = str_replace('mailto:', '', $url);
364 return self::mail($uri, $uid);
367 if ($network == NETWORK_MAIL) {
368 return self::mail($uri, $uid);
370 // Remove "acct:" from the URI
371 $uri = str_replace('acct:', '', $uri);
373 $host = substr($uri,strpos($uri, '@') + 1);
374 $nick = substr($uri,0, strpos($uri, '@'));
376 if (strpos($uri, '@twitter.com')) {
377 return array("network" => NETWORK_TWITTER);
379 $lrdd = self::xrd($host);
382 return self::mail($uri, $uid);
391 /// @todo Do we need the prefix "acct:" or "acct://"?
393 foreach ($lrdd AS $key => $link) {
397 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
400 // At first try it with the given uri
401 $path = str_replace('{uri}', urlencode($uri), $link);
402 $webfinger = self::webfinger($path);
404 // We cannot be sure that the detected address was correct, so we don't use the values
405 if ($webfinger AND ($uri != $addr)) {
410 // Try webfinger with the address (user@domain.tld)
412 $path = str_replace('{uri}', urlencode($addr), $link);
413 $webfinger = self::webfinger($path);
416 // Mastodon needs to have it with "acct:"
418 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
419 $webfinger = self::webfinger($path);
423 return self::feed($uri);
428 logger("Probing ".$uri, LOGGER_DEBUG);
430 if (in_array($network, array("", NETWORK_DFRN)))
431 $result = self::dfrn($webfinger);
432 if ((!$result AND ($network == "")) OR ($network == NETWORK_DIASPORA))
433 $result = self::diaspora($webfinger);
434 if ((!$result AND ($network == "")) OR ($network == NETWORK_OSTATUS))
435 $result = self::ostatus($webfinger);
436 if ((!$result AND ($network == "")) OR ($network == NETWORK_PUMPIO))
437 $result = self::pumpio($webfinger);
438 if ((!$result AND ($network == "")) OR ($network == NETWORK_FEED))
439 $result = self::feed($uri);
441 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
442 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
443 if ((!isset($result["nick"]) OR ($result["nick"] == "") OR (strstr($result["nick"], " "))) AND ($nick != ""))
444 $result["nick"] = $nick;
446 if ((!isset($result["addr"]) OR ($result["addr"] == "")) AND ($addr != ""))
447 $result["addr"] = $addr;
450 logger($uri." is ".$result["network"], LOGGER_DEBUG);
452 if (!isset($result["baseurl"]) OR ($result["baseurl"] == "")) {
453 $pos = strpos($result["url"], $host);
455 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
462 * @brief Perform a webfinger request.
464 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
466 * @param string $url Address that should be probed
468 * @return array webfinger data
470 private function webfinger($url) {
472 $xrd_timeout = Config::get('system','xrd_timeout', 20);
475 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
476 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
479 $data = $ret['body'];
481 $xrd = parse_xml_string($data, false);
483 if (!is_object($xrd)) {
484 // If it is not XML, maybe it is JSON
485 $webfinger = json_decode($data, true);
487 if (!isset($webfinger["links"]))
493 $xrd_arr = xml::element_to_array($xrd);
494 if (!isset($xrd_arr["xrd"]["link"]))
497 $webfinger = array();
499 if (isset($xrd_arr["xrd"]["subject"]))
500 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
502 if (isset($xrd_arr["xrd"]["alias"]))
503 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
505 $webfinger["links"] = array();
507 foreach ($xrd_arr["xrd"]["link"] AS $value => $data) {
508 if (isset($data["@attributes"]))
509 $attributes = $data["@attributes"];
510 elseif ($value == "@attributes")
515 $webfinger["links"][] = $attributes;
521 * @brief Poll the Friendica specific noscrape page.
523 * "noscrape" is a faster alternative to fetch the data from the hcard.
524 * This functionality was originally created for the directory.
526 * @param string $noscrape Link to the noscrape page
527 * @param array $data The already fetched data
529 * @return array noscrape data
531 private function poll_noscrape($noscrape, $data) {
532 $ret = z_fetch_url($noscrape);
533 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
536 $content = $ret['body'];
541 $json = json_decode($content, true);
542 if (!is_array($json))
545 if (isset($json["fn"]))
546 $data["name"] = $json["fn"];
548 if (isset($json["addr"]))
549 $data["addr"] = $json["addr"];
551 if (isset($json["nick"]))
552 $data["nick"] = $json["nick"];
554 if (isset($json["comm"]))
555 $data["community"] = $json["comm"];
557 if (isset($json["tags"])) {
558 $keywords = implode(" ", $json["tags"]);
560 $data["keywords"] = $keywords;
563 $location = formatted_location($json);
565 $data["location"] = $location;
567 if (isset($json["about"]))
568 $data["about"] = $json["about"];
570 if (isset($json["key"]))
571 $data["pubkey"] = $json["key"];
573 if (isset($json["photo"]))
574 $data["photo"] = $json["photo"];
576 if (isset($json["dfrn-request"]))
577 $data["request"] = $json["dfrn-request"];
579 if (isset($json["dfrn-confirm"]))
580 $data["confirm"] = $json["dfrn-confirm"];
582 if (isset($json["dfrn-notify"]))
583 $data["notify"] = $json["dfrn-notify"];
585 if (isset($json["dfrn-poll"]))
586 $data["poll"] = $json["dfrn-poll"];
592 * @brief Check for valid DFRN data
594 * @param array $data DFRN data
596 * @return int Number of errors
598 public static function valid_dfrn($data) {
600 if(!isset($data['key']))
602 if(!isset($data['dfrn-request']))
604 if(!isset($data['dfrn-confirm']))
606 if(!isset($data['dfrn-notify']))
608 if(!isset($data['dfrn-poll']))
614 * @brief Fetch data from a DFRN profile page and via "noscrape"
616 * @param string $profile Link to the profile page
618 * @return array profile data
620 public static function profile($profile) {
624 logger("Check profile ".$profile, LOGGER_DEBUG);
626 // Fetch data via noscrape - this is faster
627 $noscrape = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile);
628 $data = self::poll_noscrape($noscrape, $data);
630 if (!isset($data["notify"]) OR !isset($data["confirm"]) OR
631 !isset($data["request"]) OR !isset($data["poll"]) OR
632 !isset($data["poco"]) OR !isset($data["name"]) OR
633 !isset($data["photo"]))
634 $data = self::poll_hcard($profile, $data, true);
636 $prof_data = array();
637 $prof_data["addr"] = $data["addr"];
638 $prof_data["nick"] = $data["nick"];
639 $prof_data["dfrn-request"] = $data["request"];
640 $prof_data["dfrn-confirm"] = $data["confirm"];
641 $prof_data["dfrn-notify"] = $data["notify"];
642 $prof_data["dfrn-poll"] = $data["poll"];
643 $prof_data["dfrn-poco"] = $data["poco"];
644 $prof_data["photo"] = $data["photo"];
645 $prof_data["fn"] = $data["name"];
646 $prof_data["key"] = $data["pubkey"];
648 logger("Result for profile ".$profile.": ".print_r($prof_data, true), LOGGER_DEBUG);
654 * @brief Check for DFRN contact
656 * @param array $webfinger Webfinger data
658 * @return array DFRN data
660 private function dfrn($webfinger) {
664 foreach ($webfinger["links"] AS $link) {
665 if (($link["rel"] == NAMESPACE_DFRN) AND ($link["href"] != ""))
666 $data["network"] = NETWORK_DFRN;
667 elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
668 $data["poll"] = $link["href"];
669 elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
670 ($link["type"] == "text/html") AND ($link["href"] != ""))
671 $data["url"] = $link["href"];
672 elseif (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != ""))
673 $hcard = $link["href"];
674 elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != ""))
675 $data["poco"] = $link["href"];
676 elseif (($link["rel"] == "http://webfinger.net/rel/avatar") AND ($link["href"] != ""))
677 $data["photo"] = $link["href"];
679 elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != ""))
680 $data["baseurl"] = trim($link["href"], '/');
681 elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != ""))
682 $data["guid"] = $link["href"];
683 elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
684 $data["pubkey"] = base64_decode($link["href"]);
686 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
687 if (strstr($data["pubkey"], 'RSA '))
688 $data["pubkey"] = rsatopem($data["pubkey"]);
692 if (!isset($data["network"]) OR ($hcard == ""))
695 // Fetch data via noscrape - this is faster
696 $noscrape = str_replace("/hcard/", "/noscrape/", $hcard);
697 $data = self::poll_noscrape($noscrape, $data);
699 if (isset($data["notify"]) AND isset($data["confirm"]) AND isset($data["request"]) AND
700 isset($data["poll"]) AND isset($data["name"]) AND isset($data["photo"]))
703 $data = self::poll_hcard($hcard, $data, true);
709 * @brief Poll the hcard page (Diaspora and Friendica specific)
711 * @param string $hcard Link to the hcard page
712 * @param array $data The already fetched data
713 * @param boolean $dfrn Poll DFRN specific data
715 * @return array hcard data
717 private function poll_hcard($hcard, $data, $dfrn = false) {
718 $ret = z_fetch_url($hcard);
719 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
722 $content = $ret['body'];
727 $doc = new DOMDocument();
728 if (!@$doc->loadHTML($content))
731 $xpath = new DomXPath($doc);
733 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
734 if (!is_object($vcards))
737 if ($vcards->length > 0) {
738 $vcard = $vcards->item(0);
740 // We have to discard the guid from the hcard in favour of the guid from lrdd
741 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
742 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
743 if (($search->length > 0) AND ($data["guid"] == ""))
744 $data["guid"] = $search->item(0)->nodeValue;
746 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
747 if ($search->length > 0)
748 $data["nick"] = $search->item(0)->nodeValue;
750 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
751 if ($search->length > 0)
752 $data["name"] = $search->item(0)->nodeValue;
754 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
755 if ($search->length > 0)
756 $data["searchable"] = $search->item(0)->nodeValue;
758 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
759 if ($search->length > 0) {
760 $data["pubkey"] = $search->item(0)->nodeValue;
761 if (strstr($data["pubkey"], 'RSA '))
762 $data["pubkey"] = rsatopem($data["pubkey"]);
765 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
766 if ($search->length > 0)
767 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
771 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
772 foreach ($photos AS $photo) {
774 foreach ($photo->attributes as $attribute) {
775 $attr[$attribute->name] = trim($attribute->value);
778 if (isset($attr["src"]) AND isset($attr["width"])) {
779 $avatar[$attr["width"]] = $attr["src"];
782 // We don't have a width. So we just take everything that we got.
783 // This is a Hubzilla workaround which doesn't send a width.
784 if ((sizeof($avatar) == 0) AND isset($attr["src"])) {
785 $avatar[] = $attr["src"];
789 if (sizeof($avatar)) {
791 $data["photo"] = array_pop($avatar);
795 // Poll DFRN specific data
796 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
797 if ($search->length > 0) {
798 foreach ($search AS $link) {
799 //$data["request"] = $search->item(0)->nodeValue;
801 foreach ($link->attributes as $attribute)
802 $attr[$attribute->name] = trim($attribute->value);
804 $data[substr($attr["rel"], 5)] = $attr["href"];
808 // Older Friendica versions had used the "uid" field differently than newer versions
809 if ($data["nick"] == $data["guid"])
810 unset($data["guid"]);
818 * @brief Check for Diaspora contact
820 * @param array $webfinger Webfinger data
822 * @return array Diaspora data
824 private function diaspora($webfinger) {
828 foreach ($webfinger["links"] AS $link) {
829 if (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != ""))
830 $hcard = $link["href"];
831 elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != ""))
832 $data["baseurl"] = trim($link["href"], '/');
833 elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != ""))
834 $data["guid"] = $link["href"];
835 elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
836 ($link["type"] == "text/html") AND ($link["href"] != ""))
837 $data["url"] = $link["href"];
838 elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
839 $data["poll"] = $link["href"];
840 elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != ""))
841 $data["poco"] = $link["href"];
842 elseif (($link["rel"] == "salmon") AND ($link["href"] != ""))
843 $data["notify"] = $link["href"];
844 elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
845 $data["pubkey"] = base64_decode($link["href"]);
847 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
848 if (strstr($data["pubkey"], 'RSA '))
849 $data["pubkey"] = rsatopem($data["pubkey"]);
853 if (!isset($data["url"]) OR ($hcard == ""))
856 if (is_array($webfinger["aliases"]))
857 foreach ($webfinger["aliases"] AS $alias)
858 if (normalise_link($alias) != normalise_link($data["url"]) AND !strstr($alias, "@"))
859 $data["alias"] = $alias;
861 // Fetch further information from the hcard
862 $data = self::poll_hcard($hcard, $data);
867 if (isset($data["url"]) AND isset($data["guid"]) AND isset($data["baseurl"]) AND
868 isset($data["pubkey"]) AND ($hcard != "")) {
869 $data["network"] = NETWORK_DIASPORA;
871 // The Diaspora handle must always be lowercase
872 $data["addr"] = strtolower($data["addr"]);
874 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
875 $data["notify"] = $data["baseurl"]."/receive/users/".$data["guid"];
876 $data["batch"] = $data["baseurl"]."/receive/public";
884 * @brief Check for OStatus contact
886 * @param array $webfinger Webfinger data
888 * @return array OStatus data
890 private function ostatus($webfinger) {
892 if (is_array($webfinger["aliases"])) {
893 foreach ($webfinger["aliases"] AS $alias) {
894 if (strstr($alias, "@")) {
895 $data["addr"] = str_replace('acct:', '', $alias);
900 if (is_string($webfinger["subject"]) AND strstr($webfinger["subject"], "@")) {
901 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
904 foreach ($webfinger["links"] AS $link) {
905 if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
906 ($link["type"] == "text/html") AND ($link["href"] != "")) {
907 $data["url"] = $link["href"];
908 } elseif (($link["rel"] == "salmon") AND ($link["href"] != "")) {
909 $data["notify"] = $link["href"];
910 } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
911 $data["poll"] = $link["href"];
912 } elseif (($link["rel"] == "magic-public-key") AND ($link["href"] != "")) {
913 $pubkey = $link["href"];
915 if (substr($pubkey, 0, 5) === 'data:') {
916 if (strstr($pubkey, ',')) {
917 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
919 $pubkey = substr($pubkey, 5);
921 } elseif (normalise_link($pubkey) == 'http://') {
922 $ret = z_fetch_url($pubkey);
923 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
926 $pubkey = $ret['body'];
929 $key = explode(".", $pubkey);
931 if (sizeof($key) >= 3) {
932 $m = base64url_decode($key[1]);
933 $e = base64url_decode($key[2]);
934 $data["pubkey"] = metopem($m,$e);
939 if (isset($data["notify"]) AND isset($data["pubkey"]) AND
940 isset($data["poll"]) AND isset($data["url"])) {
941 $data["network"] = NETWORK_OSTATUS;
945 // Fetch all additional data from the feed
946 $ret = z_fetch_url($data["poll"]);
947 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
950 $feed = $ret['body'];
951 $feed_data = feed_import($feed,$dummy1,$dummy2, $dummy3, true);
955 if ($feed_data["header"]["author-name"] != "") {
956 $data["name"] = $feed_data["header"]["author-name"];
958 if ($feed_data["header"]["author-nick"] != "") {
959 $data["nick"] = $feed_data["header"]["author-nick"];
961 if ($feed_data["header"]["author-avatar"] != "") {
962 $data["photo"] = ostatus::fix_avatar($feed_data["header"]["author-avatar"], $data["url"]);
964 if ($feed_data["header"]["author-id"] != "") {
965 $data["alias"] = $feed_data["header"]["author-id"];
967 if ($feed_data["header"]["author-location"] != "") {
968 $data["location"] = $feed_data["header"]["author-location"];
970 if ($feed_data["header"]["author-about"] != "") {
971 $data["about"] = $feed_data["header"]["author-about"];
973 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
974 // So we take the value that we just fetched, although the other one worked as well
975 if ($feed_data["header"]["author-link"] != "") {
976 $data["url"] = $feed_data["header"]["author-link"];
978 /// @todo Fetch location and "about" from the feed as well
983 * @brief Fetch data from a pump.io profile page
985 * @param string $profile Link to the profile page
987 * @return array profile data
989 private function pumpio_profile_data($profile) {
991 $doc = new DOMDocument();
992 if (!@$doc->loadHTMLFile($profile))
995 $xpath = new DomXPath($doc);
999 // This is ugly - but pump.io doesn't seem to know a better way for it
1000 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1001 $pos = strpos($data["name"], chr(10));
1003 $data["name"] = trim(substr($data["name"], 0, $pos));
1005 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1007 foreach ($avatar->attributes as $attribute)
1008 if ($attribute->name == "src")
1009 $data["photo"] = trim($attribute->value);
1011 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
1012 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
1018 * @brief Check for pump.io contact
1020 * @param array $webfinger Webfinger data
1022 * @return array pump.io data
1024 private function pumpio($webfinger) {
1027 foreach ($webfinger["links"] AS $link) {
1028 if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
1029 ($link["type"] == "text/html") AND ($link["href"] != ""))
1030 $data["url"] = $link["href"];
1031 elseif (($link["rel"] == "activity-inbox") AND ($link["href"] != ""))
1032 $data["notify"] = $link["href"];
1033 elseif (($link["rel"] == "activity-outbox") AND ($link["href"] != ""))
1034 $data["poll"] = $link["href"];
1035 elseif (($link["rel"] == "dialback") AND ($link["href"] != ""))
1036 $data["dialback"] = $link["href"];
1038 if (isset($data["poll"]) AND isset($data["notify"]) AND
1039 isset($data["dialback"]) AND isset($data["url"])) {
1041 // by now we use these fields only for the network type detection
1042 // So we unset all data that isn't used at the moment
1043 unset($data["dialback"]);
1045 $data["network"] = NETWORK_PUMPIO;
1049 $profile_data = self::pumpio_profile_data($data["url"]);
1054 $data = array_merge($data, $profile_data);
1060 * @brief Check page for feed link
1062 * @param string $url Page link
1064 * @return string feed link
1066 private function get_feed_link($url) {
1067 $doc = new DOMDocument();
1069 if (!@$doc->loadHTMLFile($url))
1072 $xpath = new DomXPath($doc);
1074 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1075 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1076 if (!is_object($feeds))
1079 if ($feeds->length == 0)
1084 foreach ($feeds AS $feed) {
1086 foreach ($feed->attributes as $attribute)
1087 $attr[$attribute->name] = trim($attribute->value);
1089 if ($feed_url == "")
1090 $feed_url = $attr["href"];
1097 * @brief Check for feed contact
1099 * @param string $url Profile link
1100 * @param boolean $probe Do a probe if the page contains a feed link
1102 * @return array feed data
1104 private function feed($url, $probe = true) {
1105 $ret = z_fetch_url($url);
1106 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1109 $feed = $ret['body'];
1110 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1116 $feed_url = self::get_feed_link($url);
1121 return self::feed($feed_url, false);
1124 if ($feed_data["header"]["author-name"] != "")
1125 $data["name"] = $feed_data["header"]["author-name"];
1127 if ($feed_data["header"]["author-nick"] != "")
1128 $data["nick"] = $feed_data["header"]["author-nick"];
1130 if ($feed_data["header"]["author-avatar"] != "")
1131 $data["photo"] = $feed_data["header"]["author-avatar"];
1133 if ($feed_data["header"]["author-id"] != "")
1134 $data["alias"] = $feed_data["header"]["author-id"];
1136 $data["url"] = $url;
1137 $data["poll"] = $url;
1139 if ($feed_data["header"]["author-link"] != "")
1140 $data["baseurl"] = $feed_data["header"]["author-link"];
1142 $data["baseurl"] = $data["url"];
1144 $data["network"] = NETWORK_FEED;
1150 * @brief Check for mail contact
1152 * @param string $uri Profile link
1153 * @param integer $uid User ID
1155 * @return array mail data
1157 private function mail($uri, $uid) {
1159 if (!validate_email($uri))
1162 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1164 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1166 if (dbm::is_result($x) && dbm::is_result($r)) {
1167 $mailbox = construct_mailbox_name($r[0]);
1169 openssl_private_decrypt(hex2bin($r[0]['pass']), $password,$x[0]['prvkey']);
1170 $mbox = email_connect($mailbox,$r[0]['user'], $password);
1175 $msgs = email_poll($mbox, $uri);
1176 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1183 $data["addr"] = $uri;
1184 $data["network"] = NETWORK_MAIL;
1185 $data["name"] = substr($uri, 0, strpos($uri,'@'));
1186 $data["nick"] = $data["name"];
1187 $data["photo"] = avatar_img($uri);
1189 $phost = substr($uri, strpos($uri,'@') + 1);
1190 $data["url"] = 'http://'.$phost."/".$data["nick"];
1191 $data["notify"] = 'smtp '.random_string();
1192 $data["poll"] = 'email '.random_string();
1194 $x = email_msg_meta($mbox, $msgs[0]);
1195 if(stristr($x[0]->from, $uri))
1196 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1197 elseif(stristr($x[0]->to, $uri))
1198 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1200 foreach($adr as $feadr) {
1201 if((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1202 &&(strcasecmp($feadr->host, $phost) == 0)
1203 && (strlen($feadr->personal))) {
1205 $personal = imap_mime_header_decode($feadr->personal);
1207 foreach($personal as $perspart)
1208 if ($perspart->charset != "default")
1209 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1211 $data["name"] .= $perspart->text;
1213 $data["name"] = notags($data["name"]);