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")
113 AND ($attributes["type"] == "application/xrd+xml")
115 $xrd_data["lrdd-xml"] = $attributes["template"];
116 } elseif (($attributes["rel"] == "lrdd")
117 AND ($attributes["type"] == "application/json")
119 $xrd_data["lrdd-json"] = $attributes["template"];
120 } elseif ($attributes["rel"] == "lrdd") {
121 $xrd_data["lrdd"] = $attributes["template"];
125 self::$baseurl = "http://".$host;
131 * @brief Perform Webfinger lookup and return DFRN data
133 * Given an email style address, perform webfinger lookup and
134 * return the resulting DFRN profile URL, or if no DFRN profile URL
135 * is located, returns an OStatus subscription template (prefixed
136 * with the string 'stat:' to identify it as on OStatus template).
137 * If this isn't an email style address just return $webbie.
138 * Return an empty string if email-style addresses but webfinger fails,
139 * or if the resultant personal XRD doesn't contain a supported
140 * subscription/friend-request attribute.
142 * amended 7/9/2011 to return an hcard which could save potentially loading
143 * a lengthy content page to scrape dfrn attributes
145 * @param string $webbie Address that should be probed
146 * @param string $hcard Link to the hcard - is returned by reference
148 * @return string profile link
151 public static function webfingerDfrn($webbie, &$hcard) {
155 $links = self::lrdd($webbie);
156 logger('webfingerDfrn: '.$webbie.':'.print_r($links, true), LOGGER_DATA);
158 foreach ($links as $link) {
159 if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
160 $profile_link = $link['@attributes']['href'];
162 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) AND ($profile_link == "")) {
163 $profile_link = 'stat:'.$link['@attributes']['template'];
165 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
166 $hcard = $link['@attributes']['href'];
170 return $profile_link;
174 * @brief Check an URI for LRDD data
176 * this is a replacement for the "lrdd" function in include/network.php.
177 * It isn't used in this class and has some redundancies in the code.
178 * When time comes we can check the existing calls for "lrdd" if we can rework them.
180 * @param string $uri Address that should be probed
182 * @return array uri data
184 public static function lrdd($uri) {
186 $lrdd = self::xrd($uri);
189 $parts = @parse_url($uri);
194 $host = $parts["host"];
195 if (isset($parts["port"])) {
196 $host .= ':'.$parts["port"];
199 $path_parts = explode("/", trim($parts["path"], "/"));
201 $nick = array_pop($path_parts);
204 $lrdd = self::xrd($host);
205 $host .= "/".array_shift($path_parts);
206 } while (!$lrdd AND (sizeof($path_parts) > 0));
213 foreach ($lrdd as $key => $link) {
218 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
222 $path = str_replace('{uri}', urlencode($uri), $link);
223 $webfinger = self::webfinger($path);
225 if (!$webfinger AND (strstr($uri, "@"))) {
226 $path = str_replace('{uri}', urlencode("acct:".$uri), $link);
227 $webfinger = self::webfinger($path);
230 // Special treatment for Mastodon
231 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
232 // But the webfinger for this format fails.
233 if (!$webfinger AND isset($nick)) {
234 // Mastodon uses a "@" as prefix for usernames in their url format
235 $nick = ltrim($nick, '@');
237 $addr = $nick."@".$host;
239 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
240 $webfinger = self::webfinger($path);
244 if (!is_array($webfinger["links"])) {
250 foreach ($webfinger["links"] as $link) {
251 $data[] = array("@attributes" => $link);
254 if (is_array($webfinger["aliases"])) {
255 foreach ($webfinger["aliases"] as $alias) {
256 $data[] = array("@attributes" =>
257 array("rel" => "alias",
266 * @brief Fetch information (protocol endpoints and user information) about a given uri
268 * @param string $uri Address that should be probed
269 * @param string $network Test for this specific network
270 * @param integer $uid User ID for the probe (only used for mails)
271 * @param boolean $cache Use cached values?
273 * @return array uri data
275 public static function uri($uri, $network = "", $uid = 0, $cache = true) {
278 $result = \Cache::get("probe_url:".$network.":".$uri);
279 if (!is_null($result)) {
288 $data = self::detect($uri, $network, $uid);
290 if (!isset($data["url"])) {
294 if ($data["photo"] != "") {
295 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
297 $data["photo"] = App::get_baseurl().'/images/person-175.jpg';
300 if (!isset($data["name"]) OR ($data["name"] == "")) {
301 if (isset($data["nick"])) {
302 $data["name"] = $data["nick"];
305 if ($data["name"] == "") {
306 $data["name"] = $data["url"];
310 if (!isset($data["nick"]) OR ($data["nick"] == "")) {
311 $data["nick"] = strtolower($data["name"]);
313 if (strpos($data['nick'], ' ')) {
314 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
318 if (self::$baseurl != "") {
319 $data["baseurl"] = self::$baseurl;
322 if (!isset($data["network"])) {
323 $data["network"] = NETWORK_PHANTOM;
326 $data = self::rearrangeData($data);
328 // Only store into the cache if the value seems to be valid
329 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
330 \Cache::set("probe_url:".$network.":".$uri, $data, CACHE_DAY);
332 /// @todo temporary fix - we need a real contact update function that updates only changing fields
333 /// The biggest problem is the avatar picture that could have a reduced image size.
334 /// It should only be updated if the existing picture isn't existing anymore.
335 if (($data['network'] != NETWORK_FEED)
336 AND ($mode == PROBE_NORMAL)
343 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `url` = '%s', `addr` = '%s',
344 `notify` = '%s', `poll` = '%s', `alias` = '%s', `success_update` = '%s'
345 WHERE `nurl` = '%s' AND NOT `self` AND `uid` = 0",
346 dbesc($data["name"]),
347 dbesc($data["nick"]),
349 dbesc($data["addr"]),
350 dbesc($data["notify"]),
351 dbesc($data["poll"]),
352 dbesc($data["alias"]),
353 dbesc(datetime_convert()),
354 dbesc(normalise_link($data['url']))
363 * @brief Fetch information (protocol endpoints and user information) about a given uri
365 * This function is only called by the "uri" function that adds caching and rearranging of data.
367 * @param string $uri Address that should be probed
368 * @param string $network Test for this specific network
369 * @param integer $uid User ID for the probe (only used for mails)
371 * @return array uri data
373 private function detect($uri, $network, $uid) {
374 $parts = parse_url($uri);
376 if (isset($parts["scheme"]) AND isset($parts["host"]) AND isset($parts["path"])) {
377 $host = $parts["host"];
378 if (isset($parts["port"])) {
379 $host .= ':'.$parts["port"];
382 if ($host == 'twitter.com') {
383 return array("network" => NETWORK_TWITTER);
385 $lrdd = self::xrd($host);
387 $path_parts = explode("/", trim($parts["path"], "/"));
389 while (!$lrdd AND (sizeof($path_parts) > 1)) {
390 $host .= "/".array_shift($path_parts);
391 $lrdd = self::xrd($host);
394 return self::feed($uri);
396 $nick = array_pop($path_parts);
398 // Mastodon uses a "@" as prefix for usernames in their url format
399 $nick = ltrim($nick, '@');
401 $addr = $nick."@".$host;
403 } elseif (strstr($uri, '@')) {
404 // If the URI starts with "mailto:" then jump directly to the mail detection
405 if (strpos($url, 'mailto:') !== false) {
406 $uri = str_replace('mailto:', '', $url);
407 return self::mail($uri, $uid);
410 if ($network == NETWORK_MAIL) {
411 return self::mail($uri, $uid);
413 // Remove "acct:" from the URI
414 $uri = str_replace('acct:', '', $uri);
416 $host = substr($uri, strpos($uri, '@') + 1);
417 $nick = substr($uri, 0, strpos($uri, '@'));
419 if (strpos($uri, '@twitter.com')) {
420 return array("network" => NETWORK_TWITTER);
422 $lrdd = self::xrd($host);
425 return self::mail($uri, $uid);
435 /// @todo Do we need the prefix "acct:" or "acct://"?
437 foreach ($lrdd as $key => $link) {
441 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
444 // At first try it with the given uri
445 $path = str_replace('{uri}', urlencode($uri), $link);
446 $webfinger = self::webfinger($path);
448 // We cannot be sure that the detected address was correct, so we don't use the values
449 if ($webfinger AND ($uri != $addr)) {
454 // Try webfinger with the address (user@domain.tld)
456 $path = str_replace('{uri}', urlencode($addr), $link);
457 $webfinger = self::webfinger($path);
460 // Mastodon needs to have it with "acct:"
462 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
463 $webfinger = self::webfinger($path);
467 return self::feed($uri);
472 logger("Probing ".$uri, LOGGER_DEBUG);
474 if (in_array($network, array("", NETWORK_DFRN))) {
475 $result = self::dfrn($webfinger);
477 if ((!$result AND ($network == "")) OR ($network == NETWORK_DIASPORA)) {
478 $result = self::diaspora($webfinger);
480 if ((!$result AND ($network == "")) OR ($network == NETWORK_OSTATUS)) {
481 $result = self::ostatus($webfinger);
483 if ((!$result AND ($network == "")) OR ($network == NETWORK_PUMPIO)) {
484 $result = self::pumpio($webfinger);
486 if ((!$result AND ($network == "")) OR ($network == NETWORK_FEED)) {
487 $result = self::feed($uri);
489 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
490 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
491 if ((!isset($result["nick"]) OR ($result["nick"] == "") OR (strstr($result["nick"], " "))) AND ($nick != "")) {
492 $result["nick"] = $nick;
495 if ((!isset($result["addr"]) OR ($result["addr"] == "")) AND ($addr != "")) {
496 $result["addr"] = $addr;
500 logger($uri." is ".$result["network"], LOGGER_DEBUG);
502 if (!isset($result["baseurl"]) OR ($result["baseurl"] == "")) {
503 $pos = strpos($result["url"], $host);
505 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
513 * @brief Perform a webfinger request.
515 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
517 * @param string $url Address that should be probed
519 * @return array webfinger data
521 private function webfinger($url) {
523 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
526 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
527 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
530 $data = $ret['body'];
532 $xrd = parse_xml_string($data, false);
534 if (!is_object($xrd)) {
535 // If it is not XML, maybe it is JSON
536 $webfinger = json_decode($data, true);
538 if (!isset($webfinger["links"])) {
545 $xrd_arr = \xml::element_to_array($xrd);
546 if (!isset($xrd_arr["xrd"]["link"])) {
550 $webfinger = array();
552 if (isset($xrd_arr["xrd"]["subject"])) {
553 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
556 if (isset($xrd_arr["xrd"]["alias"])) {
557 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
560 $webfinger["links"] = array();
562 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
563 if (isset($data["@attributes"])) {
564 $attributes = $data["@attributes"];
565 } elseif ($value == "@attributes") {
571 $webfinger["links"][] = $attributes;
577 * @brief Poll the Friendica specific noscrape page.
579 * "noscrape" is a faster alternative to fetch the data from the hcard.
580 * This functionality was originally created for the directory.
582 * @param string $noscrape Link to the noscrape page
583 * @param array $data The already fetched data
585 * @return array noscrape data
587 private function pollNoscrape($noscrape, $data) {
588 $ret = z_fetch_url($noscrape);
589 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
592 $content = $ret['body'];
597 $json = json_decode($content, true);
598 if (!is_array($json)) {
602 if (isset($json["fn"])) {
603 $data["name"] = $json["fn"];
606 if (isset($json["addr"])) {
607 $data["addr"] = $json["addr"];
610 if (isset($json["nick"])) {
611 $data["nick"] = $json["nick"];
614 if (isset($json["comm"])) {
615 $data["community"] = $json["comm"];
618 if (isset($json["tags"])) {
619 $keywords = implode(" ", $json["tags"]);
620 if ($keywords != "") {
621 $data["keywords"] = $keywords;
625 $location = formatted_location($json);
627 $data["location"] = $location;
630 if (isset($json["about"])) {
631 $data["about"] = $json["about"];
634 if (isset($json["key"])) {
635 $data["pubkey"] = $json["key"];
638 if (isset($json["photo"])) {
639 $data["photo"] = $json["photo"];
642 if (isset($json["dfrn-request"])) {
643 $data["request"] = $json["dfrn-request"];
646 if (isset($json["dfrn-confirm"])) {
647 $data["confirm"] = $json["dfrn-confirm"];
650 if (isset($json["dfrn-notify"])) {
651 $data["notify"] = $json["dfrn-notify"];
654 if (isset($json["dfrn-poll"])) {
655 $data["poll"] = $json["dfrn-poll"];
662 * @brief Check for valid DFRN data
664 * @param array $data DFRN data
666 * @return int Number of errors
668 public static function validDfrn($data) {
670 if (!isset($data['key'])) {
673 if (!isset($data['dfrn-request'])) {
676 if (!isset($data['dfrn-confirm'])) {
679 if (!isset($data['dfrn-notify'])) {
682 if (!isset($data['dfrn-poll'])) {
689 * @brief Fetch data from a DFRN profile page and via "noscrape"
691 * @param string $profile Link to the profile page
693 * @return array profile data
695 public static function profile($profile) {
699 logger("Check profile ".$profile, LOGGER_DEBUG);
701 // Fetch data via noscrape - this is faster
702 $noscrape = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile);
703 $data = self::pollNoscrape($noscrape, $data);
705 if (!isset($data["notify"])
706 OR !isset($data["confirm"])
707 OR !isset($data["request"])
708 OR !isset($data["poll"])
709 OR !isset($data["poco"])
710 OR !isset($data["name"])
711 OR !isset($data["photo"])
713 $data = self::pollHcard($profile, $data, true);
716 $prof_data = array();
717 $prof_data["addr"] = $data["addr"];
718 $prof_data["nick"] = $data["nick"];
719 $prof_data["dfrn-request"] = $data["request"];
720 $prof_data["dfrn-confirm"] = $data["confirm"];
721 $prof_data["dfrn-notify"] = $data["notify"];
722 $prof_data["dfrn-poll"] = $data["poll"];
723 $prof_data["dfrn-poco"] = $data["poco"];
724 $prof_data["photo"] = $data["photo"];
725 $prof_data["fn"] = $data["name"];
726 $prof_data["key"] = $data["pubkey"];
728 logger("Result for profile ".$profile.": ".print_r($prof_data, true), LOGGER_DEBUG);
734 * @brief Check for DFRN contact
736 * @param array $webfinger Webfinger data
738 * @return array DFRN data
740 private function dfrn($webfinger) {
744 foreach ($webfinger["links"] as $link) {
745 if (($link["rel"] == NAMESPACE_DFRN) AND ($link["href"] != "")) {
746 $data["network"] = NETWORK_DFRN;
747 } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
748 $data["poll"] = $link["href"];
749 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND ($link["type"] == "text/html") AND ($link["href"] != "")) {
750 $data["url"] = $link["href"];
751 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != "")) {
752 $hcard = $link["href"];
753 } elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != "")) {
754 $data["poco"] = $link["href"];
755 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") AND ($link["href"] != "")) {
756 $data["photo"] = $link["href"];
757 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != "")) {
758 $data["baseurl"] = trim($link["href"], '/');
759 } elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != "")) {
760 $data["guid"] = $link["href"];
761 } elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
762 $data["pubkey"] = base64_decode($link["href"]);
764 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
765 if (strstr($data["pubkey"], 'RSA ')) {
766 $data["pubkey"] = rsatopem($data["pubkey"]);
771 if (!isset($data["network"]) OR ($hcard == "")) {
775 // Fetch data via noscrape - this is faster
776 $noscrape = str_replace("/hcard/", "/noscrape/", $hcard);
777 $data = self::pollNoscrape($noscrape, $data);
779 if (isset($data["notify"])
780 AND isset($data["confirm"])
781 AND isset($data["request"])
782 AND isset($data["poll"])
783 AND isset($data["name"])
784 AND isset($data["photo"])
789 $data = self::pollHcard($hcard, $data, true);
795 * @brief Poll the hcard page (Diaspora and Friendica specific)
797 * @param string $hcard Link to the hcard page
798 * @param array $data The already fetched data
799 * @param boolean $dfrn Poll DFRN specific data
801 * @return array hcard data
803 private function pollHcard($hcard, $data, $dfrn = false) {
804 $ret = z_fetch_url($hcard);
805 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
808 $content = $ret['body'];
813 $doc = new \DOMDocument();
814 if (!@$doc->loadHTML($content)) {
818 $xpath = new \DomXPath($doc);
820 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
821 if (!is_object($vcards)) {
825 if ($vcards->length > 0) {
826 $vcard = $vcards->item(0);
828 // We have to discard the guid from the hcard in favour of the guid from lrdd
829 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
830 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
831 if (($search->length > 0) AND ($data["guid"] == "")) {
832 $data["guid"] = $search->item(0)->nodeValue;
835 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
836 if ($search->length > 0) {
837 $data["nick"] = $search->item(0)->nodeValue;
840 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
841 if ($search->length > 0) {
842 $data["name"] = $search->item(0)->nodeValue;
845 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
846 if ($search->length > 0) {
847 $data["searchable"] = $search->item(0)->nodeValue;
850 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
851 if ($search->length > 0) {
852 $data["pubkey"] = $search->item(0)->nodeValue;
853 if (strstr($data["pubkey"], 'RSA ')) {
854 $data["pubkey"] = rsatopem($data["pubkey"]);
858 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
859 if ($search->length > 0) {
860 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
865 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
866 foreach ($photos as $photo) {
868 foreach ($photo->attributes as $attribute) {
869 $attr[$attribute->name] = trim($attribute->value);
872 if (isset($attr["src"]) AND isset($attr["width"])) {
873 $avatar[$attr["width"]] = $attr["src"];
876 // We don't have a width. So we just take everything that we got.
877 // This is a Hubzilla workaround which doesn't send a width.
878 if ((sizeof($avatar) == 0) AND isset($attr["src"])) {
879 $avatar[] = $attr["src"];
883 if (sizeof($avatar)) {
885 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
889 // Poll DFRN specific data
890 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
891 if ($search->length > 0) {
892 foreach ($search as $link) {
893 //$data["request"] = $search->item(0)->nodeValue;
895 foreach ($link->attributes as $attribute) {
896 $attr[$attribute->name] = trim($attribute->value);
899 $data[substr($attr["rel"], 5)] = $attr["href"];
903 // Older Friendica versions had used the "uid" field differently than newer versions
904 if ($data["nick"] == $data["guid"]) {
905 unset($data["guid"]);
914 * @brief Check for Diaspora contact
916 * @param array $webfinger Webfinger data
918 * @return array Diaspora data
920 private function diaspora($webfinger) {
924 foreach ($webfinger["links"] as $link) {
925 if (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != "")) {
926 $hcard = $link["href"];
927 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != "")) {
928 $data["baseurl"] = trim($link["href"], '/');
929 } elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != "")) {
930 $data["guid"] = $link["href"];
931 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND ($link["type"] == "text/html") AND ($link["href"] != "")) {
932 $data["url"] = $link["href"];
933 } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
934 $data["poll"] = $link["href"];
935 } elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != "")) {
936 $data["poco"] = $link["href"];
937 } elseif (($link["rel"] == "salmon") AND ($link["href"] != "")) {
938 $data["notify"] = $link["href"];
939 } elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
940 $data["pubkey"] = base64_decode($link["href"]);
942 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
943 if (strstr($data["pubkey"], 'RSA ')) {
944 $data["pubkey"] = rsatopem($data["pubkey"]);
949 if (!isset($data["url"]) OR ($hcard == "")) {
953 if (is_array($webfinger["aliases"])) {
954 foreach ($webfinger["aliases"] as $alias) {
955 if (normalise_link($alias) != normalise_link($data["url"]) AND ! strstr($alias, "@")) {
956 $data["alias"] = $alias;
961 // Fetch further information from the hcard
962 $data = self::pollHcard($hcard, $data);
968 if (isset($data["url"])
969 AND isset($data["guid"])
970 AND isset($data["baseurl"])
971 AND isset($data["pubkey"])
974 $data["network"] = NETWORK_DIASPORA;
976 // The Diaspora handle must always be lowercase
977 $data["addr"] = strtolower($data["addr"]);
979 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
980 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
981 $data["batch"] = $data["baseurl"] . "/receive/public";
990 * @brief Check for OStatus contact
992 * @param array $webfinger Webfinger data
994 * @return array OStatus data
996 private function ostatus($webfinger) {
998 if (is_array($webfinger["aliases"])) {
999 foreach ($webfinger["aliases"] as $alias) {
1000 if (strstr($alias, "@")) {
1001 $data["addr"] = str_replace('acct:', '', $alias);
1006 if (is_string($webfinger["subject"]) AND strstr($webfinger["subject"], "@")) {
1007 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1010 foreach ($webfinger["links"] as $link) {
1011 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1012 AND ($link["type"] == "text/html")
1013 AND ($link["href"] != "")
1015 $data["url"] = $link["href"];
1016 } elseif (($link["rel"] == "salmon") AND ($link["href"] != "")) {
1017 $data["notify"] = $link["href"];
1018 } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
1019 $data["poll"] = $link["href"];
1020 } elseif (($link["rel"] == "magic-public-key") AND ($link["href"] != "")) {
1021 $pubkey = $link["href"];
1023 if (substr($pubkey, 0, 5) === 'data:') {
1024 if (strstr($pubkey, ',')) {
1025 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1027 $pubkey = substr($pubkey, 5);
1029 } elseif (normalise_link($pubkey) == 'http://') {
1030 $ret = z_fetch_url($pubkey);
1031 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1034 $pubkey = $ret['body'];
1037 $key = explode(".", $pubkey);
1039 if (sizeof($key) >= 3) {
1040 $m = base64url_decode($key[1]);
1041 $e = base64url_decode($key[2]);
1042 $data["pubkey"] = metopem($m, $e);
1047 if (isset($data["notify"]) AND isset($data["pubkey"])
1048 AND isset($data["poll"])
1049 AND isset($data["url"])
1051 $data["network"] = NETWORK_OSTATUS;
1055 // Fetch all additional data from the feed
1056 $ret = z_fetch_url($data["poll"]);
1057 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1060 $feed = $ret['body'];
1061 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1065 if ($feed_data["header"]["author-name"] != "") {
1066 $data["name"] = $feed_data["header"]["author-name"];
1068 if ($feed_data["header"]["author-nick"] != "") {
1069 $data["nick"] = $feed_data["header"]["author-nick"];
1071 if ($feed_data["header"]["author-avatar"] != "") {
1072 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1074 if ($feed_data["header"]["author-id"] != "") {
1075 $data["alias"] = $feed_data["header"]["author-id"];
1077 if ($feed_data["header"]["author-location"] != "") {
1078 $data["location"] = $feed_data["header"]["author-location"];
1080 if ($feed_data["header"]["author-about"] != "") {
1081 $data["about"] = $feed_data["header"]["author-about"];
1083 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1084 // So we take the value that we just fetched, although the other one worked as well
1085 if ($feed_data["header"]["author-link"] != "") {
1086 $data["url"] = $feed_data["header"]["author-link"];
1088 /// @todo Fetch location and "about" from the feed as well
1093 * @brief Fetch data from a pump.io profile page
1095 * @param string $profile Link to the profile page
1097 * @return array profile data
1099 private function pumpioProfileData($profile) {
1101 $doc = new \DOMDocument();
1102 if (!@$doc->loadHTMLFile($profile)) {
1106 $xpath = new \DomXPath($doc);
1110 // This is ugly - but pump.io doesn't seem to know a better way for it
1111 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1112 $pos = strpos($data["name"], chr(10));
1114 $data["name"] = trim(substr($data["name"], 0, $pos));
1117 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1119 foreach ($avatar->attributes as $attribute) {
1120 if ($attribute->name == "src") {
1121 $data["photo"] = trim($attribute->value);
1126 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
1127 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
1133 * @brief Check for pump.io contact
1135 * @param array $webfinger Webfinger data
1137 * @return array pump.io data
1139 private function pumpio($webfinger) {
1142 foreach ($webfinger["links"] as $link) {
1143 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1144 AND ($link["type"] == "text/html")
1145 AND ($link["href"] != "")
1147 $data["url"] = $link["href"];
1148 } elseif (($link["rel"] == "activity-inbox") AND ($link["href"] != "")) {
1149 $data["notify"] = $link["href"];
1150 } elseif (($link["rel"] == "activity-outbox") AND ($link["href"] != "")) {
1151 $data["poll"] = $link["href"];
1152 } elseif (($link["rel"] == "dialback") AND ($link["href"] != "")) {
1153 $data["dialback"] = $link["href"];
1156 if (isset($data["poll"]) AND isset($data["notify"])
1157 AND isset($data["dialback"])
1158 AND isset($data["url"])
1160 // by now we use these fields only for the network type detection
1161 // So we unset all data that isn't used at the moment
1162 unset($data["dialback"]);
1164 $data["network"] = NETWORK_PUMPIO;
1169 $profile_data = self::pumpioProfileData($data["url"]);
1171 if (!$profile_data) {
1175 $data = array_merge($data, $profile_data);
1181 * @brief Check page for feed link
1183 * @param string $url Page link
1185 * @return string feed link
1187 private function getFeedLink($url) {
1188 $doc = new \DOMDocument();
1190 if (!@$doc->loadHTMLFile($url)) {
1194 $xpath = new \DomXPath($doc);
1196 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1197 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1198 if (!is_object($feeds)) {
1202 if ($feeds->length == 0) {
1208 foreach ($feeds as $feed) {
1210 foreach ($feed->attributes as $attribute) {
1211 $attr[$attribute->name] = trim($attribute->value);
1214 if ($feed_url == "") {
1215 $feed_url = $attr["href"];
1223 * @brief Check for feed contact
1225 * @param string $url Profile link
1226 * @param boolean $probe Do a probe if the page contains a feed link
1228 * @return array feed data
1230 private function feed($url, $probe = true) {
1231 $ret = z_fetch_url($url);
1232 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1235 $feed = $ret['body'];
1236 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1243 $feed_url = self::getFeedLink($url);
1249 return self::feed($feed_url, false);
1252 if ($feed_data["header"]["author-name"] != "") {
1253 $data["name"] = $feed_data["header"]["author-name"];
1256 if ($feed_data["header"]["author-nick"] != "") {
1257 $data["nick"] = $feed_data["header"]["author-nick"];
1260 if ($feed_data["header"]["author-avatar"] != "") {
1261 $data["photo"] = $feed_data["header"]["author-avatar"];
1264 if ($feed_data["header"]["author-id"] != "") {
1265 $data["alias"] = $feed_data["header"]["author-id"];
1268 $data["url"] = $url;
1269 $data["poll"] = $url;
1271 if ($feed_data["header"]["author-link"] != "") {
1272 $data["baseurl"] = $feed_data["header"]["author-link"];
1274 $data["baseurl"] = $data["url"];
1277 $data["network"] = NETWORK_FEED;
1283 * @brief Check for mail contact
1285 * @param string $uri Profile link
1286 * @param integer $uid User ID
1288 * @return array mail data
1290 private function mail($uri, $uid) {
1292 if (!validate_email($uri)) {
1296 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1298 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1300 if (\dbm::is_result($x) && \dbm::is_result($r)) {
1301 $mailbox = construct_mailbox_name($r[0]);
1303 openssl_private_decrypt(hex2bin($r[0]['pass']), $password, $x[0]['prvkey']);
1304 $mbox = email_connect($mailbox, $r[0]['user'], $password);
1310 $msgs = email_poll($mbox, $uri);
1311 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1313 if (!count($msgs)) {
1319 $data["addr"] = $uri;
1320 $data["network"] = NETWORK_MAIL;
1321 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1322 $data["nick"] = $data["name"];
1323 $data["photo"] = avatar_img($uri);
1325 $phost = substr($uri, strpos($uri, '@') + 1);
1326 $data["url"] = 'http://'.$phost."/".$data["nick"];
1327 $data["notify"] = 'smtp '.random_string();
1328 $data["poll"] = 'email '.random_string();
1330 $x = email_msg_meta($mbox, $msgs[0]);
1331 if (stristr($x[0]->from, $uri)) {
1332 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1333 } elseif (stristr($x[0]->to, $uri)) {
1334 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1337 foreach ($adr as $feadr) {
1338 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1339 &&(strcasecmp($feadr->host, $phost) == 0)
1340 && (strlen($feadr->personal))
1342 $personal = imap_mime_header_decode($feadr->personal);
1344 foreach ($personal as $perspart) {
1345 if ($perspart->charset != "default") {
1346 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1348 $data["name"] .= $perspart->text;
1352 $data["name"] = notags($data["name"]);
1362 * @brief Mix two paths together to possibly fix missing parts
1364 * @param string $avatar Path to the avatar
1365 * @param string $base Another path that is hopefully complete
1367 * @return string fixed avatar path
1369 public static function fixAvatar($avatar, $base) {
1370 $base_parts = parse_url($base);
1372 // Remove all parts that could create a problem
1373 unset($base_parts['path']);
1374 unset($base_parts['query']);
1375 unset($base_parts['fragment']);
1377 $avatar_parts = parse_url($avatar);
1380 $parts = array_merge($base_parts, $avatar_parts);
1382 // And put them together again
1383 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1384 $host = isset($parts['host']) ? $parts['host'] : '';
1385 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1386 $path = isset($parts['path']) ? $parts['path'] : '';
1387 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1388 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1390 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1392 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);