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;
23 require_once 'include/feed.php';
24 require_once 'include/email.php';
25 require_once 'include/network.php';
28 * @brief This class contain functions for probing URL
33 private static $baseurl;
36 * @brief Rearrange the array so that it always has the same order
38 * @param array $data Unordered data
40 * @return array Ordered data
42 private static function rearrangeData($data) {
43 $fields = array("name", "nick", "guid", "url", "addr", "alias",
44 "photo", "community", "keywords", "location", "about",
45 "batch", "notify", "poll", "request", "confirm", "poco",
46 "priority", "network", "pubkey", "baseurl");
49 foreach ($fields as $field) {
50 if (isset($data[$field])) {
51 $newdata[$field] = $data[$field];
53 $newdata[$field] = "";
57 // We don't use the "priority" field anymore and replace it with a dummy.
58 $newdata["priority"] = 0;
64 * @brief Check if the hostname belongs to the own server
66 * @param string $host The hostname that is to be checked
68 * @return bool Does the testes hostname belongs to the own server?
70 private static function ownHost($host) {
71 $own_host = get_app()->get_hostname();
73 $parts = parse_url($host);
75 if (!isset($parts['scheme'])) {
76 $parts = parse_url('http://'.$host);
79 if (!isset($parts['host'])) {
82 return $parts['host'] == $own_host;
86 * @brief Probes for XRD data
88 * @param string $host The host part of an url
91 * 'lrdd' => Link to LRDD endpoint
92 * 'lrdd-xml' => Link to LRDD endpoint in XML format
93 * 'lrdd-json' => Link to LRDD endpoint in JSON format
95 private static function xrd($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);
114 if (!is_object($xrd)) {
115 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
116 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
117 logger("Probing timeout for ".$url, LOGGER_DEBUG);
121 $xrd = parse_xml_string($xml, false);
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);
136 foreach ($links["xrd"]["link"] as $value => $link) {
137 if (!empty($link["@attributes"])) {
138 $attributes = $link["@attributes"];
139 } elseif ($value == "@attributes") {
145 if (($attributes["rel"] == "lrdd")
146 && ($attributes["type"] == "application/xrd+xml")
148 $xrd_data["lrdd-xml"] = $attributes["template"];
149 } elseif (($attributes["rel"] == "lrdd")
150 && ($attributes["type"] == "application/json")
152 $xrd_data["lrdd-json"] = $attributes["template"];
153 } elseif ($attributes["rel"] == "lrdd") {
154 $xrd_data["lrdd"] = $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::xrd($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::xrd($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 $key => $link) {
258 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
262 $path = str_replace('{uri}', urlencode($uri), $link);
263 $webfinger = self::webfinger($path);
265 if (!$webfinger && (strstr($uri, "@"))) {
266 $path = str_replace('{uri}', urlencode("acct:".$uri), $link);
267 $webfinger = self::webfinger($path);
270 // Special treatment for Mastodon
271 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
272 // But the webfinger for this format fails.
273 if (!$webfinger && !empty($nick)) {
274 // Mastodon uses a "@" as prefix for usernames in their url format
275 $nick = ltrim($nick, '@');
277 $addr = $nick."@".$host;
279 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
280 $webfinger = self::webfinger($path);
284 if (!is_array($webfinger["links"])) {
285 logger("No webfinger links found for ".$uri, LOGGER_DEBUG);
291 foreach ($webfinger["links"] as $link) {
292 $data[] = array("@attributes" => $link);
295 if (is_array($webfinger["aliases"])) {
296 foreach ($webfinger["aliases"] as $alias) {
297 $data[] = array("@attributes" =>
298 array("rel" => "alias",
307 * @brief Fetch information (protocol endpoints and user information) about a given uri
309 * @param string $uri Address that should be probed
310 * @param string $network Test for this specific network
311 * @param integer $uid User ID for the probe (only used for mails)
312 * @param boolean $cache Use cached values?
314 * @return array uri data
316 public static function uri($uri, $network = "", $uid = 0, $cache = true) {
319 $result = Cache::get("probe_url:".$network.":".$uri);
320 if (!is_null($result)) {
329 $data = self::detect($uri, $network, $uid);
331 if (!isset($data["url"])) {
335 if ($data["photo"] != "") {
336 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
338 $data["photo"] = System::baseUrl().'/images/person-175.jpg';
341 if (empty($data["name"])) {
342 if (!empty($data["nick"])) {
343 $data["name"] = $data["nick"];
346 if ($data["name"] == "") {
347 $data["name"] = $data["url"];
351 if (empty($data["nick"])) {
352 $data["nick"] = strtolower($data["name"]);
354 if (strpos($data['nick'], ' ')) {
355 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
359 if (self::$baseurl != "") {
360 $data["baseurl"] = self::$baseurl;
363 if (!isset($data["network"])) {
364 $data["network"] = NETWORK_PHANTOM;
367 $data = self::rearrangeData($data);
369 // Only store into the cache if the value seems to be valid
370 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
371 Cache::set("probe_url:".$network.":".$uri, $data, CACHE_DAY);
373 /// @todo temporary fix - we need a real contact update function that updates only changing fields
374 /// The biggest problem is the avatar picture that could have a reduced image size.
375 /// It should only be updated if the existing picture isn't existing anymore.
376 /// We only update the contact when it is no probing for a specific network.
377 if (($data['network'] != NETWORK_FEED)
385 $fields = array('name' => $data['name'],
386 'nick' => $data['nick'],
387 'url' => $data['url'],
388 'addr' => $data['addr'],
389 'photo' => $data['photo'],
390 'keywords' => $data['keywords'],
391 'location' => $data['location'],
392 'about' => $data['about'],
393 'notify' => $data['notify'],
394 'network' => $data['network'],
395 'server_url' => $data['baseurl'],
396 'updated' => dbm::date());
398 foreach ($fields AS $key => $val) {
400 unset($fields[$key]);
404 dba::update('gcontact', $fields, array('nurl' => normalise_link($data["url"])));
406 $fields = array('name' => $data['name'],
407 'nick' => $data['nick'],
408 'url' => $data['url'],
409 'addr' => $data['addr'],
410 'alias' => $data['alias'],
411 'keywords' => $data['keywords'],
412 'location' => $data['location'],
413 'about' => $data['about'],
414 'batch' => $data['batch'],
415 'notify' => $data['notify'],
416 'poll' => $data['poll'],
417 'request' => $data['request'],
418 'confirm' => $data['confirm'],
419 'poco' => $data['poco'],
420 'network' => $data['network'],
421 'success_update' => dbm::date());
423 foreach ($fields AS $key => $val) {
425 unset($fields[$key]);
429 $condition = array('nurl' => normalise_link($data["url"]), 'self' => false, 'uid' => 0);
430 dba::update('contact', $fields, $condition);
438 * @brief Switch the scheme of an url between http and https
440 * @param string $url URL
442 * @return string switched URL
444 private static function switchScheme($url) {
445 $parts = parse_url($url);
447 if (!isset($parts['scheme'])) {
451 if ($parts['scheme'] == 'http') {
452 $url = str_replace('http://', 'https://', $url);
453 } elseif ($parts['scheme'] == 'https') {
454 $url = str_replace('https://', 'http://', $url);
461 * @brief Checks if a profile url should be OStatus but only provides partial information
463 * @param array $webfinger Webfinger data
464 * @param string $lrdd Path template for webfinger request
466 * @return array fixed webfinger data
468 private static function fixOstatus($webfinger, $lrdd) {
469 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
476 foreach ($webfinger['links'] as $link) {
477 if ($link['rel'] == NAMESPACE_OSTATUSSUB) {
480 if ($link['rel'] == 'magic-public-key') {
485 if (!$is_ostatus || $has_key) {
489 $url = self::switchScheme($webfinger['subject']);
490 $path = str_replace('{uri}', urlencode($url), $lrdd);
491 $webfinger2 = self::webfinger($path);
493 // Is the new webfinger detectable as OStatus?
494 if (self::ostatus($webfinger2, true)) {
495 $webfinger = $webfinger2;
502 * @brief Fetch information (protocol endpoints and user information) about a given uri
504 * This function is only called by the "uri" function that adds caching and rearranging of data.
506 * @param string $uri Address that should be probed
507 * @param string $network Test for this specific network
508 * @param integer $uid User ID for the probe (only used for mails)
510 * @return array uri data
512 private static function detect($uri, $network, $uid) {
513 $parts = parse_url($uri);
515 if (!empty($parts["scheme"]) && !empty($parts["host"]) && !empty($parts["path"])) {
516 $host = $parts["host"];
517 if (!empty($parts["port"])) {
518 $host .= ':'.$parts["port"];
521 if ($host == 'twitter.com') {
522 return array("network" => NETWORK_TWITTER);
524 $lrdd = self::xrd($host);
526 if (is_bool($lrdd)) {
530 $path_parts = explode("/", trim($parts["path"], "/"));
532 while (!$lrdd && (sizeof($path_parts) > 1)) {
533 $host .= "/".array_shift($path_parts);
534 $lrdd = self::xrd($host);
537 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
538 return self::feed($uri);
540 $nick = array_pop($path_parts);
542 // Mastodon uses a "@" as prefix for usernames in their url format
543 $nick = ltrim($nick, '@');
545 $addr = $nick."@".$host;
547 } elseif (strstr($uri, '@')) {
548 // If the URI starts with "mailto:" then jump directly to the mail detection
549 if (strpos($uri, 'mailto:') !== false) {
550 $uri = str_replace('mailto:', '', $uri);
551 return self::mail($uri, $uid);
554 if ($network == NETWORK_MAIL) {
555 return self::mail($uri, $uid);
557 // Remove "acct:" from the URI
558 $uri = str_replace('acct:', '', $uri);
560 $host = substr($uri, strpos($uri, '@') + 1);
561 $nick = substr($uri, 0, strpos($uri, '@'));
563 if (strpos($uri, '@twitter.com')) {
564 return array("network" => NETWORK_TWITTER);
566 $lrdd = self::xrd($host);
568 if (is_bool($lrdd)) {
573 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
574 return self::mail($uri, $uid);
579 logger("Uri ".$uri." was not detectable", LOGGER_DEBUG);
585 /// @todo Do we need the prefix "acct:" or "acct://"?
587 foreach ($lrdd as $key => $link) {
591 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
594 // At first try it with the given uri
595 $path = str_replace('{uri}', urlencode($uri), $link);
596 $webfinger = self::webfinger($path);
598 // Fix possible problems with GNU Social probing to wrong scheme
599 $webfinger = self::fixOstatus($webfinger, $link);
601 // We cannot be sure that the detected address was correct, so we don't use the values
602 if ($webfinger && ($uri != $addr)) {
607 // Try webfinger with the address (user@domain.tld)
609 $path = str_replace('{uri}', urlencode($addr), $link);
610 $webfinger = self::webfinger($path);
613 // Mastodon needs to have it with "acct:"
615 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
616 $webfinger = self::webfinger($path);
620 return self::feed($uri);
625 logger("Probing ".$uri, LOGGER_DEBUG);
627 if (in_array($network, array("", NETWORK_DFRN))) {
628 $result = self::dfrn($webfinger);
630 if ((!$result && ($network == "")) || ($network == NETWORK_DIASPORA)) {
631 $result = self::diaspora($webfinger);
633 if ((!$result && ($network == "")) || ($network == NETWORK_OSTATUS)) {
634 $result = self::ostatus($webfinger);
636 if ((!$result && ($network == "")) || ($network == NETWORK_PUMPIO)) {
637 $result = self::pumpio($webfinger);
639 if ((!$result && ($network == "")) || ($network == NETWORK_FEED)) {
640 $result = self::feed($uri);
642 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
643 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
644 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
645 $result["nick"] = $nick;
648 if (empty($result["addr"]) && ($addr != "")) {
649 $result["addr"] = $addr;
653 logger($uri." is ".$result["network"], LOGGER_DEBUG);
655 if (empty($result["baseurl"])) {
656 $pos = strpos($result["url"], $host);
658 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
666 * @brief Perform a webfinger request.
668 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
670 * @param string $url Address that should be probed
672 * @return array webfinger data
674 private static function webfinger($url) {
676 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
679 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
680 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
683 $data = $ret['body'];
685 // This is a bugfix for this issue: https://github.com/redmatrix/hubzilla/issues/851
686 // $data = str_replace('&url=', '&url=', $data);
687 // we have to decide if we want to create a workaround - or we wait for an update
689 $xrd = parse_xml_string($data, false);
691 if (!is_object($xrd)) {
692 // If it is not XML, maybe it is JSON
693 $webfinger = json_decode($data, true);
695 if (!isset($webfinger["links"])) {
696 logger("No json webfinger links for ".$url, LOGGER_DEBUG);
703 $xrd_arr = xml::element_to_array($xrd);
704 if (!isset($xrd_arr["xrd"]["link"])) {
705 logger("No XML webfinger links for ".$url, LOGGER_DEBUG);
709 $webfinger = array();
711 if (!empty($xrd_arr["xrd"]["subject"])) {
712 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
715 if (!empty($xrd_arr["xrd"]["alias"])) {
716 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
719 $webfinger["links"] = array();
721 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
722 if (!empty($data["@attributes"])) {
723 $attributes = $data["@attributes"];
724 } elseif ($value == "@attributes") {
730 $webfinger["links"][] = $attributes;
736 * @brief Poll the Friendica specific noscrape page.
738 * "noscrape" is a faster alternative to fetch the data from the hcard.
739 * This functionality was originally created for the directory.
741 * @param string $noscrape_url Link to the noscrape page
742 * @param array $data The already fetched data
744 * @return array noscrape data
746 private static function pollNoscrape($noscrape_url, $data) {
747 $ret = z_fetch_url($noscrape_url);
748 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
751 $content = $ret['body'];
753 logger("Empty body for ".$noscrape_url, LOGGER_DEBUG);
757 $json = json_decode($content, true);
758 if (!is_array($json)) {
759 logger("No json data for ".$noscrape_url, LOGGER_DEBUG);
763 if (!empty($json["fn"])) {
764 $data["name"] = $json["fn"];
767 if (!empty($json["addr"])) {
768 $data["addr"] = $json["addr"];
771 if (!empty($json["nick"])) {
772 $data["nick"] = $json["nick"];
775 if (!empty($json["comm"])) {
776 $data["community"] = $json["comm"];
779 if (!empty($json["tags"])) {
780 $keywords = implode(" ", $json["tags"]);
781 if ($keywords != "") {
782 $data["keywords"] = $keywords;
786 $location = formatted_location($json);
788 $data["location"] = $location;
791 if (!empty($json["about"])) {
792 $data["about"] = $json["about"];
795 if (!empty($json["key"])) {
796 $data["pubkey"] = $json["key"];
799 if (!empty($json["photo"])) {
800 $data["photo"] = $json["photo"];
803 if (!empty($json["dfrn-request"])) {
804 $data["request"] = $json["dfrn-request"];
807 if (!empty($json["dfrn-confirm"])) {
808 $data["confirm"] = $json["dfrn-confirm"];
811 if (!empty($json["dfrn-notify"])) {
812 $data["notify"] = $json["dfrn-notify"];
815 if (!empty($json["dfrn-poll"])) {
816 $data["poll"] = $json["dfrn-poll"];
823 * @brief Check for valid DFRN data
825 * @param array $data DFRN data
827 * @return int Number of errors
829 public static function validDfrn($data) {
831 if (!isset($data['key'])) {
834 if (!isset($data['dfrn-request'])) {
837 if (!isset($data['dfrn-confirm'])) {
840 if (!isset($data['dfrn-notify'])) {
843 if (!isset($data['dfrn-poll'])) {
850 * @brief Fetch data from a DFRN profile page and via "noscrape"
852 * @param string $profile_link Link to the profile page
854 * @return array profile data
856 public static function profile($profile_link) {
860 logger("Check profile ".$profile_link, LOGGER_DEBUG);
862 // Fetch data via noscrape - this is faster
863 $noscrape_url = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile_link);
864 $data = self::pollNoscrape($noscrape_url, $data);
866 if (!isset($data["notify"])
867 || !isset($data["confirm"])
868 || !isset($data["request"])
869 || !isset($data["poll"])
870 || !isset($data["poco"])
871 || !isset($data["name"])
872 || !isset($data["photo"])
874 $data = self::pollHcard($profile_link, $data, true);
877 $prof_data = array();
878 $prof_data["addr"] = $data["addr"];
879 $prof_data["nick"] = $data["nick"];
880 $prof_data["dfrn-request"] = $data["request"];
881 $prof_data["dfrn-confirm"] = $data["confirm"];
882 $prof_data["dfrn-notify"] = $data["notify"];
883 $prof_data["dfrn-poll"] = $data["poll"];
884 $prof_data["dfrn-poco"] = $data["poco"];
885 $prof_data["photo"] = $data["photo"];
886 $prof_data["fn"] = $data["name"];
887 $prof_data["key"] = $data["pubkey"];
889 logger("Result for profile ".$profile_link.": ".print_r($prof_data, true), LOGGER_DEBUG);
895 * @brief Check for DFRN contact
897 * @param array $webfinger Webfinger data
899 * @return array DFRN data
901 private static function dfrn($webfinger) {
905 foreach ($webfinger["links"] as $link) {
906 if (($link["rel"] == NAMESPACE_DFRN) && ($link["href"] != "")) {
907 $data["network"] = NETWORK_DFRN;
908 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
909 $data["poll"] = $link["href"];
910 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
911 $data["url"] = $link["href"];
912 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
913 $hcard_url = $link["href"];
914 } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
915 $data["poco"] = $link["href"];
916 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && ($link["href"] != "")) {
917 $data["photo"] = $link["href"];
918 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
919 $data["baseurl"] = trim($link["href"], '/');
920 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
921 $data["guid"] = $link["href"];
922 } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
923 $data["pubkey"] = base64_decode($link["href"]);
925 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
926 if (strstr($data["pubkey"], 'RSA ')) {
927 $data["pubkey"] = rsatopem($data["pubkey"]);
932 if (is_array($webfinger["aliases"])) {
933 foreach ($webfinger["aliases"] as $alias) {
934 if (substr($alias, 0, 5) == 'acct:') {
935 $data["addr"] = substr($alias, 5);
940 if (!isset($data["network"]) || ($hcard_url == "")) {
944 // Fetch data via noscrape - this is faster
945 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
946 $data = self::pollNoscrape($noscrape_url, $data);
948 if (isset($data["notify"])
949 && isset($data["confirm"])
950 && isset($data["request"])
951 && isset($data["poll"])
952 && isset($data["name"])
953 && isset($data["photo"])
958 $data = self::pollHcard($hcard_url, $data, true);
964 * @brief Poll the hcard page (Diaspora and Friendica specific)
966 * @param string $hcard_url Link to the hcard page
967 * @param array $data The already fetched data
968 * @param boolean $dfrn Poll DFRN specific data
970 * @return array hcard data
972 private static function pollHcard($hcard_url, $data, $dfrn = false) {
973 $ret = z_fetch_url($hcard_url);
974 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
977 $content = $ret['body'];
982 $doc = new DOMDocument();
983 if (!@$doc->loadHTML($content)) {
987 $xpath = new DomXPath($doc);
989 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
990 if (!is_object($vcards)) {
994 if ($vcards->length > 0) {
995 $vcard = $vcards->item(0);
997 // We have to discard the guid from the hcard in favour of the guid from lrdd
998 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
999 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1000 if (($search->length > 0) && ($data["guid"] == "")) {
1001 $data["guid"] = $search->item(0)->nodeValue;
1004 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1005 if ($search->length > 0) {
1006 $data["nick"] = $search->item(0)->nodeValue;
1009 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1010 if ($search->length > 0) {
1011 $data["name"] = $search->item(0)->nodeValue;
1014 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1015 if ($search->length > 0) {
1016 $data["searchable"] = $search->item(0)->nodeValue;
1019 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1020 if ($search->length > 0) {
1021 $data["pubkey"] = $search->item(0)->nodeValue;
1022 if (strstr($data["pubkey"], 'RSA ')) {
1023 $data["pubkey"] = rsatopem($data["pubkey"]);
1027 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1028 if ($search->length > 0) {
1029 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1034 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1035 foreach ($photos as $photo) {
1037 foreach ($photo->attributes as $attribute) {
1038 $attr[$attribute->name] = trim($attribute->value);
1041 if (isset($attr["src"]) && isset($attr["width"])) {
1042 $avatar[$attr["width"]] = $attr["src"];
1045 // We don't have a width. So we just take everything that we got.
1046 // This is a Hubzilla workaround which doesn't send a width.
1047 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1048 $avatar[] = $attr["src"];
1052 if (sizeof($avatar)) {
1054 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1058 // Poll DFRN specific data
1059 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1060 if ($search->length > 0) {
1061 foreach ($search as $link) {
1062 //$data["request"] = $search->item(0)->nodeValue;
1064 foreach ($link->attributes as $attribute) {
1065 $attr[$attribute->name] = trim($attribute->value);
1068 $data[substr($attr["rel"], 5)] = $attr["href"];
1072 // Older Friendica versions had used the "uid" field differently than newer versions
1073 if ($data["nick"] == $data["guid"]) {
1074 unset($data["guid"]);
1083 * @brief Check for Diaspora contact
1085 * @param array $webfinger Webfinger data
1087 * @return array Diaspora data
1089 private static function diaspora($webfinger) {
1093 foreach ($webfinger["links"] as $link) {
1094 if (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
1095 $hcard_url = $link["href"];
1096 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
1097 $data["baseurl"] = trim($link["href"], '/');
1098 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
1099 $data["guid"] = $link["href"];
1100 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
1101 $data["url"] = $link["href"];
1102 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1103 $data["poll"] = $link["href"];
1104 } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
1105 $data["poco"] = $link["href"];
1106 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1107 $data["notify"] = $link["href"];
1108 } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
1109 $data["pubkey"] = base64_decode($link["href"]);
1111 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1112 if (strstr($data["pubkey"], 'RSA ')) {
1113 $data["pubkey"] = rsatopem($data["pubkey"]);
1118 if (!isset($data["url"]) || ($hcard_url == "")) {
1122 if (is_array($webfinger["aliases"])) {
1123 foreach ($webfinger["aliases"] as $alias) {
1124 if (normalise_link($alias) != normalise_link($data["url"]) && ! strstr($alias, "@")) {
1125 $data["alias"] = $alias;
1130 // Fetch further information from the hcard
1131 $data = self::pollHcard($hcard_url, $data);
1137 if (isset($data["url"])
1138 && isset($data["guid"])
1139 && isset($data["baseurl"])
1140 && isset($data["pubkey"])
1141 && ($hcard_url != "")
1143 $data["network"] = NETWORK_DIASPORA;
1145 // The Diaspora handle must always be lowercase
1146 $data["addr"] = strtolower($data["addr"]);
1148 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1149 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1150 $data["batch"] = $data["baseurl"] . "/receive/public";
1159 * @brief Check for OStatus contact
1161 * @param array $webfinger Webfinger data
1162 * @param bool $short Short detection mode
1164 * @return array|bool OStatus data or "false" on error or "true" on short mode
1166 private static function ostatus($webfinger, $short = false) {
1168 if (is_array($webfinger["aliases"])) {
1169 foreach ($webfinger["aliases"] as $alias) {
1170 if (strstr($alias, "@")) {
1171 $data["addr"] = str_replace('acct:', '', $alias);
1176 if (is_string($webfinger["subject"]) && strstr($webfinger["subject"], "@")) {
1177 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1180 if (is_array($webfinger["links"])) {
1181 foreach ($webfinger["links"] as $link) {
1182 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1183 && ($link["type"] == "text/html")
1184 && ($link["href"] != "")
1186 $data["url"] = $link["href"];
1187 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1188 $data["notify"] = $link["href"];
1189 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1190 $data["poll"] = $link["href"];
1191 } elseif (($link["rel"] == "magic-public-key") && ($link["href"] != "")) {
1192 $pubkey = $link["href"];
1194 if (substr($pubkey, 0, 5) === 'data:') {
1195 if (strstr($pubkey, ',')) {
1196 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1198 $pubkey = substr($pubkey, 5);
1200 } elseif (normalise_link($pubkey) == 'http://') {
1201 $ret = z_fetch_url($pubkey);
1202 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1205 $pubkey = $ret['body'];
1208 $key = explode(".", $pubkey);
1210 if (sizeof($key) >= 3) {
1211 $m = base64url_decode($key[1]);
1212 $e = base64url_decode($key[2]);
1213 $data["pubkey"] = metopem($m, $e);
1219 if (isset($data["notify"]) && isset($data["pubkey"])
1220 && isset($data["poll"])
1221 && isset($data["url"])
1223 $data["network"] = NETWORK_OSTATUS;
1232 // Fetch all additional data from the feed
1233 $ret = z_fetch_url($data["poll"]);
1234 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1237 $feed = $ret['body'];
1238 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1243 if ($feed_data["header"]["author-name"] != "") {
1244 $data["name"] = $feed_data["header"]["author-name"];
1246 if ($feed_data["header"]["author-nick"] != "") {
1247 $data["nick"] = $feed_data["header"]["author-nick"];
1249 if ($feed_data["header"]["author-avatar"] != "") {
1250 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1252 if ($feed_data["header"]["author-id"] != "") {
1253 $data["alias"] = $feed_data["header"]["author-id"];
1255 if ($feed_data["header"]["author-location"] != "") {
1256 $data["location"] = $feed_data["header"]["author-location"];
1258 if ($feed_data["header"]["author-about"] != "") {
1259 $data["about"] = $feed_data["header"]["author-about"];
1261 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1262 // So we take the value that we just fetched, although the other one worked as well
1263 if ($feed_data["header"]["author-link"] != "") {
1264 $data["url"] = $feed_data["header"]["author-link"];
1267 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1268 $data['url'] = $data["alias"];
1269 $data["alias"] = '';
1272 /// @todo Fetch location and "about" from the feed as well
1277 * @brief Fetch data from a pump.io profile page
1279 * @param string $profile_link Link to the profile page
1281 * @return array profile data
1283 private static function pumpioProfileData($profile_link) {
1285 $doc = new DOMDocument();
1286 if (!@$doc->loadHTMLFile($profile_link)) {
1290 $xpath = new DomXPath($doc);
1294 // This is ugly - but pump.io doesn't seem to know a better way for it
1295 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1296 $pos = strpos($data["name"], chr(10));
1298 $data["name"] = trim(substr($data["name"], 0, $pos));
1301 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1303 foreach ($avatar->attributes as $attribute) {
1304 if ($attribute->name == "src") {
1305 $data["photo"] = trim($attribute->value);
1310 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
1311 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
1317 * @brief Check for pump.io contact
1319 * @param array $webfinger Webfinger data
1321 * @return array pump.io data
1323 private static function pumpio($webfinger) {
1326 foreach ($webfinger["links"] as $link) {
1327 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1328 && ($link["type"] == "text/html")
1329 && ($link["href"] != "")
1331 $data["url"] = $link["href"];
1332 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1333 $data["notify"] = $link["href"];
1334 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1335 $data["poll"] = $link["href"];
1336 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1337 $data["dialback"] = $link["href"];
1340 if (isset($data["poll"]) && isset($data["notify"])
1341 && isset($data["dialback"])
1342 && isset($data["url"])
1344 // by now we use these fields only for the network type detection
1345 // So we unset all data that isn't used at the moment
1346 unset($data["dialback"]);
1348 $data["network"] = NETWORK_PUMPIO;
1353 $profile_data = self::pumpioProfileData($data["url"]);
1355 if (!$profile_data) {
1359 $data = array_merge($data, $profile_data);
1365 * @brief Check page for feed link
1367 * @param string $url Page link
1369 * @return string feed link
1371 private static function getFeedLink($url) {
1372 $doc = new DOMDocument();
1374 if (!@$doc->loadHTMLFile($url)) {
1378 $xpath = new DomXPath($doc);
1380 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1381 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1382 if (!is_object($feeds)) {
1386 if ($feeds->length == 0) {
1392 foreach ($feeds as $feed) {
1394 foreach ($feed->attributes as $attribute) {
1395 $attr[$attribute->name] = trim($attribute->value);
1398 if ($feed_url == "") {
1399 $feed_url = $attr["href"];
1407 * @brief Check for feed contact
1409 * @param string $url Profile link
1410 * @param boolean $probe Do a probe if the page contains a feed link
1412 * @return array feed data
1414 private static function feed($url, $probe = true) {
1415 $ret = z_fetch_url($url);
1416 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1419 $feed = $ret['body'];
1420 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1427 $feed_url = self::getFeedLink($url);
1433 return self::feed($feed_url, false);
1436 if ($feed_data["header"]["author-name"] != "") {
1437 $data["name"] = $feed_data["header"]["author-name"];
1440 if ($feed_data["header"]["author-nick"] != "") {
1441 $data["nick"] = $feed_data["header"]["author-nick"];
1444 if ($feed_data["header"]["author-avatar"] != "") {
1445 $data["photo"] = $feed_data["header"]["author-avatar"];
1448 if ($feed_data["header"]["author-id"] != "") {
1449 $data["alias"] = $feed_data["header"]["author-id"];
1452 $data["url"] = $url;
1453 $data["poll"] = $url;
1455 if ($feed_data["header"]["author-link"] != "") {
1456 $data["baseurl"] = $feed_data["header"]["author-link"];
1458 $data["baseurl"] = $data["url"];
1461 $data["network"] = NETWORK_FEED;
1467 * @brief Check for mail contact
1469 * @param string $uri Profile link
1470 * @param integer $uid User ID
1472 * @return array mail data
1474 private static function mail($uri, $uid) {
1476 if (!validate_email($uri)) {
1480 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1482 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1484 if (dbm::is_result($x) && dbm::is_result($r)) {
1485 $mailbox = construct_mailbox_name($r[0]);
1487 openssl_private_decrypt(hex2bin($r[0]['pass']), $password, $x[0]['prvkey']);
1488 $mbox = email_connect($mailbox, $r[0]['user'], $password);
1494 $msgs = email_poll($mbox, $uri);
1495 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1497 if (!count($msgs)) {
1501 $phost = substr($uri, strpos($uri, '@') + 1);
1504 $data["addr"] = $uri;
1505 $data["network"] = NETWORK_MAIL;
1506 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1507 $data["nick"] = $data["name"];
1508 $data["photo"] = avatar_img($uri);
1509 $data["url"] = 'http://'.$phost."/".$data["nick"];
1510 $data["notify"] = 'smtp '.random_string();
1511 $data["poll"] = 'email '.random_string();
1513 $x = email_msg_meta($mbox, $msgs[0]);
1514 if (stristr($x[0]->from, $uri)) {
1515 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1516 } elseif (stristr($x[0]->to, $uri)) {
1517 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1520 foreach ($adr as $feadr) {
1521 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1522 &&(strcasecmp($feadr->host, $phost) == 0)
1523 && (strlen($feadr->personal))
1525 $personal = imap_mime_header_decode($feadr->personal);
1527 foreach ($personal as $perspart) {
1528 if ($perspart->charset != "default") {
1529 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1531 $data["name"] .= $perspart->text;
1535 $data["name"] = notags($data["name"]);
1545 * @brief Mix two paths together to possibly fix missing parts
1547 * @param string $avatar Path to the avatar
1548 * @param string $base Another path that is hopefully complete
1550 * @return string fixed avatar path
1552 public static function fixAvatar($avatar, $base) {
1553 $base_parts = parse_url($base);
1555 // Remove all parts that could create a problem
1556 unset($base_parts['path']);
1557 unset($base_parts['query']);
1558 unset($base_parts['fragment']);
1560 $avatar_parts = parse_url($avatar);
1563 $parts = array_merge($base_parts, $avatar_parts);
1565 // And put them together again
1566 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1567 $host = isset($parts['host']) ? $parts['host'] : '';
1568 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1569 $path = isset($parts['path']) ? $parts['path'] : '';
1570 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1571 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1573 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1575 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);