3 namespace Friendica\Network;
6 * @file src/Network/Probe.php
7 * @brief Functions for probing URL
12 use Friendica\Core\System;
13 use Friendica\Core\Config;
14 use Friendica\Network\Probe;
24 require_once 'include/feed.php';
25 require_once 'include/email.php';
26 require_once 'include/network.php';
29 * @brief This class contain functions for probing URL
34 private static $baseurl;
37 * @brief Rearrange the array so that it always has the same order
39 * @param array $data Unordered data
41 * @return array Ordered data
43 private static function rearrangeData($data) {
44 $fields = array("name", "nick", "guid", "url", "addr", "alias",
45 "photo", "community", "keywords", "location", "about",
46 "batch", "notify", "poll", "request", "confirm", "poco",
47 "priority", "network", "pubkey", "baseurl");
50 foreach ($fields as $field) {
51 if (isset($data[$field])) {
52 $newdata[$field] = $data[$field];
54 $newdata[$field] = "";
58 // We don't use the "priority" field anymore and replace it with a dummy.
59 $newdata["priority"] = 0;
65 * @brief Check if the hostname belongs to the own server
67 * @param string $host The hostname that is to be checked
69 * @return bool Does the testes hostname belongs to the own server?
71 private static function ownHost($host) {
72 $own_host = get_app()->get_hostname();
74 $parts = parse_url($host);
76 if (!isset($parts['scheme'])) {
77 $parts = parse_url('http://'.$host);
80 if (!isset($parts['host'])) {
83 return $parts['host'] == $own_host;
87 * @brief Probes for webfinger path via "host-meta"
89 * @param string $host The host part of an url
91 * @return array with template and type of the webfinger template for JSON or XML
93 private static function hostMeta($host) {
95 // Reset the static variable
98 $ssl_url = "https://".$host."/.well-known/host-meta";
99 $url = "http://".$host."/.well-known/host-meta";
101 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
104 logger("Probing for ".$host, LOGGER_DEBUG);
106 $ret = z_fetch_url($ssl_url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
107 if ($ret['success']) {
109 $xrd = parse_xml_string($xml, false);
110 $host_url = 'https://'.$host;
113 if (!is_object($xrd)) {
114 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
115 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
116 logger("Probing timeout for ".$url, LOGGER_DEBUG);
120 $xrd = parse_xml_string($xml, false);
121 $host_url = 'http://'.$host;
123 if (!is_object($xrd)) {
124 logger("No xrd object found for ".$host, LOGGER_DEBUG);
128 $links = xml::element_to_array($xrd);
129 if (!isset($links["xrd"]["link"])) {
130 logger("No xrd data found for ".$host, LOGGER_DEBUG);
135 // The following webfinger path is defined in RFC 7033 https://tools.ietf.org/html/rfc7033
136 // Problem is that Hubzilla currently doesn't provide all data in the JSON webfinger
137 // compared to the XML webfinger. So this is commented out by now.
138 // $lrdd = array("application/jrd+json" => $host_url.'/.well-known/webfinger?resource={uri}');
140 foreach ($links["xrd"]["link"] as $value => $link) {
141 if (!empty($link["@attributes"])) {
142 $attributes = $link["@attributes"];
143 } elseif ($value == "@attributes") {
149 if (($attributes["rel"] == "lrdd") && !empty($attributes["template"])) {
150 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
152 $lrdd[$type] = $attributes["template"];
156 self::$baseurl = "http://".$host;
158 logger("Probing successful for ".$host, LOGGER_DEBUG);
164 * @brief Perform Webfinger lookup and return DFRN data
166 * Given an email style address, perform webfinger lookup and
167 * return the resulting DFRN profile URL, or if no DFRN profile URL
168 * is located, returns an OStatus subscription template (prefixed
169 * with the string 'stat:' to identify it as on OStatus template).
170 * If this isn't an email style address just return $webbie.
171 * Return an empty string if email-style addresses but webfinger fails,
172 * or if the resultant personal XRD doesn't contain a supported
173 * subscription/friend-request attribute.
175 * amended 7/9/2011 to return an hcard which could save potentially loading
176 * a lengthy content page to scrape dfrn attributes
178 * @param string $webbie Address that should be probed
179 * @param string $hcard_url Link to the hcard - is returned by reference
181 * @return string profile link
183 public static function webfingerDfrn($webbie, &$hcard_url) {
187 $links = self::lrdd($webbie);
188 logger('webfingerDfrn: '.$webbie.':'.print_r($links, true), LOGGER_DATA);
190 foreach ($links as $link) {
191 if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
192 $profile_link = $link['@attributes']['href'];
194 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) && ($profile_link == "")) {
195 $profile_link = 'stat:'.$link['@attributes']['template'];
197 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
198 $hcard_url = $link['@attributes']['href'];
202 return $profile_link;
206 * @brief Check an URI for LRDD data
208 * this is a replacement for the "lrdd" function in include/network.php.
209 * It isn't used in this class and has some redundancies in the code.
210 * When time comes we can check the existing calls for "lrdd" if we can rework them.
212 * @param string $uri Address that should be probed
214 * @return array uri data
216 public static function lrdd($uri) {
218 $lrdd = self::hostMeta($uri);
221 if (is_bool($lrdd)) {
226 $parts = @parse_url($uri);
231 $host = $parts["host"];
232 if (!empty($parts["port"])) {
233 $host .= ':'.$parts["port"];
236 $path_parts = explode("/", trim($parts["path"], "/"));
238 $nick = array_pop($path_parts);
241 $lrdd = self::hostMeta($host);
242 $host .= "/".array_shift($path_parts);
243 } while (!$lrdd && (sizeof($path_parts) > 0));
247 logger("No lrdd data found for ".$uri, LOGGER_DEBUG);
251 foreach ($lrdd AS $type => $template) {
256 $path = str_replace('{uri}', urlencode($uri), $template);
257 $webfinger = self::webfinger($path, $type);
259 if (!$webfinger && (strstr($uri, "@"))) {
260 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
261 $webfinger = self::webfinger($path, $type);
264 // Special treatment for Mastodon
265 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
266 // But the webfinger for this format fails.
267 if (!$webfinger && !empty($nick)) {
268 // Mastodon uses a "@" as prefix for usernames in their url format
269 $nick = ltrim($nick, '@');
271 $addr = $nick."@".$host;
273 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
274 $webfinger = self::webfinger($path, $type);
278 if (!is_array($webfinger["links"])) {
279 logger("No webfinger links found for ".$uri, LOGGER_DEBUG);
285 foreach ($webfinger["links"] as $link) {
286 $data[] = array("@attributes" => $link);
289 if (is_array($webfinger["aliases"])) {
290 foreach ($webfinger["aliases"] as $alias) {
291 $data[] = array("@attributes" =>
292 array("rel" => "alias",
301 * @brief Fetch information (protocol endpoints and user information) about a given uri
303 * @param string $uri Address that should be probed
304 * @param string $network Test for this specific network
305 * @param integer $uid User ID for the probe (only used for mails)
306 * @param boolean $cache Use cached values?
308 * @return array uri data
310 public static function uri($uri, $network = "", $uid = -1, $cache = true) {
313 $result = Cache::get("Probe::uri:".$network.":".$uri);
314 if (!is_null($result)) {
323 $data = self::detect($uri, $network, $uid);
325 if (!isset($data["url"])) {
329 if ($data["photo"] != "") {
330 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
332 $data["photo"] = System::baseUrl().'/images/person-175.jpg';
335 if (empty($data["name"])) {
336 if (!empty($data["nick"])) {
337 $data["name"] = $data["nick"];
340 if ($data["name"] == "") {
341 $data["name"] = $data["url"];
345 if (empty($data["nick"])) {
346 $data["nick"] = strtolower($data["name"]);
348 if (strpos($data['nick'], ' ')) {
349 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
353 if (self::$baseurl != "") {
354 $data["baseurl"] = self::$baseurl;
357 if (!isset($data["network"])) {
358 $data["network"] = NETWORK_PHANTOM;
361 $data = self::rearrangeData($data);
363 // Only store into the cache if the value seems to be valid
364 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
365 Cache::set("Probe::uri:".$network.":".$uri, $data, CACHE_DAY);
367 /// @todo temporary fix - we need a real contact update function that updates only changing fields
368 /// The biggest problem is the avatar picture that could have a reduced image size.
369 /// It should only be updated if the existing picture isn't existing anymore.
370 /// We only update the contact when it is no probing for a specific network.
371 if (($data['network'] != NETWORK_FEED)
379 $fields = array('name' => $data['name'],
380 'nick' => $data['nick'],
381 'url' => $data['url'],
382 'addr' => $data['addr'],
383 'photo' => $data['photo'],
384 'keywords' => $data['keywords'],
385 'location' => $data['location'],
386 'about' => $data['about'],
387 'notify' => $data['notify'],
388 'network' => $data['network'],
389 'server_url' => $data['baseurl']);
391 $fieldnames = array();
393 foreach ($fields AS $key => $val) {
395 unset($fields[$key]);
397 $fieldnames[] = $key;
401 $fields['updated'] = dbm::date();
403 $condition = array('nurl' => normalise_link($data["url"]));
405 $old_fields = dba::select('gcontact', $fieldnames, $condition, array('limit' => 1));
407 dba::update('gcontact', $fields, $condition, $old_fields);
409 $fields = array('name' => $data['name'],
410 'nick' => $data['nick'],
411 'url' => $data['url'],
412 'addr' => $data['addr'],
413 'alias' => $data['alias'],
414 'keywords' => $data['keywords'],
415 'location' => $data['location'],
416 'about' => $data['about'],
417 'batch' => $data['batch'],
418 'notify' => $data['notify'],
419 'poll' => $data['poll'],
420 'request' => $data['request'],
421 'confirm' => $data['confirm'],
422 'poco' => $data['poco'],
423 'network' => $data['network'],
424 'success_update' => dbm::date());
426 $fieldnames = array();
428 foreach ($fields AS $key => $val) {
430 unset($fields[$key]);
432 $fieldnames[] = $key;
436 $condition = array('nurl' => normalise_link($data["url"]), 'self' => false, 'uid' => 0);
438 $old_fields = dba::select('contact', $fieldnames, $condition, array('limit' => 1));
440 dba::update('contact', $fields, $condition, $old_fields);
448 * @brief Switch the scheme of an url between http and https
450 * @param string $url URL
452 * @return string switched URL
454 private static function switchScheme($url) {
455 $parts = parse_url($url);
457 if (!isset($parts['scheme'])) {
461 if ($parts['scheme'] == 'http') {
462 $url = str_replace('http://', 'https://', $url);
463 } elseif ($parts['scheme'] == 'https') {
464 $url = str_replace('https://', 'http://', $url);
471 * @brief Checks if a profile url should be OStatus but only provides partial information
473 * @param array $webfinger Webfinger data
474 * @param string $lrdd Path template for webfinger request
476 * @return array fixed webfinger data
478 private static function fixOstatus($webfinger, $lrdd, $type) {
479 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
486 foreach ($webfinger['links'] as $link) {
487 if ($link['rel'] == NAMESPACE_OSTATUSSUB) {
490 if ($link['rel'] == 'magic-public-key') {
495 if (!$is_ostatus || $has_key) {
499 $url = self::switchScheme($webfinger['subject']);
500 $path = str_replace('{uri}', urlencode($url), $lrdd);
501 $webfinger2 = self::webfinger($path, $type);
503 // Is the new webfinger detectable as OStatus?
504 if (self::ostatus($webfinger2, true)) {
505 $webfinger = $webfinger2;
512 * @brief Fetch information (protocol endpoints and user information) about a given uri
514 * This function is only called by the "uri" function that adds caching and rearranging of data.
516 * @param string $uri Address that should be probed
517 * @param string $network Test for this specific network
518 * @param integer $uid User ID for the probe (only used for mails)
520 * @return array uri data
522 private static function detect($uri, $network, $uid) {
523 $parts = parse_url($uri);
525 if (!empty($parts["scheme"]) && !empty($parts["host"]) && !empty($parts["path"])) {
526 $host = $parts["host"];
527 if (!empty($parts["port"])) {
528 $host .= ':'.$parts["port"];
531 if ($host == 'twitter.com') {
532 return array("network" => NETWORK_TWITTER);
534 $lrdd = self::hostMeta($host);
536 if (is_bool($lrdd)) {
540 $path_parts = explode("/", trim($parts["path"], "/"));
542 while (!$lrdd && (sizeof($path_parts) > 1)) {
543 $host .= "/".array_shift($path_parts);
544 $lrdd = self::hostMeta($host);
547 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
548 return self::feed($uri);
550 $nick = array_pop($path_parts);
552 // Mastodon uses a "@" as prefix for usernames in their url format
553 $nick = ltrim($nick, '@');
555 $addr = $nick."@".$host;
557 } elseif (strstr($uri, '@')) {
558 // If the URI starts with "mailto:" then jump directly to the mail detection
559 if (strpos($uri, 'mailto:') !== false) {
560 $uri = str_replace('mailto:', '', $uri);
561 return self::mail($uri, $uid);
564 if ($network == NETWORK_MAIL) {
565 return self::mail($uri, $uid);
567 // Remove "acct:" from the URI
568 $uri = str_replace('acct:', '', $uri);
570 $host = substr($uri, strpos($uri, '@') + 1);
571 $nick = substr($uri, 0, strpos($uri, '@'));
573 if (strpos($uri, '@twitter.com')) {
574 return array("network" => NETWORK_TWITTER);
576 $lrdd = self::hostMeta($host);
578 if (is_bool($lrdd)) {
583 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
584 return self::mail($uri, $uid);
589 logger("Uri ".$uri." was not detectable", LOGGER_DEBUG);
595 /// @todo Do we need the prefix "acct:" or "acct://"?
597 foreach ($lrdd AS $type => $template) {
602 // At first try it with the given uri
603 $path = str_replace('{uri}', urlencode($uri), $template);
604 $webfinger = self::webfinger($path, $type);
606 // Fix possible problems with GNU Social probing to wrong scheme
607 $webfinger = self::fixOstatus($webfinger, $template, $type);
609 // We cannot be sure that the detected address was correct, so we don't use the values
610 if ($webfinger && ($uri != $addr)) {
615 // Try webfinger with the address (user@domain.tld)
617 $path = str_replace('{uri}', urlencode($addr), $template);
618 $webfinger = self::webfinger($path, $type);
621 // Mastodon needs to have it with "acct:"
623 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
624 $webfinger = self::webfinger($path, $type);
629 return self::feed($uri);
634 logger("Probing ".$uri, LOGGER_DEBUG);
636 if (in_array($network, array("", NETWORK_DFRN))) {
637 $result = self::dfrn($webfinger);
639 if ((!$result && ($network == "")) || ($network == NETWORK_DIASPORA)) {
640 $result = self::diaspora($webfinger);
642 if ((!$result && ($network == "")) || ($network == NETWORK_OSTATUS)) {
643 $result = self::ostatus($webfinger);
645 if ((!$result && ($network == "")) || ($network == NETWORK_PUMPIO)) {
646 $result = self::pumpio($webfinger);
648 if ((!$result && ($network == "")) || ($network == NETWORK_FEED)) {
649 $result = self::feed($uri);
651 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
652 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
653 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
654 $result["nick"] = $nick;
657 if (empty($result["addr"]) && ($addr != "")) {
658 $result["addr"] = $addr;
662 logger($uri." is ".$result["network"], LOGGER_DEBUG);
664 if (empty($result["baseurl"])) {
665 $pos = strpos($result["url"], $host);
667 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
675 * @brief Perform a webfinger request.
677 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
679 * @param string $url Address that should be probed
681 * @return array webfinger data
683 private static function webfinger($url, $type) {
685 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
688 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => $type));
689 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
692 $data = $ret['body'];
694 $webfinger = json_decode($data, true);
695 if (is_array($webfinger)) {
696 if (!isset($webfinger["links"])) {
697 logger("No json webfinger links for ".$url, LOGGER_DEBUG);
703 // If it is not JSON, maybe it is XML
704 $xrd = parse_xml_string($data, false);
705 if (!is_object($xrd)) {
706 logger("No webfinger data retrievable for ".$url, LOGGER_DEBUG);
710 $xrd_arr = xml::element_to_array($xrd);
711 if (!isset($xrd_arr["xrd"]["link"])) {
712 logger("No XML webfinger links for ".$url, LOGGER_DEBUG);
716 $webfinger = array();
718 if (!empty($xrd_arr["xrd"]["subject"])) {
719 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
722 if (!empty($xrd_arr["xrd"]["alias"])) {
723 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
726 $webfinger["links"] = array();
728 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
729 if (!empty($data["@attributes"])) {
730 $attributes = $data["@attributes"];
731 } elseif ($value == "@attributes") {
737 $webfinger["links"][] = $attributes;
743 * @brief Poll the Friendica specific noscrape page.
745 * "noscrape" is a faster alternative to fetch the data from the hcard.
746 * This functionality was originally created for the directory.
748 * @param string $noscrape_url Link to the noscrape page
749 * @param array $data The already fetched data
751 * @return array noscrape data
753 private static function pollNoscrape($noscrape_url, $data) {
754 $ret = z_fetch_url($noscrape_url);
755 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
758 $content = $ret['body'];
760 logger("Empty body for ".$noscrape_url, LOGGER_DEBUG);
764 $json = json_decode($content, true);
765 if (!is_array($json)) {
766 logger("No json data for ".$noscrape_url, LOGGER_DEBUG);
770 if (!empty($json["fn"])) {
771 $data["name"] = $json["fn"];
774 if (!empty($json["addr"])) {
775 $data["addr"] = $json["addr"];
778 if (!empty($json["nick"])) {
779 $data["nick"] = $json["nick"];
782 if (!empty($json["guid"])) {
783 $data["guid"] = $json["guid"];
786 if (!empty($json["comm"])) {
787 $data["community"] = $json["comm"];
790 if (!empty($json["tags"])) {
791 $keywords = implode(" ", $json["tags"]);
792 if ($keywords != "") {
793 $data["keywords"] = $keywords;
797 $location = formatted_location($json);
799 $data["location"] = $location;
802 if (!empty($json["about"])) {
803 $data["about"] = $json["about"];
806 if (!empty($json["key"])) {
807 $data["pubkey"] = $json["key"];
810 if (!empty($json["photo"])) {
811 $data["photo"] = $json["photo"];
814 if (!empty($json["dfrn-request"])) {
815 $data["request"] = $json["dfrn-request"];
818 if (!empty($json["dfrn-confirm"])) {
819 $data["confirm"] = $json["dfrn-confirm"];
822 if (!empty($json["dfrn-notify"])) {
823 $data["notify"] = $json["dfrn-notify"];
826 if (!empty($json["dfrn-poll"])) {
827 $data["poll"] = $json["dfrn-poll"];
834 * @brief Check for valid DFRN data
836 * @param array $data DFRN data
838 * @return int Number of errors
840 public static function validDfrn($data) {
842 if (!isset($data['key'])) {
845 if (!isset($data['dfrn-request'])) {
848 if (!isset($data['dfrn-confirm'])) {
851 if (!isset($data['dfrn-notify'])) {
854 if (!isset($data['dfrn-poll'])) {
861 * @brief Fetch data from a DFRN profile page and via "noscrape"
863 * @param string $profile_link Link to the profile page
865 * @return array profile data
867 public static function profile($profile_link) {
871 logger("Check profile ".$profile_link, LOGGER_DEBUG);
873 // Fetch data via noscrape - this is faster
874 $noscrape_url = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile_link);
875 $data = self::pollNoscrape($noscrape_url, $data);
877 if (!isset($data["notify"])
878 || !isset($data["confirm"])
879 || !isset($data["request"])
880 || !isset($data["poll"])
881 || !isset($data["poco"])
882 || !isset($data["name"])
883 || !isset($data["photo"])
885 $data = self::pollHcard($profile_link, $data, true);
888 $prof_data = array();
889 $prof_data["addr"] = $data["addr"];
890 $prof_data["nick"] = $data["nick"];
891 $prof_data["dfrn-request"] = $data["request"];
892 $prof_data["dfrn-confirm"] = $data["confirm"];
893 $prof_data["dfrn-notify"] = $data["notify"];
894 $prof_data["dfrn-poll"] = $data["poll"];
895 $prof_data["dfrn-poco"] = $data["poco"];
896 $prof_data["photo"] = $data["photo"];
897 $prof_data["fn"] = $data["name"];
898 $prof_data["key"] = $data["pubkey"];
900 logger("Result for profile ".$profile_link.": ".print_r($prof_data, true), LOGGER_DEBUG);
906 * @brief Check for DFRN contact
908 * @param array $webfinger Webfinger data
910 * @return array DFRN data
912 private static function dfrn($webfinger) {
915 foreach ($webfinger["links"] as $link) {
916 if (($link["rel"] == NAMESPACE_DFRN) && ($link["href"] != "")) {
917 $data["network"] = NETWORK_DFRN;
918 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
919 $data["poll"] = $link["href"];
920 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
921 $data["url"] = $link["href"];
922 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
923 $hcard_url = $link["href"];
924 } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
925 $data["poco"] = $link["href"];
926 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && ($link["href"] != "")) {
927 $data["photo"] = $link["href"];
928 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
929 $data["baseurl"] = trim($link["href"], '/');
930 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
931 $data["guid"] = $link["href"];
932 } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
933 $data["pubkey"] = base64_decode($link["href"]);
935 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
936 if (strstr($data["pubkey"], 'RSA ')) {
937 $data["pubkey"] = rsatopem($data["pubkey"]);
942 if (is_array($webfinger["aliases"])) {
943 foreach ($webfinger["aliases"] as $alias) {
944 if (normalise_link($alias) != normalise_link($data["url"]) && ! strstr($alias, "@")) {
945 $data["alias"] = $alias;
946 } elseif (substr($alias, 0, 5) == 'acct:') {
947 $data["addr"] = substr($alias, 5);
952 if (!isset($data["network"]) || ($hcard_url == "")) {
956 // Fetch data via noscrape - this is faster
957 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
958 $data = self::pollNoscrape($noscrape_url, $data);
960 if (isset($data["notify"])
961 && isset($data["confirm"])
962 && isset($data["request"])
963 && isset($data["poll"])
964 && isset($data["name"])
965 && isset($data["photo"])
970 $data = self::pollHcard($hcard_url, $data, true);
976 * @brief Poll the hcard page (Diaspora and Friendica specific)
978 * @param string $hcard_url Link to the hcard page
979 * @param array $data The already fetched data
980 * @param boolean $dfrn Poll DFRN specific data
982 * @return array hcard data
984 private static function pollHcard($hcard_url, $data, $dfrn = false) {
985 $ret = z_fetch_url($hcard_url);
986 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
989 $content = $ret['body'];
994 $doc = new DOMDocument();
995 if (!@$doc->loadHTML($content)) {
999 $xpath = new DomXPath($doc);
1001 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1002 if (!is_object($vcards)) {
1006 if ($vcards->length > 0) {
1007 $vcard = $vcards->item(0);
1009 // We have to discard the guid from the hcard in favour of the guid from lrdd
1010 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1011 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1012 if (($search->length > 0) && ($data["guid"] == "")) {
1013 $data["guid"] = $search->item(0)->nodeValue;
1016 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1017 if ($search->length > 0) {
1018 $data["nick"] = $search->item(0)->nodeValue;
1021 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1022 if ($search->length > 0) {
1023 $data["name"] = $search->item(0)->nodeValue;
1026 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1027 if ($search->length > 0) {
1028 $data["searchable"] = $search->item(0)->nodeValue;
1031 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1032 if ($search->length > 0) {
1033 $data["pubkey"] = $search->item(0)->nodeValue;
1034 if (strstr($data["pubkey"], 'RSA ')) {
1035 $data["pubkey"] = rsatopem($data["pubkey"]);
1039 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1040 if ($search->length > 0) {
1041 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1046 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1047 foreach ($photos as $photo) {
1049 foreach ($photo->attributes as $attribute) {
1050 $attr[$attribute->name] = trim($attribute->value);
1053 if (isset($attr["src"]) && isset($attr["width"])) {
1054 $avatar[$attr["width"]] = $attr["src"];
1057 // We don't have a width. So we just take everything that we got.
1058 // This is a Hubzilla workaround which doesn't send a width.
1059 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1060 $avatar[] = $attr["src"];
1064 if (sizeof($avatar)) {
1066 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1070 // Poll DFRN specific data
1071 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1072 if ($search->length > 0) {
1073 foreach ($search as $link) {
1074 //$data["request"] = $search->item(0)->nodeValue;
1076 foreach ($link->attributes as $attribute) {
1077 $attr[$attribute->name] = trim($attribute->value);
1080 $data[substr($attr["rel"], 5)] = $attr["href"];
1084 // Older Friendica versions had used the "uid" field differently than newer versions
1085 if ($data["nick"] == $data["guid"]) {
1086 unset($data["guid"]);
1095 * @brief Check for Diaspora contact
1097 * @param array $webfinger Webfinger data
1099 * @return array Diaspora data
1101 private static function diaspora($webfinger) {
1104 foreach ($webfinger["links"] as $link) {
1105 if (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
1106 $hcard_url = $link["href"];
1107 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
1108 $data["baseurl"] = trim($link["href"], '/');
1109 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
1110 $data["guid"] = $link["href"];
1111 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
1112 $data["url"] = $link["href"];
1113 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1114 $data["poll"] = $link["href"];
1115 } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
1116 $data["poco"] = $link["href"];
1117 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1118 $data["notify"] = $link["href"];
1119 } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
1120 $data["pubkey"] = base64_decode($link["href"]);
1122 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1123 if (strstr($data["pubkey"], 'RSA ')) {
1124 $data["pubkey"] = rsatopem($data["pubkey"]);
1129 if (!isset($data["url"]) || ($hcard_url == "")) {
1133 if (is_array($webfinger["aliases"])) {
1134 foreach ($webfinger["aliases"] as $alias) {
1135 if (normalise_link($alias) != normalise_link($data["url"]) && ! strstr($alias, "@")) {
1136 $data["alias"] = $alias;
1137 } elseif (substr($alias, 0, 5) == 'acct:') {
1138 $data["addr"] = substr($alias, 5);
1143 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1144 $data["addr"] = substr($webfinger["subject"], 5);
1147 // Fetch further information from the hcard
1148 $data = self::pollHcard($hcard_url, $data);
1154 if (isset($data["url"])
1155 && isset($data["guid"])
1156 && isset($data["baseurl"])
1157 && isset($data["pubkey"])
1158 && ($hcard_url != "")
1160 $data["network"] = NETWORK_DIASPORA;
1162 // The Diaspora handle must always be lowercase
1163 $data["addr"] = strtolower($data["addr"]);
1165 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1166 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1167 $data["batch"] = $data["baseurl"] . "/receive/public";
1176 * @brief Check for OStatus contact
1178 * @param array $webfinger Webfinger data
1179 * @param bool $short Short detection mode
1181 * @return array|bool OStatus data or "false" on error or "true" on short mode
1183 private static function ostatus($webfinger, $short = false) {
1186 if (is_array($webfinger["aliases"])) {
1187 foreach ($webfinger["aliases"] as $alias) {
1188 if (strstr($alias, "@") && !strstr(normalise_link($alias), "http://")) {
1189 $data["addr"] = str_replace('acct:', '', $alias);
1194 if (is_string($webfinger["subject"]) && strstr($webfinger["subject"], "@") &&
1195 !strstr(normalise_link($webfinger["subject"]), "http://")) {
1196 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1200 if (is_array($webfinger["links"])) {
1201 foreach ($webfinger["links"] as $link) {
1202 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1203 && ($link["type"] == "text/html")
1204 && ($link["href"] != "")
1206 $data["url"] = $link["href"];
1207 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1208 $data["notify"] = $link["href"];
1209 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1210 $data["poll"] = $link["href"];
1211 } elseif (($link["rel"] == "magic-public-key") && ($link["href"] != "")) {
1212 $pubkey = $link["href"];
1214 if (substr($pubkey, 0, 5) === 'data:') {
1215 if (strstr($pubkey, ',')) {
1216 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1218 $pubkey = substr($pubkey, 5);
1220 } elseif (normalise_link($pubkey) == 'http://') {
1221 $ret = z_fetch_url($pubkey);
1222 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1225 $pubkey = $ret['body'];
1228 $key = explode(".", $pubkey);
1230 if (sizeof($key) >= 3) {
1231 $m = base64url_decode($key[1]);
1232 $e = base64url_decode($key[2]);
1233 $data["pubkey"] = metopem($m, $e);
1239 if (isset($data["notify"]) && isset($data["pubkey"])
1240 && isset($data["poll"])
1241 && isset($data["url"])
1243 $data["network"] = NETWORK_OSTATUS;
1252 // Fetch all additional data from the feed
1253 $ret = z_fetch_url($data["poll"]);
1254 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1257 $feed = $ret['body'];
1258 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1263 if ($feed_data["header"]["author-name"] != "") {
1264 $data["name"] = $feed_data["header"]["author-name"];
1266 if ($feed_data["header"]["author-nick"] != "") {
1267 $data["nick"] = $feed_data["header"]["author-nick"];
1269 if ($feed_data["header"]["author-avatar"] != "") {
1270 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1272 if ($feed_data["header"]["author-id"] != "") {
1273 $data["alias"] = $feed_data["header"]["author-id"];
1275 if ($feed_data["header"]["author-location"] != "") {
1276 $data["location"] = $feed_data["header"]["author-location"];
1278 if ($feed_data["header"]["author-about"] != "") {
1279 $data["about"] = $feed_data["header"]["author-about"];
1281 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1282 // So we take the value that we just fetched, although the other one worked as well
1283 if ($feed_data["header"]["author-link"] != "") {
1284 $data["url"] = $feed_data["header"]["author-link"];
1287 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1288 $data['url'] = $data["alias"];
1289 $data["alias"] = '';
1292 /// @todo Fetch location and "about" from the feed as well
1297 * @brief Fetch data from a pump.io profile page
1299 * @param string $profile_link Link to the profile page
1301 * @return array profile data
1303 private static function pumpioProfileData($profile_link) {
1305 $doc = new DOMDocument();
1306 if (!@$doc->loadHTMLFile($profile_link)) {
1310 $xpath = new DomXPath($doc);
1314 // This is ugly - but pump.io doesn't seem to know a better way for it
1315 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1316 $pos = strpos($data["name"], chr(10));
1318 $data["name"] = trim(substr($data["name"], 0, $pos));
1321 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1323 foreach ($avatar->attributes as $attribute) {
1324 if ($attribute->name == "src") {
1325 $data["photo"] = trim($attribute->value);
1330 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
1331 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
1337 * @brief Check for pump.io contact
1339 * @param array $webfinger Webfinger data
1341 * @return array pump.io data
1343 private static function pumpio($webfinger) {
1346 foreach ($webfinger["links"] as $link) {
1347 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1348 && ($link["type"] == "text/html")
1349 && ($link["href"] != "")
1351 $data["url"] = $link["href"];
1352 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1353 $data["notify"] = $link["href"];
1354 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1355 $data["poll"] = $link["href"];
1356 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1357 $data["dialback"] = $link["href"];
1360 if (isset($data["poll"]) && isset($data["notify"])
1361 && isset($data["dialback"])
1362 && isset($data["url"])
1364 // by now we use these fields only for the network type detection
1365 // So we unset all data that isn't used at the moment
1366 unset($data["dialback"]);
1368 $data["network"] = NETWORK_PUMPIO;
1373 $profile_data = self::pumpioProfileData($data["url"]);
1375 if (!$profile_data) {
1379 $data = array_merge($data, $profile_data);
1385 * @brief Check page for feed link
1387 * @param string $url Page link
1389 * @return string feed link
1391 private static function getFeedLink($url) {
1392 $doc = new DOMDocument();
1394 if (!@$doc->loadHTMLFile($url)) {
1398 $xpath = new DomXPath($doc);
1400 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1401 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1402 if (!is_object($feeds)) {
1406 if ($feeds->length == 0) {
1412 foreach ($feeds as $feed) {
1414 foreach ($feed->attributes as $attribute) {
1415 $attr[$attribute->name] = trim($attribute->value);
1418 if ($feed_url == "") {
1419 $feed_url = $attr["href"];
1427 * @brief Check for feed contact
1429 * @param string $url Profile link
1430 * @param boolean $probe Do a probe if the page contains a feed link
1432 * @return array feed data
1434 private static function feed($url, $probe = true) {
1435 $ret = z_fetch_url($url);
1436 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1439 $feed = $ret['body'];
1440 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1447 $feed_url = self::getFeedLink($url);
1453 return self::feed($feed_url, false);
1456 if ($feed_data["header"]["author-name"] != "") {
1457 $data["name"] = $feed_data["header"]["author-name"];
1460 if ($feed_data["header"]["author-nick"] != "") {
1461 $data["nick"] = $feed_data["header"]["author-nick"];
1464 if ($feed_data["header"]["author-avatar"] != "") {
1465 $data["photo"] = $feed_data["header"]["author-avatar"];
1468 if ($feed_data["header"]["author-id"] != "") {
1469 $data["alias"] = $feed_data["header"]["author-id"];
1472 $data["url"] = $url;
1473 $data["poll"] = $url;
1475 if ($feed_data["header"]["author-link"] != "") {
1476 $data["baseurl"] = $feed_data["header"]["author-link"];
1478 $data["baseurl"] = $data["url"];
1481 $data["network"] = NETWORK_FEED;
1487 * @brief Check for mail contact
1489 * @param string $uri Profile link
1490 * @param integer $uid User ID
1492 * @return array mail data
1494 private static function mail($uri, $uid) {
1496 if (!validate_email($uri)) {
1501 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1503 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1505 if (dbm::is_result($x) && dbm::is_result($r)) {
1506 $mailbox = construct_mailbox_name($r[0]);
1508 openssl_private_decrypt(hex2bin($r[0]['pass']), $password, $x[0]['prvkey']);
1509 $mbox = email_connect($mailbox, $r[0]['user'], $password);
1515 $msgs = email_poll($mbox, $uri);
1516 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1518 if (!count($msgs)) {
1523 $phost = substr($uri, strpos($uri, '@') + 1);
1526 $data["addr"] = $uri;
1527 $data["network"] = NETWORK_MAIL;
1528 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1529 $data["nick"] = $data["name"];
1530 $data["photo"] = avatar_img($uri);
1531 $data["url"] = 'mailto:'.$uri;
1532 $data["notify"] = 'smtp '.random_string();
1533 $data["poll"] = 'email '.random_string();
1535 $x = email_msg_meta($mbox, $msgs[0]);
1536 if (stristr($x[0]->from, $uri)) {
1537 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1538 } elseif (stristr($x[0]->to, $uri)) {
1539 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1542 foreach ($adr as $feadr) {
1543 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1544 &&(strcasecmp($feadr->host, $phost) == 0)
1545 && (strlen($feadr->personal))
1547 $personal = imap_mime_header_decode($feadr->personal);
1549 foreach ($personal as $perspart) {
1550 if ($perspart->charset != "default") {
1551 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1553 $data["name"] .= $perspart->text;
1557 $data["name"] = notags($data["name"]);
1561 if (!empty($mbox)) {
1569 * @brief Mix two paths together to possibly fix missing parts
1571 * @param string $avatar Path to the avatar
1572 * @param string $base Another path that is hopefully complete
1574 * @return string fixed avatar path
1576 public static function fixAvatar($avatar, $base) {
1577 $base_parts = parse_url($base);
1579 // Remove all parts that could create a problem
1580 unset($base_parts['path']);
1581 unset($base_parts['query']);
1582 unset($base_parts['fragment']);
1584 $avatar_parts = parse_url($avatar);
1587 $parts = array_merge($base_parts, $avatar_parts);
1589 // And put them together again
1590 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1591 $host = isset($parts['host']) ? $parts['host'] : '';
1592 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1593 $path = isset($parts['path']) ? $parts['path'] : '';
1594 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1595 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1597 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1599 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);