3 * @file src/Network/Probe.php
5 namespace Friendica\Network;
8 * @file src/Network/Probe.php
9 * @brief Functions for probing URL
13 use Friendica\Core\System;
14 use Friendica\Core\Cache;
15 use Friendica\Core\Config;
16 use Friendica\Database\DBM;
17 use Friendica\Object\Profile;
18 use Friendica\Util\XML;
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)
45 $fields = array("name", "nick", "guid", "url", "addr", "alias",
46 "photo", "community", "keywords", "location", "about",
47 "batch", "notify", "poll", "request", "confirm", "poco",
48 "priority", "network", "pubkey", "baseurl");
51 foreach ($fields as $field) {
52 if (isset($data[$field])) {
53 $newdata[$field] = $data[$field];
55 $newdata[$field] = "";
59 // We don't use the "priority" field anymore and replace it with a dummy.
60 $newdata["priority"] = 0;
66 * @brief Check if the hostname belongs to the own server
68 * @param string $host The hostname that is to be checked
70 * @return bool Does the testes hostname belongs to the own server?
72 private static function ownHost($host)
74 $own_host = get_app()->get_hostname();
76 $parts = parse_url($host);
78 if (!isset($parts['scheme'])) {
79 $parts = parse_url('http://'.$host);
82 if (!isset($parts['host'])) {
85 return $parts['host'] == $own_host;
89 * @brief Probes for webfinger path via "host-meta"
91 * @param string $host The host part of an url
93 * @return array with template and type of the webfinger template for JSON or XML
95 private static function hostMeta($host)
97 // Reset the static variable
100 $ssl_url = "https://".$host."/.well-known/host-meta";
101 $url = "http://".$host."/.well-known/host-meta";
103 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
106 logger("Probing for ".$host, LOGGER_DEBUG);
108 $ret = z_fetch_url($ssl_url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
109 if ($ret['success']) {
111 $xrd = parse_xml_string($xml, false);
112 $host_url = 'https://'.$host;
115 if (!is_object($xrd)) {
116 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
117 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
118 logger("Probing timeout for ".$url, LOGGER_DEBUG);
122 $xrd = parse_xml_string($xml, false);
123 $host_url = 'http://'.$host;
125 if (!is_object($xrd)) {
126 logger("No xrd object found for ".$host, LOGGER_DEBUG);
130 $links = XML::elementToArray($xrd);
131 if (!isset($links["xrd"]["link"])) {
132 logger("No xrd data found for ".$host, LOGGER_DEBUG);
137 // The following webfinger path is defined in RFC 7033 https://tools.ietf.org/html/rfc7033
138 // Problem is that Hubzilla currently doesn't provide all data in the JSON webfinger
139 // compared to the XML webfinger. So this is commented out by now.
140 // $lrdd = array("application/jrd+json" => $host_url.'/.well-known/webfinger?resource={uri}');
142 foreach ($links["xrd"]["link"] as $value => $link) {
143 if (!empty($link["@attributes"])) {
144 $attributes = $link["@attributes"];
145 } elseif ($value == "@attributes") {
151 if (($attributes["rel"] == "lrdd") && !empty($attributes["template"])) {
152 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
154 $lrdd[$type] = $attributes["template"];
158 self::$baseurl = "http://".$host;
160 logger("Probing successful for ".$host, LOGGER_DEBUG);
166 * @brief Perform Webfinger lookup and return DFRN data
168 * Given an email style address, perform webfinger lookup and
169 * return the resulting DFRN profile URL, or if no DFRN profile URL
170 * is located, returns an OStatus subscription template (prefixed
171 * with the string 'stat:' to identify it as on OStatus template).
172 * If this isn't an email style address just return $webbie.
173 * Return an empty string if email-style addresses but webfinger fails,
174 * or if the resultant personal XRD doesn't contain a supported
175 * subscription/friend-request attribute.
177 * amended 7/9/2011 to return an hcard which could save potentially loading
178 * a lengthy content page to scrape dfrn attributes
180 * @param string $webbie Address that should be probed
181 * @param string $hcard_url Link to the hcard - is returned by reference
183 * @return string profile link
185 public static function webfingerDfrn($webbie, &$hcard_url)
189 $links = self::lrdd($webbie);
190 logger('webfingerDfrn: '.$webbie.':'.print_r($links, true), LOGGER_DATA);
192 foreach ($links as $link) {
193 if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
194 $profile_link = $link['@attributes']['href'];
196 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) && ($profile_link == "")) {
197 $profile_link = 'stat:'.$link['@attributes']['template'];
199 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
200 $hcard_url = $link['@attributes']['href'];
204 return $profile_link;
208 * @brief Check an URI for LRDD data
210 * this is a replacement for the "lrdd" function in include/network.php.
211 * It isn't used in this class and has some redundancies in the code.
212 * When time comes we can check the existing calls for "lrdd" if we can rework them.
214 * @param string $uri Address that should be probed
216 * @return array uri data
218 public static function lrdd($uri)
220 $lrdd = self::hostMeta($uri);
223 if (is_bool($lrdd)) {
228 $parts = @parse_url($uri);
233 $host = $parts["host"];
234 if (!empty($parts["port"])) {
235 $host .= ':'.$parts["port"];
238 $path_parts = explode("/", trim($parts["path"], "/"));
240 $nick = array_pop($path_parts);
243 $lrdd = self::hostMeta($host);
244 $host .= "/".array_shift($path_parts);
245 } while (!$lrdd && (sizeof($path_parts) > 0));
249 logger("No lrdd data found for ".$uri, LOGGER_DEBUG);
253 foreach ($lrdd as $type => $template) {
258 $path = str_replace('{uri}', urlencode($uri), $template);
259 $webfinger = self::webfinger($path, $type);
261 if (!$webfinger && (strstr($uri, "@"))) {
262 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
263 $webfinger = self::webfinger($path, $type);
266 // Special treatment for Mastodon
267 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
268 // But the webfinger for this format fails.
269 if (!$webfinger && !empty($nick)) {
270 // Mastodon uses a "@" as prefix for usernames in their url format
271 $nick = ltrim($nick, '@');
273 $addr = $nick."@".$host;
275 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
276 $webfinger = self::webfinger($path, $type);
280 if (!is_array($webfinger["links"])) {
281 logger("No webfinger links found for ".$uri, LOGGER_DEBUG);
287 foreach ($webfinger["links"] as $link) {
288 $data[] = array("@attributes" => $link);
291 if (is_array($webfinger["aliases"])) {
292 foreach ($webfinger["aliases"] as $alias) {
293 $data[] = array("@attributes" =>
294 array("rel" => "alias",
303 * @brief Fetch information (protocol endpoints and user information) about a given uri
305 * @param string $uri Address that should be probed
306 * @param string $network Test for this specific network
307 * @param integer $uid User ID for the probe (only used for mails)
308 * @param boolean $cache Use cached values?
310 * @return array uri data
312 public static function uri($uri, $network = "", $uid = -1, $cache = true)
315 $result = Cache::get("Probe::uri:".$network.":".$uri);
316 if (!is_null($result)) {
325 $data = self::detect($uri, $network, $uid);
327 if (!isset($data["url"])) {
331 if ($data["photo"] != "") {
332 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
334 $data["photo"] = System::baseUrl().'/images/person-175.jpg';
337 if (empty($data["name"])) {
338 if (!empty($data["nick"])) {
339 $data["name"] = $data["nick"];
342 if ($data["name"] == "") {
343 $data["name"] = $data["url"];
347 if (empty($data["nick"])) {
348 $data["nick"] = strtolower($data["name"]);
350 if (strpos($data['nick'], ' ')) {
351 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
355 if (self::$baseurl != "") {
356 $data["baseurl"] = self::$baseurl;
359 if (!isset($data["network"])) {
360 $data["network"] = NETWORK_PHANTOM;
363 $data = self::rearrangeData($data);
365 // Only store into the cache if the value seems to be valid
366 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
367 Cache::set("Probe::uri:".$network.":".$uri, $data, CACHE_DAY);
369 /// @todo temporary fix - we need a real contact update function that updates only changing fields
370 /// The biggest problem is the avatar picture that could have a reduced image size.
371 /// It should only be updated if the existing picture isn't existing anymore.
372 /// We only update the contact when it is no probing for a specific network.
373 if (($data['network'] != NETWORK_FEED)
381 $fields = array('name' => $data['name'],
382 'nick' => $data['nick'],
383 'url' => $data['url'],
384 'addr' => $data['addr'],
385 'photo' => $data['photo'],
386 'keywords' => $data['keywords'],
387 'location' => $data['location'],
388 'about' => $data['about'],
389 'notify' => $data['notify'],
390 'network' => $data['network'],
391 'server_url' => $data['baseurl']);
393 $fieldnames = array();
395 foreach ($fields as $key => $val) {
397 unset($fields[$key]);
399 $fieldnames[] = $key;
403 $fields['updated'] = DBM::date();
405 $condition = array('nurl' => normalise_link($data["url"]));
407 $old_fields = dba::select('gcontact', $fieldnames, $condition, array('limit' => 1));
409 dba::update('gcontact', $fields, $condition, $old_fields);
411 $fields = array('name' => $data['name'],
412 'nick' => $data['nick'],
413 'url' => $data['url'],
414 'addr' => $data['addr'],
415 'alias' => $data['alias'],
416 'keywords' => $data['keywords'],
417 'location' => $data['location'],
418 'about' => $data['about'],
419 'batch' => $data['batch'],
420 'notify' => $data['notify'],
421 'poll' => $data['poll'],
422 'request' => $data['request'],
423 'confirm' => $data['confirm'],
424 'poco' => $data['poco'],
425 'network' => $data['network'],
426 'success_update' => DBM::date());
428 $fieldnames = array();
430 foreach ($fields as $key => $val) {
432 unset($fields[$key]);
434 $fieldnames[] = $key;
438 $condition = array('nurl' => normalise_link($data["url"]), 'self' => false, 'uid' => 0);
440 $old_fields = dba::select('contact', $fieldnames, $condition, array('limit' => 1));
442 dba::update('contact', $fields, $condition, $old_fields);
450 * @brief Switch the scheme of an url between http and https
452 * @param string $url URL
454 * @return string switched URL
456 private static function switchScheme($url)
458 $parts = parse_url($url);
460 if (!isset($parts['scheme'])) {
464 if ($parts['scheme'] == 'http') {
465 $url = str_replace('http://', 'https://', $url);
466 } elseif ($parts['scheme'] == 'https') {
467 $url = str_replace('https://', 'http://', $url);
474 * @brief Checks if a profile url should be OStatus but only provides partial information
476 * @param array $webfinger Webfinger data
477 * @param string $lrdd Path template for webfinger request
478 * @param string $type type
480 * @return array fixed webfinger data
482 private static function fixOStatus($webfinger, $lrdd, $type)
484 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
491 foreach ($webfinger['links'] as $link) {
492 if ($link['rel'] == NAMESPACE_OSTATUSSUB) {
495 if ($link['rel'] == 'magic-public-key') {
500 if (!$is_ostatus || $has_key) {
504 $url = self::switchScheme($webfinger['subject']);
505 $path = str_replace('{uri}', urlencode($url), $lrdd);
506 $webfinger2 = self::webfinger($path, $type);
508 // Is the new webfinger detectable as OStatus?
509 if (self::ostatus($webfinger2, true)) {
510 $webfinger = $webfinger2;
517 * @brief Fetch information (protocol endpoints and user information) about a given uri
519 * This function is only called by the "uri" function that adds caching and rearranging of data.
521 * @param string $uri Address that should be probed
522 * @param string $network Test for this specific network
523 * @param integer $uid User ID for the probe (only used for mails)
525 * @return array uri data
527 private static function detect($uri, $network, $uid)
529 $parts = parse_url($uri);
531 if (!empty($parts["scheme"]) && !empty($parts["host"]) && !empty($parts["path"])) {
532 $host = $parts["host"];
533 if (!empty($parts["port"])) {
534 $host .= ':'.$parts["port"];
537 if ($host == 'twitter.com') {
538 return array("network" => NETWORK_TWITTER);
540 $lrdd = self::hostMeta($host);
542 if (is_bool($lrdd)) {
546 $path_parts = explode("/", trim($parts["path"], "/"));
548 while (!$lrdd && (sizeof($path_parts) > 1)) {
549 $host .= "/".array_shift($path_parts);
550 $lrdd = self::hostMeta($host);
553 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
554 return self::feed($uri);
556 $nick = array_pop($path_parts);
558 // Mastodon uses a "@" as prefix for usernames in their url format
559 $nick = ltrim($nick, '@');
561 $addr = $nick."@".$host;
562 } elseif (strstr($uri, '@')) {
563 // If the URI starts with "mailto:" then jump directly to the mail detection
564 if (strpos($uri, 'mailto:') !== false) {
565 $uri = str_replace('mailto:', '', $uri);
566 return self::mail($uri, $uid);
569 if ($network == NETWORK_MAIL) {
570 return self::mail($uri, $uid);
572 // Remove "acct:" from the URI
573 $uri = str_replace('acct:', '', $uri);
575 $host = substr($uri, strpos($uri, '@') + 1);
576 $nick = substr($uri, 0, strpos($uri, '@'));
578 if (strpos($uri, '@twitter.com')) {
579 return array("network" => NETWORK_TWITTER);
581 $lrdd = self::hostMeta($host);
583 if (is_bool($lrdd)) {
588 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
589 return self::mail($uri, $uid);
593 logger("Uri ".$uri." was not detectable", LOGGER_DEBUG);
599 /// @todo Do we need the prefix "acct:" or "acct://"?
601 foreach ($lrdd as $type => $template) {
606 // At first try it with the given uri
607 $path = str_replace('{uri}', urlencode($uri), $template);
608 $webfinger = self::webfinger($path, $type);
610 // Fix possible problems with GNU Social probing to wrong scheme
611 $webfinger = self::fixOStatus($webfinger, $template, $type);
613 // We cannot be sure that the detected address was correct, so we don't use the values
614 if ($webfinger && ($uri != $addr)) {
619 // Try webfinger with the address (user@domain.tld)
621 $path = str_replace('{uri}', urlencode($addr), $template);
622 $webfinger = self::webfinger($path, $type);
625 // Mastodon needs to have it with "acct:"
627 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
628 $webfinger = self::webfinger($path, $type);
633 return self::feed($uri);
638 logger("Probing ".$uri, LOGGER_DEBUG);
640 if (in_array($network, array("", NETWORK_DFRN))) {
641 $result = self::dfrn($webfinger);
643 if ((!$result && ($network == "")) || ($network == NETWORK_DIASPORA)) {
644 $result = self::diaspora($webfinger);
646 if ((!$result && ($network == "")) || ($network == NETWORK_OSTATUS)) {
647 $result = self::ostatus($webfinger);
649 if ((!$result && ($network == "")) || ($network == NETWORK_PUMPIO)) {
650 $result = self::pumpio($webfinger);
652 if ((!$result && ($network == "")) || ($network == NETWORK_FEED)) {
653 $result = self::feed($uri);
655 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
656 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
657 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
658 $result["nick"] = $nick;
661 if (empty($result["addr"]) && ($addr != "")) {
662 $result["addr"] = $addr;
666 logger($uri." is ".$result["network"], LOGGER_DEBUG);
668 if (empty($result["baseurl"])) {
669 $pos = strpos($result["url"], $host);
671 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
679 * @brief Perform a webfinger request.
681 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
683 * @param string $url Address that should be probed
684 * @param string $type type
686 * @return array webfinger data
688 private static function webfinger($url, $type)
690 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
693 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => $type));
694 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
697 $data = $ret['body'];
699 $webfinger = json_decode($data, true);
700 if (is_array($webfinger)) {
701 if (!isset($webfinger["links"])) {
702 logger("No json webfinger links for ".$url, LOGGER_DEBUG);
708 // If it is not JSON, maybe it is XML
709 $xrd = parse_xml_string($data, false);
710 if (!is_object($xrd)) {
711 logger("No webfinger data retrievable for ".$url, LOGGER_DEBUG);
715 $xrd_arr = XML::elementToArray($xrd);
716 if (!isset($xrd_arr["xrd"]["link"])) {
717 logger("No XML webfinger links for ".$url, LOGGER_DEBUG);
721 $webfinger = array();
723 if (!empty($xrd_arr["xrd"]["subject"])) {
724 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
727 if (!empty($xrd_arr["xrd"]["alias"])) {
728 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
731 $webfinger["links"] = array();
733 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
734 if (!empty($data["@attributes"])) {
735 $attributes = $data["@attributes"];
736 } elseif ($value == "@attributes") {
742 $webfinger["links"][] = $attributes;
748 * @brief Poll the Friendica specific noscrape page.
750 * "noscrape" is a faster alternative to fetch the data from the hcard.
751 * This functionality was originally created for the directory.
753 * @param string $noscrape_url Link to the noscrape page
754 * @param array $data The already fetched data
756 * @return array noscrape data
758 private static function pollNoscrape($noscrape_url, $data)
760 $ret = z_fetch_url($noscrape_url);
761 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
764 $content = $ret['body'];
766 logger("Empty body for ".$noscrape_url, LOGGER_DEBUG);
770 $json = json_decode($content, true);
771 if (!is_array($json)) {
772 logger("No json data for ".$noscrape_url, LOGGER_DEBUG);
776 if (!empty($json["fn"])) {
777 $data["name"] = $json["fn"];
780 if (!empty($json["addr"])) {
781 $data["addr"] = $json["addr"];
784 if (!empty($json["nick"])) {
785 $data["nick"] = $json["nick"];
788 if (!empty($json["guid"])) {
789 $data["guid"] = $json["guid"];
792 if (!empty($json["comm"])) {
793 $data["community"] = $json["comm"];
796 if (!empty($json["tags"])) {
797 $keywords = implode(" ", $json["tags"]);
798 if ($keywords != "") {
799 $data["keywords"] = $keywords;
803 $location = Profile::formatLocation($json);
805 $data["location"] = $location;
808 if (!empty($json["about"])) {
809 $data["about"] = $json["about"];
812 if (!empty($json["key"])) {
813 $data["pubkey"] = $json["key"];
816 if (!empty($json["photo"])) {
817 $data["photo"] = $json["photo"];
820 if (!empty($json["dfrn-request"])) {
821 $data["request"] = $json["dfrn-request"];
824 if (!empty($json["dfrn-confirm"])) {
825 $data["confirm"] = $json["dfrn-confirm"];
828 if (!empty($json["dfrn-notify"])) {
829 $data["notify"] = $json["dfrn-notify"];
832 if (!empty($json["dfrn-poll"])) {
833 $data["poll"] = $json["dfrn-poll"];
840 * @brief Check for valid DFRN data
842 * @param array $data DFRN data
844 * @return int Number of errors
846 public static function validDfrn($data)
849 if (!isset($data['key'])) {
852 if (!isset($data['dfrn-request'])) {
855 if (!isset($data['dfrn-confirm'])) {
858 if (!isset($data['dfrn-notify'])) {
861 if (!isset($data['dfrn-poll'])) {
868 * @brief Fetch data from a DFRN profile page and via "noscrape"
870 * @param string $profile_link Link to the profile page
872 * @return array profile data
874 public static function profile($profile_link)
878 logger("Check profile ".$profile_link, LOGGER_DEBUG);
880 // Fetch data via noscrape - this is faster
881 $noscrape_url = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile_link);
882 $data = self::pollNoscrape($noscrape_url, $data);
884 if (!isset($data["notify"])
885 || !isset($data["confirm"])
886 || !isset($data["request"])
887 || !isset($data["poll"])
888 || !isset($data["poco"])
889 || !isset($data["name"])
890 || !isset($data["photo"])
892 $data = self::pollHcard($profile_link, $data, true);
895 $prof_data = array();
896 $prof_data["addr"] = $data["addr"];
897 $prof_data["nick"] = $data["nick"];
898 $prof_data["dfrn-request"] = $data["request"];
899 $prof_data["dfrn-confirm"] = $data["confirm"];
900 $prof_data["dfrn-notify"] = $data["notify"];
901 $prof_data["dfrn-poll"] = $data["poll"];
902 $prof_data["dfrn-poco"] = $data["poco"];
903 $prof_data["photo"] = $data["photo"];
904 $prof_data["fn"] = $data["name"];
905 $prof_data["key"] = $data["pubkey"];
907 logger("Result for profile ".$profile_link.": ".print_r($prof_data, true), LOGGER_DEBUG);
913 * @brief Check for DFRN contact
915 * @param array $webfinger Webfinger data
917 * @return array DFRN data
919 private static function dfrn($webfinger)
923 foreach ($webfinger["links"] as $link) {
924 if (($link["rel"] == NAMESPACE_DFRN) && ($link["href"] != "")) {
925 $data["network"] = NETWORK_DFRN;
926 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
927 $data["poll"] = $link["href"];
928 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
929 $data["url"] = $link["href"];
930 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
931 $hcard_url = $link["href"];
932 } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
933 $data["poco"] = $link["href"];
934 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && ($link["href"] != "")) {
935 $data["photo"] = $link["href"];
936 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
937 $data["baseurl"] = trim($link["href"], '/');
938 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
939 $data["guid"] = $link["href"];
940 } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
941 $data["pubkey"] = base64_decode($link["href"]);
943 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
944 if (strstr($data["pubkey"], 'RSA ')) {
945 $data["pubkey"] = rsatopem($data["pubkey"]);
950 if (is_array($webfinger["aliases"])) {
951 foreach ($webfinger["aliases"] as $alias) {
952 if (normalise_link($alias) != normalise_link($data["url"]) && ! strstr($alias, "@")) {
953 $data["alias"] = $alias;
954 } elseif (substr($alias, 0, 5) == 'acct:') {
955 $data["addr"] = substr($alias, 5);
960 if (!isset($data["network"]) || ($hcard_url == "")) {
964 // Fetch data via noscrape - this is faster
965 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
966 $data = self::pollNoscrape($noscrape_url, $data);
968 if (isset($data["notify"])
969 && isset($data["confirm"])
970 && isset($data["request"])
971 && isset($data["poll"])
972 && isset($data["name"])
973 && isset($data["photo"])
978 $data = self::pollHcard($hcard_url, $data, true);
984 * @brief Poll the hcard page (Diaspora and Friendica specific)
986 * @param string $hcard_url Link to the hcard page
987 * @param array $data The already fetched data
988 * @param boolean $dfrn Poll DFRN specific data
990 * @return array hcard data
992 private static function pollHcard($hcard_url, $data, $dfrn = false)
994 $ret = z_fetch_url($hcard_url);
995 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
998 $content = $ret['body'];
1003 $doc = new DOMDocument();
1004 if (!@$doc->loadHTML($content)) {
1008 $xpath = new DomXPath($doc);
1010 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1011 if (!is_object($vcards)) {
1015 if ($vcards->length > 0) {
1016 $vcard = $vcards->item(0);
1018 // We have to discard the guid from the hcard in favour of the guid from lrdd
1019 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1020 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1021 if (($search->length > 0) && ($data["guid"] == "")) {
1022 $data["guid"] = $search->item(0)->nodeValue;
1025 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1026 if ($search->length > 0) {
1027 $data["nick"] = $search->item(0)->nodeValue;
1030 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1031 if ($search->length > 0) {
1032 $data["name"] = $search->item(0)->nodeValue;
1035 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1036 if ($search->length > 0) {
1037 $data["searchable"] = $search->item(0)->nodeValue;
1040 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1041 if ($search->length > 0) {
1042 $data["pubkey"] = $search->item(0)->nodeValue;
1043 if (strstr($data["pubkey"], 'RSA ')) {
1044 $data["pubkey"] = rsatopem($data["pubkey"]);
1048 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1049 if ($search->length > 0) {
1050 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1055 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1056 foreach ($photos as $photo) {
1058 foreach ($photo->attributes as $attribute) {
1059 $attr[$attribute->name] = trim($attribute->value);
1062 if (isset($attr["src"]) && isset($attr["width"])) {
1063 $avatar[$attr["width"]] = $attr["src"];
1066 // We don't have a width. So we just take everything that we got.
1067 // This is a Hubzilla workaround which doesn't send a width.
1068 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1069 $avatar[] = $attr["src"];
1073 if (sizeof($avatar)) {
1075 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1079 // Poll DFRN specific data
1080 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1081 if ($search->length > 0) {
1082 foreach ($search as $link) {
1083 //$data["request"] = $search->item(0)->nodeValue;
1085 foreach ($link->attributes as $attribute) {
1086 $attr[$attribute->name] = trim($attribute->value);
1089 $data[substr($attr["rel"], 5)] = $attr["href"];
1093 // Older Friendica versions had used the "uid" field differently than newer versions
1094 if ($data["nick"] == $data["guid"]) {
1095 unset($data["guid"]);
1104 * @brief Check for Diaspora contact
1106 * @param array $webfinger Webfinger data
1108 * @return array Diaspora data
1110 private static function diaspora($webfinger)
1114 foreach ($webfinger["links"] as $link) {
1115 if (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
1116 $hcard_url = $link["href"];
1117 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
1118 $data["baseurl"] = trim($link["href"], '/');
1119 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
1120 $data["guid"] = $link["href"];
1121 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
1122 $data["url"] = $link["href"];
1123 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1124 $data["poll"] = $link["href"];
1125 } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
1126 $data["poco"] = $link["href"];
1127 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1128 $data["notify"] = $link["href"];
1129 } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
1130 $data["pubkey"] = base64_decode($link["href"]);
1132 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1133 if (strstr($data["pubkey"], 'RSA ')) {
1134 $data["pubkey"] = rsatopem($data["pubkey"]);
1139 if (!isset($data["url"]) || ($hcard_url == "")) {
1143 if (is_array($webfinger["aliases"])) {
1144 foreach ($webfinger["aliases"] as $alias) {
1145 if (normalise_link($alias) != normalise_link($data["url"]) && ! strstr($alias, "@")) {
1146 $data["alias"] = $alias;
1147 } elseif (substr($alias, 0, 5) == 'acct:') {
1148 $data["addr"] = substr($alias, 5);
1153 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1154 $data["addr"] = substr($webfinger["subject"], 5);
1157 // Fetch further information from the hcard
1158 $data = self::pollHcard($hcard_url, $data);
1164 if (isset($data["url"])
1165 && isset($data["guid"])
1166 && isset($data["baseurl"])
1167 && isset($data["pubkey"])
1168 && ($hcard_url != "")
1170 $data["network"] = NETWORK_DIASPORA;
1172 // The Diaspora handle must always be lowercase
1173 $data["addr"] = strtolower($data["addr"]);
1175 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1176 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1177 $data["batch"] = $data["baseurl"] . "/receive/public";
1186 * @brief Check for OStatus contact
1188 * @param array $webfinger Webfinger data
1189 * @param bool $short Short detection mode
1191 * @return array|bool OStatus data or "false" on error or "true" on short mode
1193 private static function ostatus($webfinger, $short = false)
1197 if (is_array($webfinger["aliases"])) {
1198 foreach ($webfinger["aliases"] as $alias) {
1199 if (strstr($alias, "@") && !strstr(normalise_link($alias), "http://")) {
1200 $data["addr"] = str_replace('acct:', '', $alias);
1205 if (is_string($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1206 && !strstr(normalise_link($webfinger["subject"]), "http://")
1208 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1212 if (is_array($webfinger["links"])) {
1213 foreach ($webfinger["links"] as $link) {
1214 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1215 && ($link["type"] == "text/html")
1216 && ($link["href"] != "")
1218 $data["url"] = $link["href"];
1219 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1220 $data["notify"] = $link["href"];
1221 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1222 $data["poll"] = $link["href"];
1223 } elseif (($link["rel"] == "magic-public-key") && ($link["href"] != "")) {
1224 $pubkey = $link["href"];
1226 if (substr($pubkey, 0, 5) === 'data:') {
1227 if (strstr($pubkey, ',')) {
1228 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1230 $pubkey = substr($pubkey, 5);
1232 } elseif (normalise_link($pubkey) == 'http://') {
1233 $ret = z_fetch_url($pubkey);
1234 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1237 $pubkey = $ret['body'];
1240 $key = explode(".", $pubkey);
1242 if (sizeof($key) >= 3) {
1243 $m = base64url_decode($key[1]);
1244 $e = base64url_decode($key[2]);
1245 $data["pubkey"] = metopem($m, $e);
1251 if (isset($data["notify"]) && isset($data["pubkey"])
1252 && isset($data["poll"])
1253 && isset($data["url"])
1255 $data["network"] = NETWORK_OSTATUS;
1264 // Fetch all additional data from the feed
1265 $ret = z_fetch_url($data["poll"]);
1266 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1269 $feed = $ret['body'];
1270 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1275 if ($feed_data["header"]["author-name"] != "") {
1276 $data["name"] = $feed_data["header"]["author-name"];
1278 if ($feed_data["header"]["author-nick"] != "") {
1279 $data["nick"] = $feed_data["header"]["author-nick"];
1281 if ($feed_data["header"]["author-avatar"] != "") {
1282 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1284 if ($feed_data["header"]["author-id"] != "") {
1285 $data["alias"] = $feed_data["header"]["author-id"];
1287 if ($feed_data["header"]["author-location"] != "") {
1288 $data["location"] = $feed_data["header"]["author-location"];
1290 if ($feed_data["header"]["author-about"] != "") {
1291 $data["about"] = $feed_data["header"]["author-about"];
1293 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1294 // So we take the value that we just fetched, although the other one worked as well
1295 if ($feed_data["header"]["author-link"] != "") {
1296 $data["url"] = $feed_data["header"]["author-link"];
1299 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1300 $data['url'] = $data["alias"];
1301 $data["alias"] = '';
1304 /// @todo Fetch location and "about" from the feed as well
1309 * @brief Fetch data from a pump.io profile page
1311 * @param string $profile_link Link to the profile page
1313 * @return array profile data
1315 private static function pumpioProfileData($profile_link)
1317 $doc = new DOMDocument();
1318 if (!@$doc->loadHTMLFile($profile_link)) {
1322 $xpath = new DomXPath($doc);
1326 // This is ugly - but pump.io doesn't seem to know a better way for it
1327 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1328 $pos = strpos($data["name"], chr(10));
1330 $data["name"] = trim(substr($data["name"], 0, $pos));
1333 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1335 foreach ($avatar->attributes as $attribute) {
1336 if ($attribute->name == "src") {
1337 $data["photo"] = trim($attribute->value);
1342 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
1343 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
1349 * @brief Check for pump.io contact
1351 * @param array $webfinger Webfinger data
1353 * @return array pump.io data
1355 private static function pumpio($webfinger)
1358 foreach ($webfinger["links"] as $link) {
1359 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1360 && ($link["type"] == "text/html")
1361 && ($link["href"] != "")
1363 $data["url"] = $link["href"];
1364 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1365 $data["notify"] = $link["href"];
1366 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1367 $data["poll"] = $link["href"];
1368 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1369 $data["dialback"] = $link["href"];
1372 if (isset($data["poll"]) && isset($data["notify"])
1373 && isset($data["dialback"])
1374 && isset($data["url"])
1376 // by now we use these fields only for the network type detection
1377 // So we unset all data that isn't used at the moment
1378 unset($data["dialback"]);
1380 $data["network"] = NETWORK_PUMPIO;
1385 $profile_data = self::pumpioProfileData($data["url"]);
1387 if (!$profile_data) {
1391 $data = array_merge($data, $profile_data);
1397 * @brief Check page for feed link
1399 * @param string $url Page link
1401 * @return string feed link
1403 private static function getFeedLink($url)
1405 $doc = new DOMDocument();
1407 if (!@$doc->loadHTMLFile($url)) {
1411 $xpath = new DomXPath($doc);
1413 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1414 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1415 if (!is_object($feeds)) {
1419 if ($feeds->length == 0) {
1425 foreach ($feeds as $feed) {
1427 foreach ($feed->attributes as $attribute) {
1428 $attr[$attribute->name] = trim($attribute->value);
1431 if ($feed_url == "") {
1432 $feed_url = $attr["href"];
1440 * @brief Check for feed contact
1442 * @param string $url Profile link
1443 * @param boolean $probe Do a probe if the page contains a feed link
1445 * @return array feed data
1447 private static function feed($url, $probe = true)
1449 $ret = z_fetch_url($url);
1450 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1453 $feed = $ret['body'];
1454 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1461 $feed_url = self::getFeedLink($url);
1467 return self::feed($feed_url, false);
1470 if ($feed_data["header"]["author-name"] != "") {
1471 $data["name"] = $feed_data["header"]["author-name"];
1474 if ($feed_data["header"]["author-nick"] != "") {
1475 $data["nick"] = $feed_data["header"]["author-nick"];
1478 if ($feed_data["header"]["author-avatar"] != "") {
1479 $data["photo"] = $feed_data["header"]["author-avatar"];
1482 if ($feed_data["header"]["author-id"] != "") {
1483 $data["alias"] = $feed_data["header"]["author-id"];
1486 $data["url"] = $url;
1487 $data["poll"] = $url;
1489 if ($feed_data["header"]["author-link"] != "") {
1490 $data["baseurl"] = $feed_data["header"]["author-link"];
1492 $data["baseurl"] = $data["url"];
1495 $data["network"] = NETWORK_FEED;
1501 * @brief Check for mail contact
1503 * @param string $uri Profile link
1504 * @param integer $uid User ID
1506 * @return array mail data
1508 private static function mail($uri, $uid)
1510 if (!validate_email($uri)) {
1515 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1517 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1519 if (DBM::is_result($x) && DBM::is_result($r)) {
1520 $mailbox = construct_mailbox_name($r[0]);
1522 openssl_private_decrypt(hex2bin($r[0]['pass']), $password, $x[0]['prvkey']);
1523 $mbox = email_connect($mailbox, $r[0]['user'], $password);
1529 $msgs = email_poll($mbox, $uri);
1530 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1532 if (!count($msgs)) {
1537 $phost = substr($uri, strpos($uri, '@') + 1);
1540 $data["addr"] = $uri;
1541 $data["network"] = NETWORK_MAIL;
1542 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1543 $data["nick"] = $data["name"];
1544 $data["photo"] = avatar_img($uri);
1545 $data["url"] = 'mailto:'.$uri;
1546 $data["notify"] = 'smtp '.random_string();
1547 $data["poll"] = 'email '.random_string();
1549 $x = email_msg_meta($mbox, $msgs[0]);
1550 if (stristr($x[0]->from, $uri)) {
1551 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1552 } elseif (stristr($x[0]->to, $uri)) {
1553 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1556 foreach ($adr as $feadr) {
1557 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1558 &&(strcasecmp($feadr->host, $phost) == 0)
1559 && (strlen($feadr->personal))
1561 $personal = imap_mime_header_decode($feadr->personal);
1563 foreach ($personal as $perspart) {
1564 if ($perspart->charset != "default") {
1565 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1567 $data["name"] .= $perspart->text;
1571 $data["name"] = notags($data["name"]);
1575 if (!empty($mbox)) {
1583 * @brief Mix two paths together to possibly fix missing parts
1585 * @param string $avatar Path to the avatar
1586 * @param string $base Another path that is hopefully complete
1588 * @return string fixed avatar path
1590 public static function fixAvatar($avatar, $base)
1592 $base_parts = parse_url($base);
1594 // Remove all parts that could create a problem
1595 unset($base_parts['path']);
1596 unset($base_parts['query']);
1597 unset($base_parts['fragment']);
1599 $avatar_parts = parse_url($avatar);
1602 $parts = array_merge($base_parts, $avatar_parts);
1604 // And put them together again
1605 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1606 $host = isset($parts['host']) ? $parts['host'] : '';
1607 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1608 $path = isset($parts['path']) ? $parts['path'] : '';
1609 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1610 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1612 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1614 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);