3 * @file include/Probe.php
4 * @brief Functions for probing URL
9 use Friendica\Core\Config;
10 use Friendica\Core\PConfig;
12 require_once("include/feed.php");
13 require_once('include/email.php');
14 require_once('include/network.php');
17 * @brief This class contain functions for probing URL
22 private static $baseurl;
25 * @brief Rearrange the array so that it always has the same order
27 * @param array $data Unordered data
29 * @return array Ordered data
31 private function rearrange_data($data) {
32 $fields = array("name", "nick", "guid", "url", "addr", "alias",
33 "photo", "community", "keywords", "location", "about",
34 "batch", "notify", "poll", "request", "confirm", "poco",
35 "priority", "network", "pubkey", "baseurl");
38 foreach ($fields AS $field)
39 if (isset($data[$field]))
40 $newdata[$field] = $data[$field];
42 $newdata[$field] = "";
44 // We don't use the "priority" field anymore and replace it with a dummy.
45 $newdata["priority"] = 0;
51 * @brief Probes for XRD data
54 * 'lrdd' => Link to LRDD endpoint
55 * 'lrdd-xml' => Link to LRDD endpoint in XML format
56 * 'lrdd-json' => Link to LRDD endpoint in JSON format
58 private function xrd($host) {
60 // Reset the static variable
63 $ssl_url = "https://".$host."/.well-known/host-meta";
64 $url = "http://".$host."/.well-known/host-meta";
66 $xrd_timeout = Config::get('system','xrd_timeout', 20);
69 $ret = z_fetch_url($ssl_url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
70 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
75 $xrd = parse_xml_string($xml, false);
77 if (!is_object($xrd)) {
78 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
79 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
83 $xrd = parse_xml_string($xml, false);
88 $links = xml::element_to_array($xrd);
89 if (!isset($links["xrd"]["link"]))
94 foreach ($links["xrd"]["link"] AS $value => $link) {
95 if (isset($link["@attributes"]))
96 $attributes = $link["@attributes"];
97 elseif ($value == "@attributes")
102 if (($attributes["rel"] == "lrdd") AND
103 ($attributes["type"] == "application/xrd+xml"))
104 $xrd_data["lrdd-xml"] = $attributes["template"];
105 elseif (($attributes["rel"] == "lrdd") AND
106 ($attributes["type"] == "application/json"))
107 $xrd_data["lrdd-json"] = $attributes["template"];
108 elseif ($attributes["rel"] == "lrdd")
109 $xrd_data["lrdd"] = $attributes["template"];
112 self::$baseurl = "http://".$host;
118 * @brief Perform Webfinger lookup and return DFRN data
120 * Given an email style address, perform webfinger lookup and
121 * return the resulting DFRN profile URL, or if no DFRN profile URL
122 * is located, returns an OStatus subscription template (prefixed
123 * with the string 'stat:' to identify it as on OStatus template).
124 * If this isn't an email style address just return $webbie.
125 * Return an empty string if email-style addresses but webfinger fails,
126 * or if the resultant personal XRD doesn't contain a supported
127 * subscription/friend-request attribute.
129 * amended 7/9/2011 to return an hcard which could save potentially loading
130 * a lengthy content page to scrape dfrn attributes
132 * @param string $webbie Address that should be probed
133 * @param string $hcard Link to the hcard - is returned by reference
135 * @return string profile link
138 public static function webfinger_dfrn($webbie, &$hcard) {
142 $links = self::lrdd($webbie);
143 logger('webfinger_dfrn: '.$webbie.':'.print_r($links,true), LOGGER_DATA);
145 foreach ($links as $link) {
146 if ($link['@attributes']['rel'] === NAMESPACE_DFRN)
147 $profile_link = $link['@attributes']['href'];
148 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) AND ($profile_link == ""))
149 $profile_link = 'stat:'.$link['@attributes']['template'];
150 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
151 $hcard = $link['@attributes']['href'];
154 return $profile_link;
158 * @brief Check an URI for LRDD data
160 * this is a replacement for the "lrdd" function in include/network.php.
161 * It isn't used in this class and has some redundancies in the code.
162 * When time comes we can check the existing calls for "lrdd" if we can rework them.
164 * @param string $uri Address that should be probed
166 * @return array uri data
168 public static function lrdd($uri) {
170 $lrdd = self::xrd($uri);
173 $parts = @parse_url($uri);
177 $host = $parts["host"];
179 $path_parts = explode("/", trim($parts["path"], "/"));
181 $nick = array_pop($path_parts);
184 $lrdd = self::xrd($host);
185 $host .= "/".array_shift($path_parts);
186 } while (!$lrdd AND (sizeof($path_parts) > 0));
192 foreach ($lrdd AS $key => $link) {
196 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json")))
199 $path = str_replace('{uri}', urlencode($uri), $link);
200 $webfinger = self::webfinger($path);
202 if (!$webfinger AND (strstr($uri, "@"))) {
203 $path = str_replace('{uri}', urlencode("acct:".$uri), $link);
204 $webfinger = self::webfinger($path);
207 // Special treatment for Mastodon
208 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
209 // But the webfinger for this format fails.
210 if (!$webfinger AND isset($nick)) {
211 // Mastodon uses a "@" as prefix for usernames in their url format
212 $nick = ltrim($nick, '@');
214 $addr = $nick."@".$host;
216 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
217 $webfinger = self::webfinger($path);
221 if (!is_array($webfinger["links"]))
226 foreach ($webfinger["links"] AS $link)
227 $data[] = array("@attributes" => $link);
229 if (is_array($webfinger["aliases"]))
230 foreach ($webfinger["aliases"] AS $alias)
231 $data[] = array("@attributes" =>
232 array("rel" => "alias",
239 * @brief Fetch information (protocol endpoints and user information) about a given uri
241 * @param string $uri Address that should be probed
242 * @param string $network Test for this specific network
243 * @param integer $uid User ID for the probe (only used for mails)
244 * @param boolean $cache Use cached values?
246 * @return array uri data
248 public static function uri($uri, $network = "", $uid = 0, $cache = true) {
251 $result = Cache::get("probe_url:".$network.":".$uri);
252 if (!is_null($result)) {
260 $data = self::detect($uri, $network, $uid);
262 if (!isset($data["url"]))
265 if ($data["photo"] != "")
266 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
268 $data["photo"] = App::get_baseurl().'/images/person-175.jpg';
270 if (!isset($data["name"]) OR ($data["name"] == "")) {
271 if (isset($data["nick"]))
272 $data["name"] = $data["nick"];
274 if ($data["name"] == "")
275 $data["name"] = $data["url"];
278 if (!isset($data["nick"]) OR ($data["nick"] == "")) {
279 $data["nick"] = strtolower($data["name"]);
281 if (strpos($data['nick'], ' '))
282 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
285 if (self::$baseurl != "") {
286 $data["baseurl"] = self::$baseurl;
289 if (!isset($data["network"])) {
290 $data["network"] = NETWORK_PHANTOM;
293 $data = self::rearrange_data($data);
295 // Only store into the cache if the value seems to be valid
296 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
297 Cache::set("probe_url:".$network.":".$uri, $data, CACHE_DAY);
299 /// @todo temporary fix - we need a real contact update function that updates only changing fields
300 /// The biggest problem is the avatar picture that could have a reduced image size.
301 /// It should only be updated if the existing picture isn't existing anymore.
302 if (($data['network'] != NETWORK_FEED) AND ($mode == PROBE_NORMAL) AND
303 $data["name"] AND $data["nick"] AND $data["url"] AND $data["addr"] AND $data["poll"])
304 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `url` = '%s', `addr` = '%s',
305 `notify` = '%s', `poll` = '%s', `alias` = '%s', `success_update` = '%s'
306 WHERE `nurl` = '%s' AND NOT `self` AND `uid` = 0",
307 dbesc($data["name"]),
308 dbesc($data["nick"]),
310 dbesc($data["addr"]),
311 dbesc($data["notify"]),
312 dbesc($data["poll"]),
313 dbesc($data["alias"]),
314 dbesc(datetime_convert()),
315 dbesc(normalise_link($data['url']))
323 * @brief Fetch information (protocol endpoints and user information) about a given uri
325 * This function is only called by the "uri" function that adds caching and rearranging of data.
327 * @param string $uri Address that should be probed
328 * @param string $network Test for this specific network
329 * @param integer $uid User ID for the probe (only used for mails)
331 * @return array uri data
333 private function detect($uri, $network, $uid) {
334 $parts = parse_url($uri);
336 if (isset($parts["scheme"]) AND isset($parts["host"]) AND isset($parts["path"])) {
339 $host = $parts["host"];
341 if ($host == 'twitter.com') {
342 return array("network" => NETWORK_TWITTER);
344 $lrdd = self::xrd($host);
346 $path_parts = explode("/", trim($parts["path"], "/"));
348 while (!$lrdd AND (sizeof($path_parts) > 1)) {
349 $host .= "/".array_shift($path_parts);
350 $lrdd = self::xrd($host);
353 return self::feed($uri);
355 $nick = array_pop($path_parts);
357 // Mastodon uses a "@" as prefix for usernames in their url format
358 $nick = ltrim($nick, '@');
360 $addr = $nick."@".$host;
361 } elseif (strstr($uri, '@')) {
362 // If the URI starts with "mailto:" then jump directly to the mail detection
363 if (strpos($url,'mailto:') !== false) {
364 $uri = str_replace('mailto:', '', $url);
365 return self::mail($uri, $uid);
368 if ($network == NETWORK_MAIL) {
369 return self::mail($uri, $uid);
371 // Remove "acct:" from the URI
372 $uri = str_replace('acct:', '', $uri);
374 $host = substr($uri,strpos($uri, '@') + 1);
375 $nick = substr($uri,0, strpos($uri, '@'));
377 if (strpos($uri, '@twitter.com')) {
378 return array("network" => NETWORK_TWITTER);
380 $lrdd = self::xrd($host);
383 return self::mail($uri, $uid);
392 /// @todo Do we need the prefix "acct:" or "acct://"?
394 foreach ($lrdd AS $key => $link) {
398 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
401 // At first try it with the given uri
402 $path = str_replace('{uri}', urlencode($uri), $link);
403 $webfinger = self::webfinger($path);
405 // We cannot be sure that the detected address was correct, so we don't use the values
406 if ($webfinger AND ($uri != $addr)) {
411 // Try webfinger with the address (user@domain.tld)
413 $path = str_replace('{uri}', urlencode($addr), $link);
414 $webfinger = self::webfinger($path);
417 // Mastodon needs to have it with "acct:"
419 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
420 $webfinger = self::webfinger($path);
424 return self::feed($uri);
429 logger("Probing ".$uri, LOGGER_DEBUG);
431 if (in_array($network, array("", NETWORK_DFRN)))
432 $result = self::dfrn($webfinger);
433 if ((!$result AND ($network == "")) OR ($network == NETWORK_DIASPORA))
434 $result = self::diaspora($webfinger);
435 if ((!$result AND ($network == "")) OR ($network == NETWORK_OSTATUS))
436 $result = self::ostatus($webfinger);
437 if ((!$result AND ($network == "")) OR ($network == NETWORK_PUMPIO))
438 $result = self::pumpio($webfinger);
439 if ((!$result AND ($network == "")) OR ($network == NETWORK_FEED))
440 $result = self::feed($uri);
442 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
443 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
444 if ((!isset($result["nick"]) OR ($result["nick"] == "") OR (strstr($result["nick"], " "))) AND ($nick != ""))
445 $result["nick"] = $nick;
447 if ((!isset($result["addr"]) OR ($result["addr"] == "")) AND ($addr != ""))
448 $result["addr"] = $addr;
451 logger($uri." is ".$result["network"], LOGGER_DEBUG);
453 if (!isset($result["baseurl"]) OR ($result["baseurl"] == "")) {
454 $pos = strpos($result["url"], $host);
456 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
463 * @brief Perform a webfinger request.
465 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
467 * @param string $url Address that should be probed
469 * @return array webfinger data
471 private function webfinger($url) {
473 $xrd_timeout = Config::get('system','xrd_timeout', 20);
476 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
477 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
480 $data = $ret['body'];
482 $xrd = parse_xml_string($data, false);
484 if (!is_object($xrd)) {
485 // If it is not XML, maybe it is JSON
486 $webfinger = json_decode($data, true);
488 if (!isset($webfinger["links"]))
494 $xrd_arr = xml::element_to_array($xrd);
495 if (!isset($xrd_arr["xrd"]["link"]))
498 $webfinger = array();
500 if (isset($xrd_arr["xrd"]["subject"]))
501 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
503 if (isset($xrd_arr["xrd"]["alias"]))
504 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
506 $webfinger["links"] = array();
508 foreach ($xrd_arr["xrd"]["link"] AS $value => $data) {
509 if (isset($data["@attributes"]))
510 $attributes = $data["@attributes"];
511 elseif ($value == "@attributes")
516 $webfinger["links"][] = $attributes;
522 * @brief Poll the Friendica specific noscrape page.
524 * "noscrape" is a faster alternative to fetch the data from the hcard.
525 * This functionality was originally created for the directory.
527 * @param string $noscrape Link to the noscrape page
528 * @param array $data The already fetched data
530 * @return array noscrape data
532 private function poll_noscrape($noscrape, $data) {
533 $ret = z_fetch_url($noscrape);
534 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
537 $content = $ret['body'];
542 $json = json_decode($content, true);
543 if (!is_array($json))
546 if (isset($json["fn"]))
547 $data["name"] = $json["fn"];
549 if (isset($json["addr"]))
550 $data["addr"] = $json["addr"];
552 if (isset($json["nick"]))
553 $data["nick"] = $json["nick"];
555 if (isset($json["comm"]))
556 $data["community"] = $json["comm"];
558 if (isset($json["tags"])) {
559 $keywords = implode(" ", $json["tags"]);
561 $data["keywords"] = $keywords;
564 $location = formatted_location($json);
566 $data["location"] = $location;
568 if (isset($json["about"]))
569 $data["about"] = $json["about"];
571 if (isset($json["key"]))
572 $data["pubkey"] = $json["key"];
574 if (isset($json["photo"]))
575 $data["photo"] = $json["photo"];
577 if (isset($json["dfrn-request"]))
578 $data["request"] = $json["dfrn-request"];
580 if (isset($json["dfrn-confirm"]))
581 $data["confirm"] = $json["dfrn-confirm"];
583 if (isset($json["dfrn-notify"]))
584 $data["notify"] = $json["dfrn-notify"];
586 if (isset($json["dfrn-poll"]))
587 $data["poll"] = $json["dfrn-poll"];
593 * @brief Check for valid DFRN data
595 * @param array $data DFRN data
597 * @return int Number of errors
599 public static function valid_dfrn($data) {
601 if(!isset($data['key']))
603 if(!isset($data['dfrn-request']))
605 if(!isset($data['dfrn-confirm']))
607 if(!isset($data['dfrn-notify']))
609 if(!isset($data['dfrn-poll']))
615 * @brief Fetch data from a DFRN profile page and via "noscrape"
617 * @param string $profile Link to the profile page
619 * @return array profile data
621 public static function profile($profile) {
625 logger("Check profile ".$profile, LOGGER_DEBUG);
627 // Fetch data via noscrape - this is faster
628 $noscrape = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile);
629 $data = self::poll_noscrape($noscrape, $data);
631 if (!isset($data["notify"]) OR !isset($data["confirm"]) OR
632 !isset($data["request"]) OR !isset($data["poll"]) OR
633 !isset($data["poco"]) OR !isset($data["name"]) OR
634 !isset($data["photo"]))
635 $data = self::poll_hcard($profile, $data, true);
637 $prof_data = array();
638 $prof_data["addr"] = $data["addr"];
639 $prof_data["nick"] = $data["nick"];
640 $prof_data["dfrn-request"] = $data["request"];
641 $prof_data["dfrn-confirm"] = $data["confirm"];
642 $prof_data["dfrn-notify"] = $data["notify"];
643 $prof_data["dfrn-poll"] = $data["poll"];
644 $prof_data["dfrn-poco"] = $data["poco"];
645 $prof_data["photo"] = $data["photo"];
646 $prof_data["fn"] = $data["name"];
647 $prof_data["key"] = $data["pubkey"];
649 logger("Result for profile ".$profile.": ".print_r($prof_data, true), LOGGER_DEBUG);
655 * @brief Check for DFRN contact
657 * @param array $webfinger Webfinger data
659 * @return array DFRN data
661 private function dfrn($webfinger) {
665 foreach ($webfinger["links"] AS $link) {
666 if (($link["rel"] == NAMESPACE_DFRN) AND ($link["href"] != ""))
667 $data["network"] = NETWORK_DFRN;
668 elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
669 $data["poll"] = $link["href"];
670 elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
671 ($link["type"] == "text/html") AND ($link["href"] != ""))
672 $data["url"] = $link["href"];
673 elseif (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != ""))
674 $hcard = $link["href"];
675 elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != ""))
676 $data["poco"] = $link["href"];
677 elseif (($link["rel"] == "http://webfinger.net/rel/avatar") AND ($link["href"] != ""))
678 $data["photo"] = $link["href"];
680 elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != ""))
681 $data["baseurl"] = trim($link["href"], '/');
682 elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != ""))
683 $data["guid"] = $link["href"];
684 elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
685 $data["pubkey"] = base64_decode($link["href"]);
687 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
688 if (strstr($data["pubkey"], 'RSA '))
689 $data["pubkey"] = rsatopem($data["pubkey"]);
693 if (!isset($data["network"]) OR ($hcard == ""))
696 // Fetch data via noscrape - this is faster
697 $noscrape = str_replace("/hcard/", "/noscrape/", $hcard);
698 $data = self::poll_noscrape($noscrape, $data);
700 if (isset($data["notify"]) AND isset($data["confirm"]) AND isset($data["request"]) AND
701 isset($data["poll"]) AND isset($data["name"]) AND isset($data["photo"]))
704 $data = self::poll_hcard($hcard, $data, true);
710 * @brief Poll the hcard page (Diaspora and Friendica specific)
712 * @param string $hcard Link to the hcard page
713 * @param array $data The already fetched data
714 * @param boolean $dfrn Poll DFRN specific data
716 * @return array hcard data
718 private function poll_hcard($hcard, $data, $dfrn = false) {
719 $ret = z_fetch_url($hcard);
720 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
723 $content = $ret['body'];
728 $doc = new DOMDocument();
729 if (!@$doc->loadHTML($content))
732 $xpath = new DomXPath($doc);
734 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
735 if (!is_object($vcards))
738 if ($vcards->length > 0) {
739 $vcard = $vcards->item(0);
741 // We have to discard the guid from the hcard in favour of the guid from lrdd
742 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
743 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
744 if (($search->length > 0) AND ($data["guid"] == ""))
745 $data["guid"] = $search->item(0)->nodeValue;
747 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
748 if ($search->length > 0)
749 $data["nick"] = $search->item(0)->nodeValue;
751 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
752 if ($search->length > 0)
753 $data["name"] = $search->item(0)->nodeValue;
755 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
756 if ($search->length > 0)
757 $data["searchable"] = $search->item(0)->nodeValue;
759 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
760 if ($search->length > 0) {
761 $data["pubkey"] = $search->item(0)->nodeValue;
762 if (strstr($data["pubkey"], 'RSA '))
763 $data["pubkey"] = rsatopem($data["pubkey"]);
766 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
767 if ($search->length > 0)
768 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
772 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
773 foreach ($photos AS $photo) {
775 foreach ($photo->attributes as $attribute) {
776 $attr[$attribute->name] = trim($attribute->value);
779 if (isset($attr["src"]) AND isset($attr["width"])) {
780 $avatar[$attr["width"]] = $attr["src"];
783 // We don't have a width. So we just take everything that we got.
784 // This is a Hubzilla workaround which doesn't send a width.
785 if ((sizeof($avatar) == 0) AND isset($attr["src"])) {
786 $avatar[] = $attr["src"];
790 if (sizeof($avatar)) {
792 $data["photo"] = array_pop($avatar);
796 // Poll DFRN specific data
797 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
798 if ($search->length > 0) {
799 foreach ($search AS $link) {
800 //$data["request"] = $search->item(0)->nodeValue;
802 foreach ($link->attributes as $attribute)
803 $attr[$attribute->name] = trim($attribute->value);
805 $data[substr($attr["rel"], 5)] = $attr["href"];
809 // Older Friendica versions had used the "uid" field differently than newer versions
810 if ($data["nick"] == $data["guid"])
811 unset($data["guid"]);
819 * @brief Check for Diaspora contact
821 * @param array $webfinger Webfinger data
823 * @return array Diaspora data
825 private function diaspora($webfinger) {
829 foreach ($webfinger["links"] AS $link) {
830 if (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != ""))
831 $hcard = $link["href"];
832 elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != ""))
833 $data["baseurl"] = trim($link["href"], '/');
834 elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != ""))
835 $data["guid"] = $link["href"];
836 elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
837 ($link["type"] == "text/html") AND ($link["href"] != ""))
838 $data["url"] = $link["href"];
839 elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
840 $data["poll"] = $link["href"];
841 elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != ""))
842 $data["poco"] = $link["href"];
843 elseif (($link["rel"] == "salmon") AND ($link["href"] != ""))
844 $data["notify"] = $link["href"];
845 elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
846 $data["pubkey"] = base64_decode($link["href"]);
848 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
849 if (strstr($data["pubkey"], 'RSA '))
850 $data["pubkey"] = rsatopem($data["pubkey"]);
854 if (!isset($data["url"]) OR ($hcard == ""))
857 if (is_array($webfinger["aliases"]))
858 foreach ($webfinger["aliases"] AS $alias)
859 if (normalise_link($alias) != normalise_link($data["url"]) AND !strstr($alias, "@"))
860 $data["alias"] = $alias;
862 // Fetch further information from the hcard
863 $data = self::poll_hcard($hcard, $data);
868 if (isset($data["url"]) AND isset($data["guid"]) AND isset($data["baseurl"]) AND
869 isset($data["pubkey"]) AND ($hcard != "")) {
870 $data["network"] = NETWORK_DIASPORA;
872 // The Diaspora handle must always be lowercase
873 $data["addr"] = strtolower($data["addr"]);
875 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
876 $data["notify"] = $data["baseurl"]."/receive/users/".$data["guid"];
877 $data["batch"] = $data["baseurl"]."/receive/public";
885 * @brief Check for OStatus contact
887 * @param array $webfinger Webfinger data
889 * @return array OStatus data
891 private function ostatus($webfinger) {
893 if (is_array($webfinger["aliases"])) {
894 foreach ($webfinger["aliases"] AS $alias) {
895 if (strstr($alias, "@")) {
896 $data["addr"] = str_replace('acct:', '', $alias);
901 if (is_string($webfinger["subject"]) AND strstr($webfinger["subject"], "@")) {
902 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
905 foreach ($webfinger["links"] AS $link) {
906 if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
907 ($link["type"] == "text/html") AND ($link["href"] != "")) {
908 $data["url"] = $link["href"];
909 } elseif (($link["rel"] == "salmon") AND ($link["href"] != "")) {
910 $data["notify"] = $link["href"];
911 } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
912 $data["poll"] = $link["href"];
913 } elseif (($link["rel"] == "magic-public-key") AND ($link["href"] != "")) {
914 $pubkey = $link["href"];
916 if (substr($pubkey, 0, 5) === 'data:') {
917 if (strstr($pubkey, ',')) {
918 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
920 $pubkey = substr($pubkey, 5);
922 } elseif (normalise_link($pubkey) == 'http://') {
923 $ret = z_fetch_url($pubkey);
924 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
927 $pubkey = $ret['body'];
930 $key = explode(".", $pubkey);
932 if (sizeof($key) >= 3) {
933 $m = base64url_decode($key[1]);
934 $e = base64url_decode($key[2]);
935 $data["pubkey"] = metopem($m,$e);
940 if (isset($data["notify"]) AND isset($data["pubkey"]) AND
941 isset($data["poll"]) AND isset($data["url"])) {
942 $data["network"] = NETWORK_OSTATUS;
946 // Fetch all additional data from the feed
947 $ret = z_fetch_url($data["poll"]);
948 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
951 $feed = $ret['body'];
952 $feed_data = feed_import($feed,$dummy1,$dummy2, $dummy3, true);
956 if ($feed_data["header"]["author-name"] != "") {
957 $data["name"] = $feed_data["header"]["author-name"];
959 if ($feed_data["header"]["author-nick"] != "") {
960 $data["nick"] = $feed_data["header"]["author-nick"];
962 if ($feed_data["header"]["author-avatar"] != "") {
963 $data["photo"] = ostatus::fix_avatar($feed_data["header"]["author-avatar"], $data["url"]);
965 if ($feed_data["header"]["author-id"] != "") {
966 $data["alias"] = $feed_data["header"]["author-id"];
968 if ($feed_data["header"]["author-location"] != "") {
969 $data["location"] = $feed_data["header"]["author-location"];
971 if ($feed_data["header"]["author-about"] != "") {
972 $data["about"] = $feed_data["header"]["author-about"];
974 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
975 // So we take the value that we just fetched, although the other one worked as well
976 if ($feed_data["header"]["author-link"] != "") {
977 $data["url"] = $feed_data["header"]["author-link"];
979 /// @todo Fetch location and "about" from the feed as well
984 * @brief Fetch data from a pump.io profile page
986 * @param string $profile Link to the profile page
988 * @return array profile data
990 private function pumpio_profile_data($profile) {
992 $doc = new DOMDocument();
993 if (!@$doc->loadHTMLFile($profile))
996 $xpath = new DomXPath($doc);
1000 // This is ugly - but pump.io doesn't seem to know a better way for it
1001 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1002 $pos = strpos($data["name"], chr(10));
1004 $data["name"] = trim(substr($data["name"], 0, $pos));
1006 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1008 foreach ($avatar->attributes as $attribute)
1009 if ($attribute->name == "src")
1010 $data["photo"] = trim($attribute->value);
1012 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
1013 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
1019 * @brief Check for pump.io contact
1021 * @param array $webfinger Webfinger data
1023 * @return array pump.io data
1025 private function pumpio($webfinger) {
1028 foreach ($webfinger["links"] AS $link) {
1029 if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
1030 ($link["type"] == "text/html") AND ($link["href"] != ""))
1031 $data["url"] = $link["href"];
1032 elseif (($link["rel"] == "activity-inbox") AND ($link["href"] != ""))
1033 $data["notify"] = $link["href"];
1034 elseif (($link["rel"] == "activity-outbox") AND ($link["href"] != ""))
1035 $data["poll"] = $link["href"];
1036 elseif (($link["rel"] == "dialback") AND ($link["href"] != ""))
1037 $data["dialback"] = $link["href"];
1039 if (isset($data["poll"]) AND isset($data["notify"]) AND
1040 isset($data["dialback"]) AND isset($data["url"])) {
1042 // by now we use these fields only for the network type detection
1043 // So we unset all data that isn't used at the moment
1044 unset($data["dialback"]);
1046 $data["network"] = NETWORK_PUMPIO;
1050 $profile_data = self::pumpio_profile_data($data["url"]);
1055 $data = array_merge($data, $profile_data);
1061 * @brief Check page for feed link
1063 * @param string $url Page link
1065 * @return string feed link
1067 private function get_feed_link($url) {
1068 $doc = new DOMDocument();
1070 if (!@$doc->loadHTMLFile($url))
1073 $xpath = new DomXPath($doc);
1075 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1076 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1077 if (!is_object($feeds))
1080 if ($feeds->length == 0)
1085 foreach ($feeds AS $feed) {
1087 foreach ($feed->attributes as $attribute)
1088 $attr[$attribute->name] = trim($attribute->value);
1090 if ($feed_url == "")
1091 $feed_url = $attr["href"];
1098 * @brief Check for feed contact
1100 * @param string $url Profile link
1101 * @param boolean $probe Do a probe if the page contains a feed link
1103 * @return array feed data
1105 private function feed($url, $probe = true) {
1106 $ret = z_fetch_url($url);
1107 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1110 $feed = $ret['body'];
1111 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1117 $feed_url = self::get_feed_link($url);
1122 return self::feed($feed_url, false);
1125 if ($feed_data["header"]["author-name"] != "")
1126 $data["name"] = $feed_data["header"]["author-name"];
1128 if ($feed_data["header"]["author-nick"] != "")
1129 $data["nick"] = $feed_data["header"]["author-nick"];
1131 if ($feed_data["header"]["author-avatar"] != "")
1132 $data["photo"] = $feed_data["header"]["author-avatar"];
1134 if ($feed_data["header"]["author-id"] != "")
1135 $data["alias"] = $feed_data["header"]["author-id"];
1137 $data["url"] = $url;
1138 $data["poll"] = $url;
1140 if ($feed_data["header"]["author-link"] != "")
1141 $data["baseurl"] = $feed_data["header"]["author-link"];
1143 $data["baseurl"] = $data["url"];
1145 $data["network"] = NETWORK_FEED;
1151 * @brief Check for mail contact
1153 * @param string $uri Profile link
1154 * @param integer $uid User ID
1156 * @return array mail data
1158 private function mail($uri, $uid) {
1160 if (!validate_email($uri))
1163 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1165 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1167 if (dbm::is_result($x) && dbm::is_result($r)) {
1168 $mailbox = construct_mailbox_name($r[0]);
1170 openssl_private_decrypt(hex2bin($r[0]['pass']), $password,$x[0]['prvkey']);
1171 $mbox = email_connect($mailbox,$r[0]['user'], $password);
1176 $msgs = email_poll($mbox, $uri);
1177 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1184 $data["addr"] = $uri;
1185 $data["network"] = NETWORK_MAIL;
1186 $data["name"] = substr($uri, 0, strpos($uri,'@'));
1187 $data["nick"] = $data["name"];
1188 $data["photo"] = avatar_img($uri);
1190 $phost = substr($uri, strpos($uri,'@') + 1);
1191 $data["url"] = 'http://'.$phost."/".$data["nick"];
1192 $data["notify"] = 'smtp '.random_string();
1193 $data["poll"] = 'email '.random_string();
1195 $x = email_msg_meta($mbox, $msgs[0]);
1196 if(stristr($x[0]->from, $uri))
1197 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1198 elseif(stristr($x[0]->to, $uri))
1199 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1201 foreach($adr as $feadr) {
1202 if((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1203 &&(strcasecmp($feadr->host, $phost) == 0)
1204 && (strlen($feadr->personal))) {
1206 $personal = imap_mime_header_decode($feadr->personal);
1208 foreach($personal as $perspart)
1209 if ($perspart->charset != "default")
1210 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1212 $data["name"] .= $perspart->text;
1214 $data["name"] = notags($data["name"]);