3 namespace Friendica\Network;
6 * @file src/Network/Probe.php
7 * @brief Functions for probing URL
12 use Friendica\Core\Config;
13 use Friendica\Core\PConfig;
15 require_once 'include/feed.php';
16 require_once 'include/email.php';
17 require_once 'include/network.php';
20 * @brief This class contain functions for probing URL
25 private static $baseurl;
28 * @brief Rearrange the array so that it always has the same order
30 * @param array $data Unordered data
32 * @return array Ordered data
34 private function rearrangeData($data) {
35 $fields = array("name", "nick", "guid", "url", "addr", "alias",
36 "photo", "community", "keywords", "location", "about",
37 "batch", "notify", "poll", "request", "confirm", "poco",
38 "priority", "network", "pubkey", "baseurl");
41 foreach ($fields as $field) {
42 if (isset($data[$field])) {
43 $newdata[$field] = $data[$field];
45 $newdata[$field] = "";
49 // We don't use the "priority" field anymore and replace it with a dummy.
50 $newdata["priority"] = 0;
56 * @brief Probes for XRD data
58 * @param string $host The host part of an url
61 * 'lrdd' => Link to LRDD endpoint
62 * 'lrdd-xml' => Link to LRDD endpoint in XML format
63 * 'lrdd-json' => Link to LRDD endpoint in JSON format
65 private function xrd($host) {
67 // Reset the static variable
70 $ssl_url = "https://".$host."/.well-known/host-meta";
71 $url = "http://".$host."/.well-known/host-meta";
73 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
76 $ret = z_fetch_url($ssl_url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
77 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
82 $xrd = parse_xml_string($xml, false);
84 if (!is_object($xrd)) {
85 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
86 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
90 $xrd = parse_xml_string($xml, false);
92 if (!is_object($xrd)) {
96 $links = \xml::element_to_array($xrd);
97 if (!isset($links["xrd"]["link"])) {
103 foreach ($links["xrd"]["link"] as $value => $link) {
104 if (isset($link["@attributes"])) {
105 $attributes = $link["@attributes"];
106 } elseif ($value == "@attributes") {
112 if (($attributes["rel"] == "lrdd") AND
113 ($attributes["type"] == "application/xrd+xml")) {
114 $xrd_data["lrdd-xml"] = $attributes["template"];
115 } elseif (($attributes["rel"] == "lrdd") AND
116 ($attributes["type"] == "application/json")) {
117 $xrd_data["lrdd-json"] = $attributes["template"];
118 } elseif ($attributes["rel"] == "lrdd") {
119 $xrd_data["lrdd"] = $attributes["template"];
123 self::$baseurl = "http://".$host;
129 * @brief Perform Webfinger lookup and return DFRN data
131 * Given an email style address, perform webfinger lookup and
132 * return the resulting DFRN profile URL, or if no DFRN profile URL
133 * is located, returns an OStatus subscription template (prefixed
134 * with the string 'stat:' to identify it as on OStatus template).
135 * If this isn't an email style address just return $webbie.
136 * Return an empty string if email-style addresses but webfinger fails,
137 * or if the resultant personal XRD doesn't contain a supported
138 * subscription/friend-request attribute.
140 * amended 7/9/2011 to return an hcard which could save potentially loading
141 * a lengthy content page to scrape dfrn attributes
143 * @param string $webbie Address that should be probed
144 * @param string $hcard Link to the hcard - is returned by reference
146 * @return string profile link
149 public static function webfingerDfrn($webbie, &$hcard) {
153 $links = self::lrdd($webbie);
154 logger('webfingerDfrn: '.$webbie.':'.print_r($links, true), LOGGER_DATA);
156 foreach ($links as $link) {
157 if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
158 $profile_link = $link['@attributes']['href'];
160 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) AND ($profile_link == "")) {
161 $profile_link = 'stat:'.$link['@attributes']['template'];
163 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
164 $hcard = $link['@attributes']['href'];
168 return $profile_link;
172 * @brief Check an URI for LRDD data
174 * this is a replacement for the "lrdd" function in include/network.php.
175 * It isn't used in this class and has some redundancies in the code.
176 * When time comes we can check the existing calls for "lrdd" if we can rework them.
178 * @param string $uri Address that should be probed
180 * @return array uri data
182 public static function lrdd($uri) {
184 $lrdd = self::xrd($uri);
187 $parts = @parse_url($uri);
192 $host = $parts["host"];
193 if (isset($parts["port"])) {
194 $host .= ':'.$parts["port"];
197 $path_parts = explode("/", trim($parts["path"], "/"));
199 $nick = array_pop($path_parts);
202 $lrdd = self::xrd($host);
203 $host .= "/".array_shift($path_parts);
204 } while (!$lrdd AND (sizeof($path_parts) > 0));
211 foreach ($lrdd as $key => $link) {
216 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
220 $path = str_replace('{uri}', urlencode($uri), $link);
221 $webfinger = self::webfinger($path);
223 if (!$webfinger AND (strstr($uri, "@"))) {
224 $path = str_replace('{uri}', urlencode("acct:".$uri), $link);
225 $webfinger = self::webfinger($path);
228 // Special treatment for Mastodon
229 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
230 // But the webfinger for this format fails.
231 if (!$webfinger AND isset($nick)) {
232 // Mastodon uses a "@" as prefix for usernames in their url format
233 $nick = ltrim($nick, '@');
235 $addr = $nick."@".$host;
237 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
238 $webfinger = self::webfinger($path);
242 if (!is_array($webfinger["links"])) {
248 foreach ($webfinger["links"] as $link) {
249 $data[] = array("@attributes" => $link);
252 if (is_array($webfinger["aliases"])) {
253 foreach ($webfinger["aliases"] as $alias) {
254 $data[] = array("@attributes" =>
255 array("rel" => "alias",
264 * @brief Fetch information (protocol endpoints and user information) about a given uri
266 * @param string $uri Address that should be probed
267 * @param string $network Test for this specific network
268 * @param integer $uid User ID for the probe (only used for mails)
269 * @param boolean $cache Use cached values?
271 * @return array uri data
273 public static function uri($uri, $network = "", $uid = 0, $cache = true) {
276 $result = \Cache::get("probe_url:".$network.":".$uri);
277 if (!is_null($result)) {
286 $data = self::detect($uri, $network, $uid);
288 if (!isset($data["url"])) {
292 if ($data["photo"] != "") {
293 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
295 $data["photo"] = App::get_baseurl().'/images/person-175.jpg';
298 if (!isset($data["name"]) OR ($data["name"] == "")) {
299 if (isset($data["nick"])) {
300 $data["name"] = $data["nick"];
303 if ($data["name"] == "") {
304 $data["name"] = $data["url"];
308 if (!isset($data["nick"]) OR ($data["nick"] == "")) {
309 $data["nick"] = strtolower($data["name"]);
311 if (strpos($data['nick'], ' ')) {
312 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
316 if (self::$baseurl != "") {
317 $data["baseurl"] = self::$baseurl;
320 if (!isset($data["network"])) {
321 $data["network"] = NETWORK_PHANTOM;
324 $data = self::rearrangeData($data);
326 // Only store into the cache if the value seems to be valid
327 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
328 \Cache::set("probe_url:".$network.":".$uri, $data, CACHE_DAY);
330 /// @todo temporary fix - we need a real contact update function that updates only changing fields
331 /// The biggest problem is the avatar picture that could have a reduced image size.
332 /// It should only be updated if the existing picture isn't existing anymore.
333 if (($data['network'] != NETWORK_FEED) AND ($mode == PROBE_NORMAL) AND
334 $data["name"] AND $data["nick"] AND $data["url"] AND $data["addr"] AND $data["poll"]) {
335 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `url` = '%s', `addr` = '%s',
336 `notify` = '%s', `poll` = '%s', `alias` = '%s', `success_update` = '%s'
337 WHERE `nurl` = '%s' AND NOT `self` AND `uid` = 0",
338 dbesc($data["name"]),
339 dbesc($data["nick"]),
341 dbesc($data["addr"]),
342 dbesc($data["notify"]),
343 dbesc($data["poll"]),
344 dbesc($data["alias"]),
345 dbesc(datetime_convert()),
346 dbesc(normalise_link($data['url']))
355 * @brief Fetch information (protocol endpoints and user information) about a given uri
357 * This function is only called by the "uri" function that adds caching and rearranging of data.
359 * @param string $uri Address that should be probed
360 * @param string $network Test for this specific network
361 * @param integer $uid User ID for the probe (only used for mails)
363 * @return array uri data
365 private function detect($uri, $network, $uid) {
366 $parts = parse_url($uri);
368 if (isset($parts["scheme"]) AND isset($parts["host"]) AND isset($parts["path"])) {
369 $host = $parts["host"];
370 if (isset($parts["port"])) {
371 $host .= ':'.$parts["port"];
374 if ($host == 'twitter.com') {
375 return array("network" => NETWORK_TWITTER);
377 $lrdd = self::xrd($host);
379 $path_parts = explode("/", trim($parts["path"], "/"));
381 while (!$lrdd AND (sizeof($path_parts) > 1)) {
382 $host .= "/".array_shift($path_parts);
383 $lrdd = self::xrd($host);
386 return self::feed($uri);
388 $nick = array_pop($path_parts);
390 // Mastodon uses a "@" as prefix for usernames in their url format
391 $nick = ltrim($nick, '@');
393 $addr = $nick."@".$host;
395 } elseif (strstr($uri, '@')) {
396 // If the URI starts with "mailto:" then jump directly to the mail detection
397 if (strpos($url, 'mailto:') !== false) {
398 $uri = str_replace('mailto:', '', $url);
399 return self::mail($uri, $uid);
402 if ($network == NETWORK_MAIL) {
403 return self::mail($uri, $uid);
405 // Remove "acct:" from the URI
406 $uri = str_replace('acct:', '', $uri);
408 $host = substr($uri, strpos($uri, '@') + 1);
409 $nick = substr($uri, 0, strpos($uri, '@'));
411 if (strpos($uri, '@twitter.com')) {
412 return array("network" => NETWORK_TWITTER);
414 $lrdd = self::xrd($host);
417 return self::mail($uri, $uid);
427 /// @todo Do we need the prefix "acct:" or "acct://"?
429 foreach ($lrdd as $key => $link) {
433 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
436 // At first try it with the given uri
437 $path = str_replace('{uri}', urlencode($uri), $link);
438 $webfinger = self::webfinger($path);
440 // We cannot be sure that the detected address was correct, so we don't use the values
441 if ($webfinger AND ($uri != $addr)) {
446 // Try webfinger with the address (user@domain.tld)
448 $path = str_replace('{uri}', urlencode($addr), $link);
449 $webfinger = self::webfinger($path);
452 // Mastodon needs to have it with "acct:"
454 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
455 $webfinger = self::webfinger($path);
459 return self::feed($uri);
464 logger("Probing ".$uri, LOGGER_DEBUG);
466 if (in_array($network, array("", NETWORK_DFRN))) {
467 $result = self::dfrn($webfinger);
469 if ((!$result AND ($network == "")) OR ($network == NETWORK_DIASPORA)) {
470 $result = self::diaspora($webfinger);
472 if ((!$result AND ($network == "")) OR ($network == NETWORK_OSTATUS)) {
473 $result = self::ostatus($webfinger);
475 if ((!$result AND ($network == "")) OR ($network == NETWORK_PUMPIO)) {
476 $result = self::pumpio($webfinger);
478 if ((!$result AND ($network == "")) OR ($network == NETWORK_FEED)) {
479 $result = self::feed($uri);
481 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
482 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
483 if ((!isset($result["nick"]) OR ($result["nick"] == "") OR (strstr($result["nick"], " "))) AND ($nick != "")) {
484 $result["nick"] = $nick;
487 if ((!isset($result["addr"]) OR ($result["addr"] == "")) AND ($addr != "")) {
488 $result["addr"] = $addr;
492 logger($uri." is ".$result["network"], LOGGER_DEBUG);
494 if (!isset($result["baseurl"]) OR ($result["baseurl"] == "")) {
495 $pos = strpos($result["url"], $host);
497 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
505 * @brief Perform a webfinger request.
507 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
509 * @param string $url Address that should be probed
511 * @return array webfinger data
513 private function webfinger($url) {
515 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
518 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
519 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
522 $data = $ret['body'];
524 $xrd = parse_xml_string($data, false);
526 if (!is_object($xrd)) {
527 // If it is not XML, maybe it is JSON
528 $webfinger = json_decode($data, true);
530 if (!isset($webfinger["links"])) {
537 $xrd_arr = \xml::element_to_array($xrd);
538 if (!isset($xrd_arr["xrd"]["link"])) {
542 $webfinger = array();
544 if (isset($xrd_arr["xrd"]["subject"])) {
545 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
548 if (isset($xrd_arr["xrd"]["alias"])) {
549 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
552 $webfinger["links"] = array();
554 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
555 if (isset($data["@attributes"])) {
556 $attributes = $data["@attributes"];
557 } elseif ($value == "@attributes") {
563 $webfinger["links"][] = $attributes;
569 * @brief Poll the Friendica specific noscrape page.
571 * "noscrape" is a faster alternative to fetch the data from the hcard.
572 * This functionality was originally created for the directory.
574 * @param string $noscrape Link to the noscrape page
575 * @param array $data The already fetched data
577 * @return array noscrape data
579 private function pollNoscrape($noscrape, $data) {
580 $ret = z_fetch_url($noscrape);
581 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
584 $content = $ret['body'];
589 $json = json_decode($content, true);
590 if (!is_array($json)) {
594 if (isset($json["fn"])) {
595 $data["name"] = $json["fn"];
598 if (isset($json["addr"])) {
599 $data["addr"] = $json["addr"];
602 if (isset($json["nick"])) {
603 $data["nick"] = $json["nick"];
606 if (isset($json["comm"])) {
607 $data["community"] = $json["comm"];
610 if (isset($json["tags"])) {
611 $keywords = implode(" ", $json["tags"]);
612 if ($keywords != "") {
613 $data["keywords"] = $keywords;
617 $location = formatted_location($json);
619 $data["location"] = $location;
622 if (isset($json["about"])) {
623 $data["about"] = $json["about"];
626 if (isset($json["key"])) {
627 $data["pubkey"] = $json["key"];
630 if (isset($json["photo"])) {
631 $data["photo"] = $json["photo"];
634 if (isset($json["dfrn-request"])) {
635 $data["request"] = $json["dfrn-request"];
638 if (isset($json["dfrn-confirm"])) {
639 $data["confirm"] = $json["dfrn-confirm"];
642 if (isset($json["dfrn-notify"])) {
643 $data["notify"] = $json["dfrn-notify"];
646 if (isset($json["dfrn-poll"])) {
647 $data["poll"] = $json["dfrn-poll"];
654 * @brief Check for valid DFRN data
656 * @param array $data DFRN data
658 * @return int Number of errors
660 public static function validDfrn($data) {
662 if (!isset($data['key'])) {
665 if (!isset($data['dfrn-request'])) {
668 if (!isset($data['dfrn-confirm'])) {
671 if (!isset($data['dfrn-notify'])) {
674 if (!isset($data['dfrn-poll'])) {
681 * @brief Fetch data from a DFRN profile page and via "noscrape"
683 * @param string $profile Link to the profile page
685 * @return array profile data
687 public static function profile($profile) {
691 logger("Check profile ".$profile, LOGGER_DEBUG);
693 // Fetch data via noscrape - this is faster
694 $noscrape = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile);
695 $data = self::pollNoscrape($noscrape, $data);
697 if (!isset($data["notify"]) OR !isset($data["confirm"]) OR
698 !isset($data["request"]) OR !isset($data["poll"]) OR
699 !isset($data["poco"]) OR !isset($data["name"]) OR
700 !isset($data["photo"])) {
701 $data = self::pollHcard($profile, $data, true);
704 $prof_data = array();
705 $prof_data["addr"] = $data["addr"];
706 $prof_data["nick"] = $data["nick"];
707 $prof_data["dfrn-request"] = $data["request"];
708 $prof_data["dfrn-confirm"] = $data["confirm"];
709 $prof_data["dfrn-notify"] = $data["notify"];
710 $prof_data["dfrn-poll"] = $data["poll"];
711 $prof_data["dfrn-poco"] = $data["poco"];
712 $prof_data["photo"] = $data["photo"];
713 $prof_data["fn"] = $data["name"];
714 $prof_data["key"] = $data["pubkey"];
716 logger("Result for profile ".$profile.": ".print_r($prof_data, true), LOGGER_DEBUG);
722 * @brief Check for DFRN contact
724 * @param array $webfinger Webfinger data
726 * @return array DFRN data
728 private function dfrn($webfinger) {
732 foreach ($webfinger["links"] as $link) {
733 if (($link["rel"] == NAMESPACE_DFRN) AND ($link["href"] != "")) {
734 $data["network"] = NETWORK_DFRN;
735 } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
736 $data["poll"] = $link["href"];
737 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND ($link["type"] == "text/html") AND ($link["href"] != "")) {
738 $data["url"] = $link["href"];
739 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != "")) {
740 $hcard = $link["href"];
741 } elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != "")) {
742 $data["poco"] = $link["href"];
743 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") AND ($link["href"] != "")) {
744 $data["photo"] = $link["href"];
745 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != "")) {
746 $data["baseurl"] = trim($link["href"], '/');
747 } elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != "")) {
748 $data["guid"] = $link["href"];
749 } elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
750 $data["pubkey"] = base64_decode($link["href"]);
752 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
753 if (strstr($data["pubkey"], 'RSA ')) {
754 $data["pubkey"] = rsatopem($data["pubkey"]);
759 if (!isset($data["network"]) OR ($hcard == "")) {
763 // Fetch data via noscrape - this is faster
764 $noscrape = str_replace("/hcard/", "/noscrape/", $hcard);
765 $data = self::pollNoscrape($noscrape, $data);
767 if (isset($data["notify"]) AND isset($data["confirm"]) AND isset($data["request"]) AND
768 isset($data["poll"]) AND isset($data["name"]) AND isset($data["photo"])) {
772 $data = self::pollHcard($hcard, $data, true);
778 * @brief Poll the hcard page (Diaspora and Friendica specific)
780 * @param string $hcard Link to the hcard page
781 * @param array $data The already fetched data
782 * @param boolean $dfrn Poll DFRN specific data
784 * @return array hcard data
786 private function pollHcard($hcard, $data, $dfrn = false) {
787 $ret = z_fetch_url($hcard);
788 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
791 $content = $ret['body'];
796 $doc = new \DOMDocument();
797 if (!@$doc->loadHTML($content)) {
801 $xpath = new \DomXPath($doc);
803 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
804 if (!is_object($vcards)) {
808 if ($vcards->length > 0) {
809 $vcard = $vcards->item(0);
811 // We have to discard the guid from the hcard in favour of the guid from lrdd
812 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
813 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
814 if (($search->length > 0) AND ($data["guid"] == "")) {
815 $data["guid"] = $search->item(0)->nodeValue;
818 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
819 if ($search->length > 0) {
820 $data["nick"] = $search->item(0)->nodeValue;
823 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
824 if ($search->length > 0) {
825 $data["name"] = $search->item(0)->nodeValue;
828 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
829 if ($search->length > 0) {
830 $data["searchable"] = $search->item(0)->nodeValue;
833 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
834 if ($search->length > 0) {
835 $data["pubkey"] = $search->item(0)->nodeValue;
836 if (strstr($data["pubkey"], 'RSA ')) {
837 $data["pubkey"] = rsatopem($data["pubkey"]);
841 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
842 if ($search->length > 0) {
843 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
848 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
849 foreach ($photos as $photo) {
851 foreach ($photo->attributes as $attribute) {
852 $attr[$attribute->name] = trim($attribute->value);
855 if (isset($attr["src"]) AND isset($attr["width"])) {
856 $avatar[$attr["width"]] = $attr["src"];
859 // We don't have a width. So we just take everything that we got.
860 // This is a Hubzilla workaround which doesn't send a width.
861 if ((sizeof($avatar) == 0) AND isset($attr["src"])) {
862 $avatar[] = $attr["src"];
866 if (sizeof($avatar)) {
868 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
872 // Poll DFRN specific data
873 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
874 if ($search->length > 0) {
875 foreach ($search as $link) {
876 //$data["request"] = $search->item(0)->nodeValue;
878 foreach ($link->attributes as $attribute) {
879 $attr[$attribute->name] = trim($attribute->value);
882 $data[substr($attr["rel"], 5)] = $attr["href"];
886 // Older Friendica versions had used the "uid" field differently than newer versions
887 if ($data["nick"] == $data["guid"]) {
888 unset($data["guid"]);
897 * @brief Check for Diaspora contact
899 * @param array $webfinger Webfinger data
901 * @return array Diaspora data
903 private function diaspora($webfinger) {
907 foreach ($webfinger["links"] as $link) {
908 if (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != "")) {
909 $hcard = $link["href"];
910 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != "")) {
911 $data["baseurl"] = trim($link["href"], '/');
912 } elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != "")) {
913 $data["guid"] = $link["href"];
914 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND ($link["type"] == "text/html") AND ($link["href"] != "")) {
915 $data["url"] = $link["href"];
916 } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
917 $data["poll"] = $link["href"];
918 } elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != "")) {
919 $data["poco"] = $link["href"];
920 } elseif (($link["rel"] == "salmon") AND ($link["href"] != "")) {
921 $data["notify"] = $link["href"];
922 } elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
923 $data["pubkey"] = base64_decode($link["href"]);
925 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
926 if (strstr($data["pubkey"], 'RSA ')) {
927 $data["pubkey"] = rsatopem($data["pubkey"]);
932 if (!isset($data["url"]) OR ($hcard == "")) {
936 if (is_array($webfinger["aliases"])) {
937 foreach ($webfinger["aliases"] as $alias) {
938 if (normalise_link($alias) != normalise_link($data["url"]) AND ! strstr($alias, "@")) {
939 $data["alias"] = $alias;
944 // Fetch further information from the hcard
945 $data = self::pollHcard($hcard, $data);
951 if (isset($data["url"]) AND isset($data["guid"]) AND isset($data["baseurl"]) AND
952 isset($data["pubkey"]) AND ($hcard != "")) {
953 $data["network"] = NETWORK_DIASPORA;
955 // The Diaspora handle must always be lowercase
956 $data["addr"] = strtolower($data["addr"]);
958 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
959 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
960 $data["batch"] = $data["baseurl"] . "/receive/public";
969 * @brief Check for OStatus contact
971 * @param array $webfinger Webfinger data
973 * @return array OStatus data
975 private function ostatus($webfinger) {
977 if (is_array($webfinger["aliases"])) {
978 foreach ($webfinger["aliases"] as $alias) {
979 if (strstr($alias, "@")) {
980 $data["addr"] = str_replace('acct:', '', $alias);
985 if (is_string($webfinger["subject"]) AND strstr($webfinger["subject"], "@")) {
986 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
989 foreach ($webfinger["links"] as $link) {
990 if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
991 ($link["type"] == "text/html") AND ($link["href"] != "")) {
992 $data["url"] = $link["href"];
993 } elseif (($link["rel"] == "salmon") AND ($link["href"] != "")) {
994 $data["notify"] = $link["href"];
995 } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
996 $data["poll"] = $link["href"];
997 } elseif (($link["rel"] == "magic-public-key") AND ($link["href"] != "")) {
998 $pubkey = $link["href"];
1000 if (substr($pubkey, 0, 5) === 'data:') {
1001 if (strstr($pubkey, ',')) {
1002 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1004 $pubkey = substr($pubkey, 5);
1006 } elseif (normalise_link($pubkey) == 'http://') {
1007 $ret = z_fetch_url($pubkey);
1008 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1011 $pubkey = $ret['body'];
1014 $key = explode(".", $pubkey);
1016 if (sizeof($key) >= 3) {
1017 $m = base64url_decode($key[1]);
1018 $e = base64url_decode($key[2]);
1019 $data["pubkey"] = metopem($m, $e);
1024 if (isset($data["notify"]) AND isset($data["pubkey"]) AND
1025 isset($data["poll"]) AND isset($data["url"])) {
1026 $data["network"] = NETWORK_OSTATUS;
1030 // Fetch all additional data from the feed
1031 $ret = z_fetch_url($data["poll"]);
1032 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1035 $feed = $ret['body'];
1036 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1040 if ($feed_data["header"]["author-name"] != "") {
1041 $data["name"] = $feed_data["header"]["author-name"];
1043 if ($feed_data["header"]["author-nick"] != "") {
1044 $data["nick"] = $feed_data["header"]["author-nick"];
1046 if ($feed_data["header"]["author-avatar"] != "") {
1047 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1049 if ($feed_data["header"]["author-id"] != "") {
1050 $data["alias"] = $feed_data["header"]["author-id"];
1052 if ($feed_data["header"]["author-location"] != "") {
1053 $data["location"] = $feed_data["header"]["author-location"];
1055 if ($feed_data["header"]["author-about"] != "") {
1056 $data["about"] = $feed_data["header"]["author-about"];
1058 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1059 // So we take the value that we just fetched, although the other one worked as well
1060 if ($feed_data["header"]["author-link"] != "") {
1061 $data["url"] = $feed_data["header"]["author-link"];
1063 /// @todo Fetch location and "about" from the feed as well
1068 * @brief Fetch data from a pump.io profile page
1070 * @param string $profile Link to the profile page
1072 * @return array profile data
1074 private function pumpioProfileData($profile) {
1076 $doc = new \DOMDocument();
1077 if (!@$doc->loadHTMLFile($profile)) {
1081 $xpath = new \DomXPath($doc);
1085 // This is ugly - but pump.io doesn't seem to know a better way for it
1086 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1087 $pos = strpos($data["name"], chr(10));
1089 $data["name"] = trim(substr($data["name"], 0, $pos));
1092 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1094 foreach ($avatar->attributes as $attribute) {
1095 if ($attribute->name == "src") {
1096 $data["photo"] = trim($attribute->value);
1101 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
1102 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
1108 * @brief Check for pump.io contact
1110 * @param array $webfinger Webfinger data
1112 * @return array pump.io data
1114 private function pumpio($webfinger) {
1117 foreach ($webfinger["links"] as $link) {
1118 if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
1119 ($link["type"] == "text/html") AND ($link["href"] != "")) {
1120 $data["url"] = $link["href"];
1121 } elseif (($link["rel"] == "activity-inbox") AND ($link["href"] != "")) {
1122 $data["notify"] = $link["href"];
1123 } elseif (($link["rel"] == "activity-outbox") AND ($link["href"] != "")) {
1124 $data["poll"] = $link["href"];
1125 } elseif (($link["rel"] == "dialback") AND ($link["href"] != "")) {
1126 $data["dialback"] = $link["href"];
1129 if (isset($data["poll"]) AND isset($data["notify"]) AND
1130 isset($data["dialback"]) AND isset($data["url"])) {
1131 // by now we use these fields only for the network type detection
1132 // So we unset all data that isn't used at the moment
1133 unset($data["dialback"]);
1135 $data["network"] = NETWORK_PUMPIO;
1140 $profile_data = self::pumpioProfileData($data["url"]);
1142 if (!$profile_data) {
1146 $data = array_merge($data, $profile_data);
1152 * @brief Check page for feed link
1154 * @param string $url Page link
1156 * @return string feed link
1158 private function getFeedLink($url) {
1159 $doc = new \DOMDocument();
1161 if (!@$doc->loadHTMLFile($url)) {
1165 $xpath = new \DomXPath($doc);
1167 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1168 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1169 if (!is_object($feeds)) {
1173 if ($feeds->length == 0) {
1179 foreach ($feeds as $feed) {
1181 foreach ($feed->attributes as $attribute) {
1182 $attr[$attribute->name] = trim($attribute->value);
1185 if ($feed_url == "") {
1186 $feed_url = $attr["href"];
1194 * @brief Check for feed contact
1196 * @param string $url Profile link
1197 * @param boolean $probe Do a probe if the page contains a feed link
1199 * @return array feed data
1201 private function feed($url, $probe = true) {
1202 $ret = z_fetch_url($url);
1203 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1206 $feed = $ret['body'];
1207 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1214 $feed_url = self::getFeedLink($url);
1220 return self::feed($feed_url, false);
1223 if ($feed_data["header"]["author-name"] != "") {
1224 $data["name"] = $feed_data["header"]["author-name"];
1227 if ($feed_data["header"]["author-nick"] != "") {
1228 $data["nick"] = $feed_data["header"]["author-nick"];
1231 if ($feed_data["header"]["author-avatar"] != "") {
1232 $data["photo"] = $feed_data["header"]["author-avatar"];
1235 if ($feed_data["header"]["author-id"] != "") {
1236 $data["alias"] = $feed_data["header"]["author-id"];
1239 $data["url"] = $url;
1240 $data["poll"] = $url;
1242 if ($feed_data["header"]["author-link"] != "") {
1243 $data["baseurl"] = $feed_data["header"]["author-link"];
1245 $data["baseurl"] = $data["url"];
1248 $data["network"] = NETWORK_FEED;
1254 * @brief Check for mail contact
1256 * @param string $uri Profile link
1257 * @param integer $uid User ID
1259 * @return array mail data
1261 private function mail($uri, $uid) {
1263 if (!validate_email($uri)) {
1267 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1269 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1271 if (\dbm::is_result($x) && \dbm::is_result($r)) {
1272 $mailbox = construct_mailbox_name($r[0]);
1274 openssl_private_decrypt(hex2bin($r[0]['pass']), $password, $x[0]['prvkey']);
1275 $mbox = email_connect($mailbox, $r[0]['user'], $password);
1281 $msgs = email_poll($mbox, $uri);
1282 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1284 if (!count($msgs)) {
1290 $data["addr"] = $uri;
1291 $data["network"] = NETWORK_MAIL;
1292 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1293 $data["nick"] = $data["name"];
1294 $data["photo"] = avatar_img($uri);
1296 $phost = substr($uri, strpos($uri, '@') + 1);
1297 $data["url"] = 'http://'.$phost."/".$data["nick"];
1298 $data["notify"] = 'smtp '.random_string();
1299 $data["poll"] = 'email '.random_string();
1301 $x = email_msg_meta($mbox, $msgs[0]);
1302 if (stristr($x[0]->from, $uri)) {
1303 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1304 } elseif (stristr($x[0]->to, $uri)) {
1305 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1308 foreach ($adr as $feadr) {
1309 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1310 &&(strcasecmp($feadr->host, $phost) == 0)
1311 && (strlen($feadr->personal))) {
1313 $personal = imap_mime_header_decode($feadr->personal);
1315 foreach ($personal as $perspart) {
1316 if ($perspart->charset != "default") {
1317 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1319 $data["name"] .= $perspart->text;
1323 $data["name"] = notags($data["name"]);
1333 * @brief Mix two paths together to possibly fix missing parts
1335 * @param string $avatar Path to the avatar
1336 * @param string $base Another path that is hopefully complete
1338 * @return string fixed avatar path
1340 public static function fixAvatar($avatar, $base) {
1341 $base_parts = parse_url($base);
1343 // Remove all parts that could create a problem
1344 unset($base_parts['path']);
1345 unset($base_parts['query']);
1346 unset($base_parts['fragment']);
1348 $avatar_parts = parse_url($avatar);
1351 $parts = array_merge($base_parts, $avatar_parts);
1353 // And put them together again
1354 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1355 $host = isset($parts['host']) ? $parts['host'] : '';
1356 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1357 $path = isset($parts['path']) ? $parts['path'] : '';
1358 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1359 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1361 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1363 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);