3 namespace Friendica\Network;
6 * @file src/Network/Probe.php
7 * @brief Functions for probing URL
12 use Friendica\Core\Config;
21 require_once 'include/feed.php';
22 require_once 'include/email.php';
23 require_once 'include/network.php';
26 * @brief This class contain functions for probing URL
31 private static $baseurl;
34 * @brief Rearrange the array so that it always has the same order
36 * @param array $data Unordered data
38 * @return array Ordered data
40 private function rearrangeData($data) {
41 $fields = array("name", "nick", "guid", "url", "addr", "alias",
42 "photo", "community", "keywords", "location", "about",
43 "batch", "notify", "poll", "request", "confirm", "poco",
44 "priority", "network", "pubkey", "baseurl");
47 foreach ($fields as $field) {
48 if (isset($data[$field])) {
49 $newdata[$field] = $data[$field];
51 $newdata[$field] = "";
55 // We don't use the "priority" field anymore and replace it with a dummy.
56 $newdata["priority"] = 0;
62 * @brief Probes for XRD data
64 * @param string $host The host part of an url
67 * 'lrdd' => Link to LRDD endpoint
68 * 'lrdd-xml' => Link to LRDD endpoint in XML format
69 * 'lrdd-json' => Link to LRDD endpoint in JSON format
71 private function xrd($host) {
73 // Reset the static variable
76 $ssl_url = "https://".$host."/.well-known/host-meta";
77 $url = "http://".$host."/.well-known/host-meta";
79 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
82 logger("Probing for ".$host, LOGGER_DEBUG);
84 $ret = z_fetch_url($ssl_url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
85 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
90 $xrd = parse_xml_string($xml, false);
92 if (!is_object($xrd)) {
93 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
94 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
98 $xrd = parse_xml_string($xml, false);
100 if (!is_object($xrd)) {
104 $links = xml::element_to_array($xrd);
105 if (!isset($links["xrd"]["link"])) {
106 logger("No xrd data found for ".$host, LOGGER_DEBUG);
112 foreach ($links["xrd"]["link"] as $value => $link) {
113 if (isset($link["@attributes"])) {
114 $attributes = $link["@attributes"];
115 } elseif ($value == "@attributes") {
121 if (($attributes["rel"] == "lrdd")
122 AND ($attributes["type"] == "application/xrd+xml")
124 $xrd_data["lrdd-xml"] = $attributes["template"];
125 } elseif (($attributes["rel"] == "lrdd")
126 AND ($attributes["type"] == "application/json")
128 $xrd_data["lrdd-json"] = $attributes["template"];
129 } elseif ($attributes["rel"] == "lrdd") {
130 $xrd_data["lrdd"] = $attributes["template"];
134 self::$baseurl = "http://".$host;
140 * @brief Perform Webfinger lookup and return DFRN data
142 * Given an email style address, perform webfinger lookup and
143 * return the resulting DFRN profile URL, or if no DFRN profile URL
144 * is located, returns an OStatus subscription template (prefixed
145 * with the string 'stat:' to identify it as on OStatus template).
146 * If this isn't an email style address just return $webbie.
147 * Return an empty string if email-style addresses but webfinger fails,
148 * or if the resultant personal XRD doesn't contain a supported
149 * subscription/friend-request attribute.
151 * amended 7/9/2011 to return an hcard which could save potentially loading
152 * a lengthy content page to scrape dfrn attributes
154 * @param string $webbie Address that should be probed
155 * @param string $hcard_url Link to the hcard - is returned by reference
157 * @return string profile link
160 public static function webfingerDfrn($webbie, &$hcard_url) {
164 $links = self::lrdd($webbie);
165 logger('webfingerDfrn: '.$webbie.':'.print_r($links, true), LOGGER_DATA);
167 foreach ($links as $link) {
168 if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
169 $profile_link = $link['@attributes']['href'];
171 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) AND ($profile_link == "")) {
172 $profile_link = 'stat:'.$link['@attributes']['template'];
174 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
175 $hcard_url = $link['@attributes']['href'];
179 return $profile_link;
183 * @brief Check an URI for LRDD data
185 * this is a replacement for the "lrdd" function in include/network.php.
186 * It isn't used in this class and has some redundancies in the code.
187 * When time comes we can check the existing calls for "lrdd" if we can rework them.
189 * @param string $uri Address that should be probed
191 * @return array uri data
193 public static function lrdd($uri) {
195 $lrdd = self::xrd($uri);
199 $parts = @parse_url($uri);
204 $host = $parts["host"];
205 if (isset($parts["port"])) {
206 $host .= ':'.$parts["port"];
209 $path_parts = explode("/", trim($parts["path"], "/"));
211 $nick = array_pop($path_parts);
214 $lrdd = self::xrd($host);
215 $host .= "/".array_shift($path_parts);
216 } while (!$lrdd AND (sizeof($path_parts) > 0));
220 logger("No lrdd data found for ".$uri, LOGGER_DEBUG);
224 foreach ($lrdd as $key => $link) {
229 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
233 $path = str_replace('{uri}', urlencode($uri), $link);
234 $webfinger = self::webfinger($path);
236 if (!$webfinger AND (strstr($uri, "@"))) {
237 $path = str_replace('{uri}', urlencode("acct:".$uri), $link);
238 $webfinger = self::webfinger($path);
241 // Special treatment for Mastodon
242 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
243 // But the webfinger for this format fails.
244 if (!$webfinger AND isset($nick)) {
245 // Mastodon uses a "@" as prefix for usernames in their url format
246 $nick = ltrim($nick, '@');
248 $addr = $nick."@".$host;
250 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
251 $webfinger = self::webfinger($path);
255 if (!is_array($webfinger["links"])) {
256 logger("No webfinger links found for ".$uri, LOGGER_DEBUG);
262 foreach ($webfinger["links"] as $link) {
263 $data[] = array("@attributes" => $link);
266 if (is_array($webfinger["aliases"])) {
267 foreach ($webfinger["aliases"] as $alias) {
268 $data[] = array("@attributes" =>
269 array("rel" => "alias",
278 * @brief Fetch information (protocol endpoints and user information) about a given uri
280 * @param string $uri Address that should be probed
281 * @param string $network Test for this specific network
282 * @param integer $uid User ID for the probe (only used for mails)
283 * @param boolean $cache Use cached values?
285 * @return array uri data
287 public static function uri($uri, $network = "", $uid = 0, $cache = true) {
290 $result = Cache::get("probe_url:".$network.":".$uri);
291 if (!is_null($result)) {
300 $data = self::detect($uri, $network, $uid);
302 if (!isset($data["url"])) {
306 if ($data["photo"] != "") {
307 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
309 $data["photo"] = App::get_baseurl().'/images/person-175.jpg';
312 if (!isset($data["name"]) OR ($data["name"] == "")) {
313 if (isset($data["nick"])) {
314 $data["name"] = $data["nick"];
317 if ($data["name"] == "") {
318 $data["name"] = $data["url"];
322 if (!isset($data["nick"]) OR ($data["nick"] == "")) {
323 $data["nick"] = strtolower($data["name"]);
325 if (strpos($data['nick'], ' ')) {
326 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
330 if (self::$baseurl != "") {
331 $data["baseurl"] = self::$baseurl;
334 if (!isset($data["network"])) {
335 $data["network"] = NETWORK_PHANTOM;
338 $data = self::rearrangeData($data);
340 // Only store into the cache if the value seems to be valid
341 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
342 Cache::set("probe_url:".$network.":".$uri, $data, CACHE_DAY);
344 /// @todo temporary fix - we need a real contact update function that updates only changing fields
345 /// The biggest problem is the avatar picture that could have a reduced image size.
346 /// It should only be updated if the existing picture isn't existing anymore.
347 /// We only update the contact when it is no probing for a specific network.
348 if (($data['network'] != NETWORK_FEED)
356 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `url` = '%s', `addr` = '%s',
357 `notify` = '%s', `poll` = '%s', `alias` = '%s', `success_update` = '%s'
358 WHERE `nurl` = '%s' AND NOT `self` AND `uid` = 0",
359 dbesc($data["name"]),
360 dbesc($data["nick"]),
362 dbesc($data["addr"]),
363 dbesc($data["notify"]),
364 dbesc($data["poll"]),
365 dbesc($data["alias"]),
366 dbesc(datetime_convert()),
367 dbesc(normalise_link($data['url']))
376 * @brief Fetch information (protocol endpoints and user information) about a given uri
378 * This function is only called by the "uri" function that adds caching and rearranging of data.
380 * @param string $uri Address that should be probed
381 * @param string $network Test for this specific network
382 * @param integer $uid User ID for the probe (only used for mails)
384 * @return array uri data
386 private function detect($uri, $network, $uid) {
387 $parts = parse_url($uri);
389 if (isset($parts["scheme"]) AND isset($parts["host"]) AND isset($parts["path"])) {
390 $host = $parts["host"];
391 if (isset($parts["port"])) {
392 $host .= ':'.$parts["port"];
395 if ($host == 'twitter.com') {
396 return array("network" => NETWORK_TWITTER);
398 $lrdd = self::xrd($host);
400 $path_parts = explode("/", trim($parts["path"], "/"));
402 while (!$lrdd AND (sizeof($path_parts) > 1)) {
403 $host .= "/".array_shift($path_parts);
404 $lrdd = self::xrd($host);
407 return self::feed($uri);
409 $nick = array_pop($path_parts);
411 // Mastodon uses a "@" as prefix for usernames in their url format
412 $nick = ltrim($nick, '@');
414 $addr = $nick."@".$host;
416 } elseif (strstr($uri, '@')) {
417 // If the URI starts with "mailto:" then jump directly to the mail detection
418 if (strpos($uri, 'mailto:') !== false) {
419 $uri = str_replace('mailto:', '', $uri);
420 return self::mail($uri, $uid);
423 if ($network == NETWORK_MAIL) {
424 return self::mail($uri, $uid);
426 // Remove "acct:" from the URI
427 $uri = str_replace('acct:', '', $uri);
429 $host = substr($uri, strpos($uri, '@') + 1);
430 $nick = substr($uri, 0, strpos($uri, '@'));
432 if (strpos($uri, '@twitter.com')) {
433 return array("network" => NETWORK_TWITTER);
435 $lrdd = self::xrd($host);
438 return self::mail($uri, $uid);
443 logger("Uri ".$uri." was not detectable", LOGGER_DEBUG);
449 /// @todo Do we need the prefix "acct:" or "acct://"?
451 foreach ($lrdd as $key => $link) {
455 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
458 // At first try it with the given uri
459 $path = str_replace('{uri}', urlencode($uri), $link);
460 $webfinger = self::webfinger($path);
462 // We cannot be sure that the detected address was correct, so we don't use the values
463 if ($webfinger AND ($uri != $addr)) {
468 // Try webfinger with the address (user@domain.tld)
470 $path = str_replace('{uri}', urlencode($addr), $link);
471 $webfinger = self::webfinger($path);
474 // Mastodon needs to have it with "acct:"
476 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
477 $webfinger = self::webfinger($path);
481 return self::feed($uri);
486 logger("Probing ".$uri, LOGGER_DEBUG);
488 if (in_array($network, array("", NETWORK_DFRN))) {
489 $result = self::dfrn($webfinger);
491 if ((!$result AND ($network == "")) OR ($network == NETWORK_DIASPORA)) {
492 $result = self::diaspora($webfinger);
494 if ((!$result AND ($network == "")) OR ($network == NETWORK_OSTATUS)) {
495 $result = self::ostatus($webfinger);
497 if ((!$result AND ($network == "")) OR ($network == NETWORK_PUMPIO)) {
498 $result = self::pumpio($webfinger);
500 if ((!$result AND ($network == "")) OR ($network == NETWORK_FEED)) {
501 $result = self::feed($uri);
503 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
504 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
505 if ((!isset($result["nick"]) OR ($result["nick"] == "") OR (strstr($result["nick"], " "))) AND ($nick != "")) {
506 $result["nick"] = $nick;
509 if ((!isset($result["addr"]) OR ($result["addr"] == "")) AND ($addr != "")) {
510 $result["addr"] = $addr;
514 logger($uri." is ".$result["network"], LOGGER_DEBUG);
516 if (!isset($result["baseurl"]) OR ($result["baseurl"] == "")) {
517 $pos = strpos($result["url"], $host);
519 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
527 * @brief Perform a webfinger request.
529 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
531 * @param string $url Address that should be probed
533 * @return array webfinger data
535 private function webfinger($url) {
537 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
540 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
541 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
544 $data = $ret['body'];
546 $xrd = parse_xml_string($data, false);
548 if (!is_object($xrd)) {
549 // If it is not XML, maybe it is JSON
550 $webfinger = json_decode($data, true);
552 if (!isset($webfinger["links"])) {
553 logger("No json webfinger links for ".$url, LOGGER_DEBUG);
560 $xrd_arr = xml::element_to_array($xrd);
561 if (!isset($xrd_arr["xrd"]["link"])) {
562 logger("No XML webfinger links for ".$url, LOGGER_DEBUG);
566 $webfinger = array();
568 if (isset($xrd_arr["xrd"]["subject"])) {
569 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
572 if (isset($xrd_arr["xrd"]["alias"])) {
573 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
576 $webfinger["links"] = array();
578 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
579 if (isset($data["@attributes"])) {
580 $attributes = $data["@attributes"];
581 } elseif ($value == "@attributes") {
587 $webfinger["links"][] = $attributes;
593 * @brief Poll the Friendica specific noscrape page.
595 * "noscrape" is a faster alternative to fetch the data from the hcard.
596 * This functionality was originally created for the directory.
598 * @param string $noscrape_url Link to the noscrape page
599 * @param array $data The already fetched data
601 * @return array noscrape data
603 private function pollNoscrape($noscrape_url, $data) {
604 $ret = z_fetch_url($noscrape_url);
605 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
608 $content = $ret['body'];
610 logger("Empty body for ".$noscrape_url, LOGGER_DEBUG);
614 $json = json_decode($content, true);
615 if (!is_array($json)) {
616 logger("No json data for ".$noscrape_url, LOGGER_DEBUG);
620 if (isset($json["fn"])) {
621 $data["name"] = $json["fn"];
624 if (isset($json["addr"])) {
625 $data["addr"] = $json["addr"];
628 if (isset($json["nick"])) {
629 $data["nick"] = $json["nick"];
632 if (isset($json["comm"])) {
633 $data["community"] = $json["comm"];
636 if (isset($json["tags"])) {
637 $keywords = implode(" ", $json["tags"]);
638 if ($keywords != "") {
639 $data["keywords"] = $keywords;
643 $location = formatted_location($json);
645 $data["location"] = $location;
648 if (isset($json["about"])) {
649 $data["about"] = $json["about"];
652 if (isset($json["key"])) {
653 $data["pubkey"] = $json["key"];
656 if (isset($json["photo"])) {
657 $data["photo"] = $json["photo"];
660 if (isset($json["dfrn-request"])) {
661 $data["request"] = $json["dfrn-request"];
664 if (isset($json["dfrn-confirm"])) {
665 $data["confirm"] = $json["dfrn-confirm"];
668 if (isset($json["dfrn-notify"])) {
669 $data["notify"] = $json["dfrn-notify"];
672 if (isset($json["dfrn-poll"])) {
673 $data["poll"] = $json["dfrn-poll"];
680 * @brief Check for valid DFRN data
682 * @param array $data DFRN data
684 * @return int Number of errors
686 public static function validDfrn($data) {
688 if (!isset($data['key'])) {
691 if (!isset($data['dfrn-request'])) {
694 if (!isset($data['dfrn-confirm'])) {
697 if (!isset($data['dfrn-notify'])) {
700 if (!isset($data['dfrn-poll'])) {
707 * @brief Fetch data from a DFRN profile page and via "noscrape"
709 * @param string $profile_link Link to the profile page
711 * @return array profile data
713 public static function profile($profile_link) {
717 logger("Check profile ".$profile_link, LOGGER_DEBUG);
719 // Fetch data via noscrape - this is faster
720 $noscrape_url = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile_link);
721 $data = self::pollNoscrape($noscrape_url, $data);
723 if (!isset($data["notify"])
724 OR !isset($data["confirm"])
725 OR !isset($data["request"])
726 OR !isset($data["poll"])
727 OR !isset($data["poco"])
728 OR !isset($data["name"])
729 OR !isset($data["photo"])
731 $data = self::pollHcard($profile_link, $data, true);
734 $prof_data = array();
735 $prof_data["addr"] = $data["addr"];
736 $prof_data["nick"] = $data["nick"];
737 $prof_data["dfrn-request"] = $data["request"];
738 $prof_data["dfrn-confirm"] = $data["confirm"];
739 $prof_data["dfrn-notify"] = $data["notify"];
740 $prof_data["dfrn-poll"] = $data["poll"];
741 $prof_data["dfrn-poco"] = $data["poco"];
742 $prof_data["photo"] = $data["photo"];
743 $prof_data["fn"] = $data["name"];
744 $prof_data["key"] = $data["pubkey"];
746 logger("Result for profile ".$profile_link.": ".print_r($prof_data, true), LOGGER_DEBUG);
752 * @brief Check for DFRN contact
754 * @param array $webfinger Webfinger data
756 * @return array DFRN data
758 private function dfrn($webfinger) {
762 foreach ($webfinger["links"] as $link) {
763 if (($link["rel"] == NAMESPACE_DFRN) AND ($link["href"] != "")) {
764 $data["network"] = NETWORK_DFRN;
765 } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
766 $data["poll"] = $link["href"];
767 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND ($link["type"] == "text/html") AND ($link["href"] != "")) {
768 $data["url"] = $link["href"];
769 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != "")) {
770 $hcard_url = $link["href"];
771 } elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != "")) {
772 $data["poco"] = $link["href"];
773 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") AND ($link["href"] != "")) {
774 $data["photo"] = $link["href"];
775 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != "")) {
776 $data["baseurl"] = trim($link["href"], '/');
777 } elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != "")) {
778 $data["guid"] = $link["href"];
779 } elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
780 $data["pubkey"] = base64_decode($link["href"]);
782 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
783 if (strstr($data["pubkey"], 'RSA ')) {
784 $data["pubkey"] = rsatopem($data["pubkey"]);
789 if (!isset($data["network"]) OR ($hcard_url == "")) {
793 // Fetch data via noscrape - this is faster
794 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
795 $data = self::pollNoscrape($noscrape_url, $data);
797 if (isset($data["notify"])
798 AND isset($data["confirm"])
799 AND isset($data["request"])
800 AND isset($data["poll"])
801 AND isset($data["name"])
802 AND isset($data["photo"])
807 $data = self::pollHcard($hcard_url, $data, true);
813 * @brief Poll the hcard page (Diaspora and Friendica specific)
815 * @param string $hcard_url Link to the hcard page
816 * @param array $data The already fetched data
817 * @param boolean $dfrn Poll DFRN specific data
819 * @return array hcard data
821 private function pollHcard($hcard_url, $data, $dfrn = false) {
822 $ret = z_fetch_url($hcard_url);
823 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
826 $content = $ret['body'];
831 $doc = new DOMDocument();
832 if (!@$doc->loadHTML($content)) {
836 $xpath = new DomXPath($doc);
838 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
839 if (!is_object($vcards)) {
843 if ($vcards->length > 0) {
844 $vcard = $vcards->item(0);
846 // We have to discard the guid from the hcard in favour of the guid from lrdd
847 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
848 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
849 if (($search->length > 0) AND ($data["guid"] == "")) {
850 $data["guid"] = $search->item(0)->nodeValue;
853 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
854 if ($search->length > 0) {
855 $data["nick"] = $search->item(0)->nodeValue;
858 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
859 if ($search->length > 0) {
860 $data["name"] = $search->item(0)->nodeValue;
863 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
864 if ($search->length > 0) {
865 $data["searchable"] = $search->item(0)->nodeValue;
868 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
869 if ($search->length > 0) {
870 $data["pubkey"] = $search->item(0)->nodeValue;
871 if (strstr($data["pubkey"], 'RSA ')) {
872 $data["pubkey"] = rsatopem($data["pubkey"]);
876 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
877 if ($search->length > 0) {
878 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
883 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
884 foreach ($photos as $photo) {
886 foreach ($photo->attributes as $attribute) {
887 $attr[$attribute->name] = trim($attribute->value);
890 if (isset($attr["src"]) AND isset($attr["width"])) {
891 $avatar[$attr["width"]] = $attr["src"];
894 // We don't have a width. So we just take everything that we got.
895 // This is a Hubzilla workaround which doesn't send a width.
896 if ((sizeof($avatar) == 0) AND isset($attr["src"])) {
897 $avatar[] = $attr["src"];
901 if (sizeof($avatar)) {
903 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
907 // Poll DFRN specific data
908 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
909 if ($search->length > 0) {
910 foreach ($search as $link) {
911 //$data["request"] = $search->item(0)->nodeValue;
913 foreach ($link->attributes as $attribute) {
914 $attr[$attribute->name] = trim($attribute->value);
917 $data[substr($attr["rel"], 5)] = $attr["href"];
921 // Older Friendica versions had used the "uid" field differently than newer versions
922 if ($data["nick"] == $data["guid"]) {
923 unset($data["guid"]);
932 * @brief Check for Diaspora contact
934 * @param array $webfinger Webfinger data
936 * @return array Diaspora data
938 private function diaspora($webfinger) {
942 foreach ($webfinger["links"] as $link) {
943 if (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != "")) {
944 $hcard_url = $link["href"];
945 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != "")) {
946 $data["baseurl"] = trim($link["href"], '/');
947 } elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != "")) {
948 $data["guid"] = $link["href"];
949 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND ($link["type"] == "text/html") AND ($link["href"] != "")) {
950 $data["url"] = $link["href"];
951 } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
952 $data["poll"] = $link["href"];
953 } elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != "")) {
954 $data["poco"] = $link["href"];
955 } elseif (($link["rel"] == "salmon") AND ($link["href"] != "")) {
956 $data["notify"] = $link["href"];
957 } elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
958 $data["pubkey"] = base64_decode($link["href"]);
960 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
961 if (strstr($data["pubkey"], 'RSA ')) {
962 $data["pubkey"] = rsatopem($data["pubkey"]);
967 if (!isset($data["url"]) OR ($hcard_url == "")) {
971 if (is_array($webfinger["aliases"])) {
972 foreach ($webfinger["aliases"] as $alias) {
973 if (normalise_link($alias) != normalise_link($data["url"]) AND ! strstr($alias, "@")) {
974 $data["alias"] = $alias;
979 // Fetch further information from the hcard
980 $data = self::pollHcard($hcard_url, $data);
986 if (isset($data["url"])
987 AND isset($data["guid"])
988 AND isset($data["baseurl"])
989 AND isset($data["pubkey"])
990 AND ($hcard_url != "")
992 $data["network"] = NETWORK_DIASPORA;
994 // The Diaspora handle must always be lowercase
995 $data["addr"] = strtolower($data["addr"]);
997 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
998 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
999 $data["batch"] = $data["baseurl"] . "/receive/public";
1008 * @brief Check for OStatus contact
1010 * @param array $webfinger Webfinger data
1012 * @return array OStatus data
1014 private function ostatus($webfinger) {
1016 if (is_array($webfinger["aliases"])) {
1017 foreach ($webfinger["aliases"] as $alias) {
1018 if (strstr($alias, "@")) {
1019 $data["addr"] = str_replace('acct:', '', $alias);
1024 if (is_string($webfinger["subject"]) AND strstr($webfinger["subject"], "@")) {
1025 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1028 foreach ($webfinger["links"] as $link) {
1029 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1030 AND ($link["type"] == "text/html")
1031 AND ($link["href"] != "")
1033 $data["url"] = $link["href"];
1034 } elseif (($link["rel"] == "salmon") AND ($link["href"] != "")) {
1035 $data["notify"] = $link["href"];
1036 } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
1037 $data["poll"] = $link["href"];
1038 } elseif (($link["rel"] == "magic-public-key") AND ($link["href"] != "")) {
1039 $pubkey = $link["href"];
1041 if (substr($pubkey, 0, 5) === 'data:') {
1042 if (strstr($pubkey, ',')) {
1043 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1045 $pubkey = substr($pubkey, 5);
1047 } elseif (normalise_link($pubkey) == 'http://') {
1048 $ret = z_fetch_url($pubkey);
1049 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1052 $pubkey = $ret['body'];
1055 $key = explode(".", $pubkey);
1057 if (sizeof($key) >= 3) {
1058 $m = base64url_decode($key[1]);
1059 $e = base64url_decode($key[2]);
1060 $data["pubkey"] = metopem($m, $e);
1065 if (isset($data["notify"]) AND isset($data["pubkey"])
1066 AND isset($data["poll"])
1067 AND isset($data["url"])
1069 $data["network"] = NETWORK_OSTATUS;
1073 // Fetch all additional data from the feed
1074 $ret = z_fetch_url($data["poll"]);
1075 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1078 $feed = $ret['body'];
1079 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1083 if ($feed_data["header"]["author-name"] != "") {
1084 $data["name"] = $feed_data["header"]["author-name"];
1086 if ($feed_data["header"]["author-nick"] != "") {
1087 $data["nick"] = $feed_data["header"]["author-nick"];
1089 if ($feed_data["header"]["author-avatar"] != "") {
1090 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1092 if ($feed_data["header"]["author-id"] != "") {
1093 $data["alias"] = $feed_data["header"]["author-id"];
1095 if ($feed_data["header"]["author-location"] != "") {
1096 $data["location"] = $feed_data["header"]["author-location"];
1098 if ($feed_data["header"]["author-about"] != "") {
1099 $data["about"] = $feed_data["header"]["author-about"];
1101 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1102 // So we take the value that we just fetched, although the other one worked as well
1103 if ($feed_data["header"]["author-link"] != "") {
1104 $data["url"] = $feed_data["header"]["author-link"];
1106 /// @todo Fetch location and "about" from the feed as well
1111 * @brief Fetch data from a pump.io profile page
1113 * @param string $profile_link Link to the profile page
1115 * @return array profile data
1117 private function pumpioProfileData($profile_link) {
1119 $doc = new DOMDocument();
1120 if (!@$doc->loadHTMLFile($profile_link)) {
1124 $xpath = new DomXPath($doc);
1128 // This is ugly - but pump.io doesn't seem to know a better way for it
1129 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1130 $pos = strpos($data["name"], chr(10));
1132 $data["name"] = trim(substr($data["name"], 0, $pos));
1135 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1137 foreach ($avatar->attributes as $attribute) {
1138 if ($attribute->name == "src") {
1139 $data["photo"] = trim($attribute->value);
1144 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
1145 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
1151 * @brief Check for pump.io contact
1153 * @param array $webfinger Webfinger data
1155 * @return array pump.io data
1157 private function pumpio($webfinger) {
1160 foreach ($webfinger["links"] as $link) {
1161 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1162 AND ($link["type"] == "text/html")
1163 AND ($link["href"] != "")
1165 $data["url"] = $link["href"];
1166 } elseif (($link["rel"] == "activity-inbox") AND ($link["href"] != "")) {
1167 $data["notify"] = $link["href"];
1168 } elseif (($link["rel"] == "activity-outbox") AND ($link["href"] != "")) {
1169 $data["poll"] = $link["href"];
1170 } elseif (($link["rel"] == "dialback") AND ($link["href"] != "")) {
1171 $data["dialback"] = $link["href"];
1174 if (isset($data["poll"]) AND isset($data["notify"])
1175 AND isset($data["dialback"])
1176 AND isset($data["url"])
1178 // by now we use these fields only for the network type detection
1179 // So we unset all data that isn't used at the moment
1180 unset($data["dialback"]);
1182 $data["network"] = NETWORK_PUMPIO;
1187 $profile_data = self::pumpioProfileData($data["url"]);
1189 if (!$profile_data) {
1193 $data = array_merge($data, $profile_data);
1199 * @brief Check page for feed link
1201 * @param string $url Page link
1203 * @return string feed link
1205 private function getFeedLink($url) {
1206 $doc = new DOMDocument();
1208 if (!@$doc->loadHTMLFile($url)) {
1212 $xpath = new DomXPath($doc);
1214 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1215 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1216 if (!is_object($feeds)) {
1220 if ($feeds->length == 0) {
1226 foreach ($feeds as $feed) {
1228 foreach ($feed->attributes as $attribute) {
1229 $attr[$attribute->name] = trim($attribute->value);
1232 if ($feed_url == "") {
1233 $feed_url = $attr["href"];
1241 * @brief Check for feed contact
1243 * @param string $url Profile link
1244 * @param boolean $probe Do a probe if the page contains a feed link
1246 * @return array feed data
1248 private function feed($url, $probe = true) {
1249 $ret = z_fetch_url($url);
1250 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1253 $feed = $ret['body'];
1254 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1261 $feed_url = self::getFeedLink($url);
1267 return self::feed($feed_url, false);
1270 if ($feed_data["header"]["author-name"] != "") {
1271 $data["name"] = $feed_data["header"]["author-name"];
1274 if ($feed_data["header"]["author-nick"] != "") {
1275 $data["nick"] = $feed_data["header"]["author-nick"];
1278 if ($feed_data["header"]["author-avatar"] != "") {
1279 $data["photo"] = $feed_data["header"]["author-avatar"];
1282 if ($feed_data["header"]["author-id"] != "") {
1283 $data["alias"] = $feed_data["header"]["author-id"];
1286 $data["url"] = $url;
1287 $data["poll"] = $url;
1289 if ($feed_data["header"]["author-link"] != "") {
1290 $data["baseurl"] = $feed_data["header"]["author-link"];
1292 $data["baseurl"] = $data["url"];
1295 $data["network"] = NETWORK_FEED;
1301 * @brief Check for mail contact
1303 * @param string $uri Profile link
1304 * @param integer $uid User ID
1306 * @return array mail data
1308 private function mail($uri, $uid) {
1310 if (!validate_email($uri)) {
1314 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1316 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1318 if (dbm::is_result($x) && dbm::is_result($r)) {
1319 $mailbox = construct_mailbox_name($r[0]);
1321 openssl_private_decrypt(hex2bin($r[0]['pass']), $password, $x[0]['prvkey']);
1322 $mbox = email_connect($mailbox, $r[0]['user'], $password);
1328 $msgs = email_poll($mbox, $uri);
1329 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1331 if (!count($msgs)) {
1335 $phost = substr($uri, strpos($uri, '@') + 1);
1338 $data["addr"] = $uri;
1339 $data["network"] = NETWORK_MAIL;
1340 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1341 $data["nick"] = $data["name"];
1342 $data["photo"] = avatar_img($uri);
1343 $data["url"] = 'http://'.$phost."/".$data["nick"];
1344 $data["notify"] = 'smtp '.random_string();
1345 $data["poll"] = 'email '.random_string();
1347 $x = email_msg_meta($mbox, $msgs[0]);
1348 if (stristr($x[0]->from, $uri)) {
1349 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1350 } elseif (stristr($x[0]->to, $uri)) {
1351 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1354 foreach ($adr as $feadr) {
1355 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1356 &&(strcasecmp($feadr->host, $phost) == 0)
1357 && (strlen($feadr->personal))
1359 $personal = imap_mime_header_decode($feadr->personal);
1361 foreach ($personal as $perspart) {
1362 if ($perspart->charset != "default") {
1363 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1365 $data["name"] .= $perspart->text;
1369 $data["name"] = notags($data["name"]);
1379 * @brief Mix two paths together to possibly fix missing parts
1381 * @param string $avatar Path to the avatar
1382 * @param string $base Another path that is hopefully complete
1384 * @return string fixed avatar path
1386 public static function fixAvatar($avatar, $base) {
1387 $base_parts = parse_url($base);
1389 // Remove all parts that could create a problem
1390 unset($base_parts['path']);
1391 unset($base_parts['query']);
1392 unset($base_parts['fragment']);
1394 $avatar_parts = parse_url($avatar);
1397 $parts = array_merge($base_parts, $avatar_parts);
1399 // And put them together again
1400 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1401 $host = isset($parts['host']) ? $parts['host'] : '';
1402 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1403 $path = isset($parts['path']) ? $parts['path'] : '';
1404 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1405 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1407 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1409 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);