3 namespace Friendica\Network;
6 * @file src/Network/Probe.php
7 * @brief Functions for probing URL
12 use Friendica\Core\Config;
21 require_once 'include/feed.php';
22 require_once 'include/email.php';
23 require_once 'include/network.php';
26 * @brief This class contain functions for probing URL
31 private static $baseurl;
34 * @brief Rearrange the array so that it always has the same order
36 * @param array $data Unordered data
38 * @return array Ordered data
40 private static function rearrangeData($data) {
41 $fields = array("name", "nick", "guid", "url", "addr", "alias",
42 "photo", "community", "keywords", "location", "about",
43 "batch", "notify", "poll", "request", "confirm", "poco",
44 "priority", "network", "pubkey", "baseurl");
47 foreach ($fields as $field) {
48 if (isset($data[$field])) {
49 $newdata[$field] = $data[$field];
51 $newdata[$field] = "";
55 // We don't use the "priority" field anymore and replace it with a dummy.
56 $newdata["priority"] = 0;
62 * @brief Check if the hostname belongs to the own server
64 * @param string $host The hostname that is to be checked
66 * @return bool Does the testes hostname belongs to the own server?
68 private static function ownHost($host) {
69 $own_host = get_app()->get_hostname();
71 $parts = parse_url($host);
73 if (!isset($parts['scheme'])) {
74 $parts = parse_url('http://'.$host);
77 if (!isset($parts['host'])) {
80 return $parts['host'] == $own_host;
84 * @brief Probes for XRD data
86 * @param string $host The host part of an url
89 * 'lrdd' => Link to LRDD endpoint
90 * 'lrdd-xml' => Link to LRDD endpoint in XML format
91 * 'lrdd-json' => Link to LRDD endpoint in JSON format
93 private static function xrd($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);
112 if (!is_object($xrd)) {
113 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
114 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
115 logger("Probing timeout for ".$url, LOGGER_DEBUG);
119 $xrd = parse_xml_string($xml, false);
121 if (!is_object($xrd)) {
122 logger("No xrd object found for ".$host, LOGGER_DEBUG);
126 $links = xml::element_to_array($xrd);
127 if (!isset($links["xrd"]["link"])) {
128 logger("No xrd data found for ".$host, LOGGER_DEBUG);
134 foreach ($links["xrd"]["link"] as $value => $link) {
135 if (!empty($link["@attributes"])) {
136 $attributes = $link["@attributes"];
137 } elseif ($value == "@attributes") {
143 if (($attributes["rel"] == "lrdd")
144 && ($attributes["type"] == "application/xrd+xml")
146 $xrd_data["lrdd-xml"] = $attributes["template"];
147 } elseif (($attributes["rel"] == "lrdd")
148 && ($attributes["type"] == "application/json")
150 $xrd_data["lrdd-json"] = $attributes["template"];
151 } elseif ($attributes["rel"] == "lrdd") {
152 $xrd_data["lrdd"] = $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::xrd($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::xrd($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 $key => $link) {
256 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
260 $path = str_replace('{uri}', urlencode($uri), $link);
261 $webfinger = self::webfinger($path);
263 if (!$webfinger && (strstr($uri, "@"))) {
264 $path = str_replace('{uri}', urlencode("acct:".$uri), $link);
265 $webfinger = self::webfinger($path);
268 // Special treatment for Mastodon
269 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
270 // But the webfinger for this format fails.
271 if (!$webfinger && !empty($nick)) {
272 // Mastodon uses a "@" as prefix for usernames in their url format
273 $nick = ltrim($nick, '@');
275 $addr = $nick."@".$host;
277 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
278 $webfinger = self::webfinger($path);
282 if (!is_array($webfinger["links"])) {
283 logger("No webfinger links found for ".$uri, LOGGER_DEBUG);
289 foreach ($webfinger["links"] as $link) {
290 $data[] = array("@attributes" => $link);
293 if (is_array($webfinger["aliases"])) {
294 foreach ($webfinger["aliases"] as $alias) {
295 $data[] = array("@attributes" =>
296 array("rel" => "alias",
305 * @brief Fetch information (protocol endpoints and user information) about a given uri
307 * @param string $uri Address that should be probed
308 * @param string $network Test for this specific network
309 * @param integer $uid User ID for the probe (only used for mails)
310 * @param boolean $cache Use cached values?
312 * @return array uri data
314 public static function uri($uri, $network = "", $uid = 0, $cache = true) {
317 $result = Cache::get("probe_url:".$network.":".$uri);
318 if (!is_null($result)) {
327 $data = self::detect($uri, $network, $uid);
329 if (!isset($data["url"])) {
333 if ($data["photo"] != "") {
334 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
336 $data["photo"] = App::get_baseurl().'/images/person-175.jpg';
339 if (empty($data["name"])) {
340 if (!empty($data["nick"])) {
341 $data["name"] = $data["nick"];
344 if ($data["name"] == "") {
345 $data["name"] = $data["url"];
349 if (empty($data["nick"])) {
350 $data["nick"] = strtolower($data["name"]);
352 if (strpos($data['nick'], ' ')) {
353 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
357 if (self::$baseurl != "") {
358 $data["baseurl"] = self::$baseurl;
361 if (!isset($data["network"])) {
362 $data["network"] = NETWORK_PHANTOM;
365 $data = self::rearrangeData($data);
367 // Only store into the cache if the value seems to be valid
368 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
369 Cache::set("probe_url:".$network.":".$uri, $data, CACHE_DAY);
371 /// @todo temporary fix - we need a real contact update function that updates only changing fields
372 /// The biggest problem is the avatar picture that could have a reduced image size.
373 /// It should only be updated if the existing picture isn't existing anymore.
374 /// We only update the contact when it is no probing for a specific network.
375 if (($data['network'] != NETWORK_FEED)
383 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `url` = '%s', `addr` = '%s',
384 `notify` = '%s', `poll` = '%s', `alias` = '%s', `success_update` = '%s'
385 WHERE `nurl` = '%s' AND NOT `self` AND `uid` = 0",
386 dbesc($data["name"]),
387 dbesc($data["nick"]),
389 dbesc($data["addr"]),
390 dbesc($data["notify"]),
391 dbesc($data["poll"]),
392 dbesc($data["alias"]),
393 dbesc(datetime_convert()),
394 dbesc(normalise_link($data['url']))
403 * @brief Switch the scheme of an url between http and https
405 * @param string $url URL
407 * @return string switched URL
409 private static function switchScheme($url) {
410 $parts = parse_url($url);
412 if (!isset($parts['scheme'])) {
416 if ($parts['scheme'] == 'http') {
417 $url = str_replace('http://', 'https://', $url);
418 } elseif ($parts['scheme'] == 'https') {
419 $url = str_replace('https://', 'http://', $url);
426 * @brief Checks if a profile url should be OStatus but only provides partial information
428 * @param array $webfinger Webfinger data
429 * @param string $lrdd Path template for webfinger request
431 * @return array fixed webfinger data
433 private static function fixOstatus($webfinger, $lrdd) {
434 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
441 foreach ($webfinger['links'] as $link) {
442 if ($link['rel'] == NAMESPACE_OSTATUSSUB) {
445 if ($link['rel'] == 'magic-public-key') {
450 if (!$is_ostatus || $has_key) {
454 $url = self::switchScheme($webfinger['subject']);
455 $path = str_replace('{uri}', urlencode($url), $lrdd);
456 $webfinger2 = self::webfinger($path);
458 // Is the new webfinger detectable as OStatus?
459 if (self::ostatus($webfinger2, true)) {
460 $webfinger = $webfinger2;
467 * @brief Fetch information (protocol endpoints and user information) about a given uri
469 * This function is only called by the "uri" function that adds caching and rearranging of data.
471 * @param string $uri Address that should be probed
472 * @param string $network Test for this specific network
473 * @param integer $uid User ID for the probe (only used for mails)
475 * @return array uri data
477 private static function detect($uri, $network, $uid) {
478 $parts = parse_url($uri);
480 if (!empty($parts["scheme"]) && !empty($parts["host"]) && !empty($parts["path"])) {
481 $host = $parts["host"];
482 if (!empty($parts["port"])) {
483 $host .= ':'.$parts["port"];
486 if ($host == 'twitter.com') {
487 return array("network" => NETWORK_TWITTER);
489 $lrdd = self::xrd($host);
491 if (is_bool($lrdd)) {
495 $path_parts = explode("/", trim($parts["path"], "/"));
497 while (!$lrdd && (sizeof($path_parts) > 1)) {
498 $host .= "/".array_shift($path_parts);
499 $lrdd = self::xrd($host);
502 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
503 return self::feed($uri);
505 $nick = array_pop($path_parts);
507 // Mastodon uses a "@" as prefix for usernames in their url format
508 $nick = ltrim($nick, '@');
510 $addr = $nick."@".$host;
512 } elseif (strstr($uri, '@')) {
513 // If the URI starts with "mailto:" then jump directly to the mail detection
514 if (strpos($uri, 'mailto:') !== false) {
515 $uri = str_replace('mailto:', '', $uri);
516 return self::mail($uri, $uid);
519 if ($network == NETWORK_MAIL) {
520 return self::mail($uri, $uid);
522 // Remove "acct:" from the URI
523 $uri = str_replace('acct:', '', $uri);
525 $host = substr($uri, strpos($uri, '@') + 1);
526 $nick = substr($uri, 0, strpos($uri, '@'));
528 if (strpos($uri, '@twitter.com')) {
529 return array("network" => NETWORK_TWITTER);
531 $lrdd = self::xrd($host);
533 if (is_bool($lrdd)) {
538 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
539 return self::mail($uri, $uid);
544 logger("Uri ".$uri." was not detectable", LOGGER_DEBUG);
550 /// @todo Do we need the prefix "acct:" or "acct://"?
552 foreach ($lrdd as $key => $link) {
556 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
559 // At first try it with the given uri
560 $path = str_replace('{uri}', urlencode($uri), $link);
561 $webfinger = self::webfinger($path);
563 // Fix possible problems with GNU Social probing to wrong scheme
564 $webfinger = self::fixOstatus($webfinger, $link);
566 // We cannot be sure that the detected address was correct, so we don't use the values
567 if ($webfinger && ($uri != $addr)) {
572 // Try webfinger with the address (user@domain.tld)
574 $path = str_replace('{uri}', urlencode($addr), $link);
575 $webfinger = self::webfinger($path);
578 // Mastodon needs to have it with "acct:"
580 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
581 $webfinger = self::webfinger($path);
585 return self::feed($uri);
590 logger("Probing ".$uri, LOGGER_DEBUG);
592 if (in_array($network, array("", NETWORK_DFRN))) {
593 $result = self::dfrn($webfinger);
595 if ((!$result && ($network == "")) || ($network == NETWORK_DIASPORA)) {
596 $result = self::diaspora($webfinger);
598 if ((!$result && ($network == "")) || ($network == NETWORK_OSTATUS)) {
599 $result = self::ostatus($webfinger);
601 if ((!$result && ($network == "")) || ($network == NETWORK_PUMPIO)) {
602 $result = self::pumpio($webfinger);
604 if ((!$result && ($network == "")) || ($network == NETWORK_FEED)) {
605 $result = self::feed($uri);
607 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
608 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
609 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
610 $result["nick"] = $nick;
613 if (empty($result["addr"]) && ($addr != "")) {
614 $result["addr"] = $addr;
618 logger($uri." is ".$result["network"], LOGGER_DEBUG);
620 if (empty($result["baseurl"])) {
621 $pos = strpos($result["url"], $host);
623 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
631 * @brief Perform a webfinger request.
633 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
635 * @param string $url Address that should be probed
637 * @return array webfinger data
639 private static function webfinger($url) {
641 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
644 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
645 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
648 $data = $ret['body'];
650 $xrd = parse_xml_string($data, false);
652 if (!is_object($xrd)) {
653 // If it is not XML, maybe it is JSON
654 $webfinger = json_decode($data, true);
656 if (!isset($webfinger["links"])) {
657 logger("No json webfinger links for ".$url, LOGGER_DEBUG);
664 $xrd_arr = xml::element_to_array($xrd);
665 if (!isset($xrd_arr["xrd"]["link"])) {
666 logger("No XML webfinger links for ".$url, LOGGER_DEBUG);
670 $webfinger = array();
672 if (!empty($xrd_arr["xrd"]["subject"])) {
673 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
676 if (!empty($xrd_arr["xrd"]["alias"])) {
677 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
680 $webfinger["links"] = array();
682 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
683 if (!empty($data["@attributes"])) {
684 $attributes = $data["@attributes"];
685 } elseif ($value == "@attributes") {
691 $webfinger["links"][] = $attributes;
697 * @brief Poll the Friendica specific noscrape page.
699 * "noscrape" is a faster alternative to fetch the data from the hcard.
700 * This functionality was originally created for the directory.
702 * @param string $noscrape_url Link to the noscrape page
703 * @param array $data The already fetched data
705 * @return array noscrape data
707 private static function pollNoscrape($noscrape_url, $data) {
708 $ret = z_fetch_url($noscrape_url);
709 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
712 $content = $ret['body'];
714 logger("Empty body for ".$noscrape_url, LOGGER_DEBUG);
718 $json = json_decode($content, true);
719 if (!is_array($json)) {
720 logger("No json data for ".$noscrape_url, LOGGER_DEBUG);
724 if (!empty($json["fn"])) {
725 $data["name"] = $json["fn"];
728 if (!empty($json["addr"])) {
729 $data["addr"] = $json["addr"];
732 if (!empty($json["nick"])) {
733 $data["nick"] = $json["nick"];
736 if (!empty($json["comm"])) {
737 $data["community"] = $json["comm"];
740 if (!empty($json["tags"])) {
741 $keywords = implode(" ", $json["tags"]);
742 if ($keywords != "") {
743 $data["keywords"] = $keywords;
747 $location = formatted_location($json);
749 $data["location"] = $location;
752 if (!empty($json["about"])) {
753 $data["about"] = $json["about"];
756 if (!empty($json["key"])) {
757 $data["pubkey"] = $json["key"];
760 if (!empty($json["photo"])) {
761 $data["photo"] = $json["photo"];
764 if (!empty($json["dfrn-request"])) {
765 $data["request"] = $json["dfrn-request"];
768 if (!empty($json["dfrn-confirm"])) {
769 $data["confirm"] = $json["dfrn-confirm"];
772 if (!empty($json["dfrn-notify"])) {
773 $data["notify"] = $json["dfrn-notify"];
776 if (!empty($json["dfrn-poll"])) {
777 $data["poll"] = $json["dfrn-poll"];
784 * @brief Check for valid DFRN data
786 * @param array $data DFRN data
788 * @return int Number of errors
790 public static function validDfrn($data) {
792 if (!isset($data['key'])) {
795 if (!isset($data['dfrn-request'])) {
798 if (!isset($data['dfrn-confirm'])) {
801 if (!isset($data['dfrn-notify'])) {
804 if (!isset($data['dfrn-poll'])) {
811 * @brief Fetch data from a DFRN profile page and via "noscrape"
813 * @param string $profile_link Link to the profile page
815 * @return array profile data
817 public static function profile($profile_link) {
821 logger("Check profile ".$profile_link, LOGGER_DEBUG);
823 // Fetch data via noscrape - this is faster
824 $noscrape_url = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile_link);
825 $data = self::pollNoscrape($noscrape_url, $data);
827 if (!isset($data["notify"])
828 || !isset($data["confirm"])
829 || !isset($data["request"])
830 || !isset($data["poll"])
831 || !isset($data["poco"])
832 || !isset($data["name"])
833 || !isset($data["photo"])
835 $data = self::pollHcard($profile_link, $data, true);
838 $prof_data = array();
839 $prof_data["addr"] = $data["addr"];
840 $prof_data["nick"] = $data["nick"];
841 $prof_data["dfrn-request"] = $data["request"];
842 $prof_data["dfrn-confirm"] = $data["confirm"];
843 $prof_data["dfrn-notify"] = $data["notify"];
844 $prof_data["dfrn-poll"] = $data["poll"];
845 $prof_data["dfrn-poco"] = $data["poco"];
846 $prof_data["photo"] = $data["photo"];
847 $prof_data["fn"] = $data["name"];
848 $prof_data["key"] = $data["pubkey"];
850 logger("Result for profile ".$profile_link.": ".print_r($prof_data, true), LOGGER_DEBUG);
856 * @brief Check for DFRN contact
858 * @param array $webfinger Webfinger data
860 * @return array DFRN data
862 private static function dfrn($webfinger) {
866 foreach ($webfinger["links"] as $link) {
867 if (($link["rel"] == NAMESPACE_DFRN) && ($link["href"] != "")) {
868 $data["network"] = NETWORK_DFRN;
869 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
870 $data["poll"] = $link["href"];
871 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
872 $data["url"] = $link["href"];
873 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
874 $hcard_url = $link["href"];
875 } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
876 $data["poco"] = $link["href"];
877 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && ($link["href"] != "")) {
878 $data["photo"] = $link["href"];
879 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
880 $data["baseurl"] = trim($link["href"], '/');
881 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
882 $data["guid"] = $link["href"];
883 } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
884 $data["pubkey"] = base64_decode($link["href"]);
886 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
887 if (strstr($data["pubkey"], 'RSA ')) {
888 $data["pubkey"] = rsatopem($data["pubkey"]);
893 if (is_array($webfinger["aliases"])) {
894 foreach ($webfinger["aliases"] as $alias) {
895 if (substr($alias, 0, 5) == 'acct:') {
896 $data["addr"] = substr($alias, 5);
901 if (!isset($data["network"]) || ($hcard_url == "")) {
905 // Fetch data via noscrape - this is faster
906 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
907 $data = self::pollNoscrape($noscrape_url, $data);
909 if (isset($data["notify"])
910 && isset($data["confirm"])
911 && isset($data["request"])
912 && isset($data["poll"])
913 && isset($data["name"])
914 && isset($data["photo"])
919 $data = self::pollHcard($hcard_url, $data, true);
925 * @brief Poll the hcard page (Diaspora and Friendica specific)
927 * @param string $hcard_url Link to the hcard page
928 * @param array $data The already fetched data
929 * @param boolean $dfrn Poll DFRN specific data
931 * @return array hcard data
933 private static function pollHcard($hcard_url, $data, $dfrn = false) {
934 $ret = z_fetch_url($hcard_url);
935 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
938 $content = $ret['body'];
943 $doc = new DOMDocument();
944 if (!@$doc->loadHTML($content)) {
948 $xpath = new DomXPath($doc);
950 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
951 if (!is_object($vcards)) {
955 if ($vcards->length > 0) {
956 $vcard = $vcards->item(0);
958 // We have to discard the guid from the hcard in favour of the guid from lrdd
959 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
960 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
961 if (($search->length > 0) && ($data["guid"] == "")) {
962 $data["guid"] = $search->item(0)->nodeValue;
965 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
966 if ($search->length > 0) {
967 $data["nick"] = $search->item(0)->nodeValue;
970 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
971 if ($search->length > 0) {
972 $data["name"] = $search->item(0)->nodeValue;
975 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
976 if ($search->length > 0) {
977 $data["searchable"] = $search->item(0)->nodeValue;
980 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
981 if ($search->length > 0) {
982 $data["pubkey"] = $search->item(0)->nodeValue;
983 if (strstr($data["pubkey"], 'RSA ')) {
984 $data["pubkey"] = rsatopem($data["pubkey"]);
988 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
989 if ($search->length > 0) {
990 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
995 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
996 foreach ($photos as $photo) {
998 foreach ($photo->attributes as $attribute) {
999 $attr[$attribute->name] = trim($attribute->value);
1002 if (isset($attr["src"]) && isset($attr["width"])) {
1003 $avatar[$attr["width"]] = $attr["src"];
1006 // We don't have a width. So we just take everything that we got.
1007 // This is a Hubzilla workaround which doesn't send a width.
1008 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1009 $avatar[] = $attr["src"];
1013 if (sizeof($avatar)) {
1015 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1019 // Poll DFRN specific data
1020 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1021 if ($search->length > 0) {
1022 foreach ($search as $link) {
1023 //$data["request"] = $search->item(0)->nodeValue;
1025 foreach ($link->attributes as $attribute) {
1026 $attr[$attribute->name] = trim($attribute->value);
1029 $data[substr($attr["rel"], 5)] = $attr["href"];
1033 // Older Friendica versions had used the "uid" field differently than newer versions
1034 if ($data["nick"] == $data["guid"]) {
1035 unset($data["guid"]);
1044 * @brief Check for Diaspora contact
1046 * @param array $webfinger Webfinger data
1048 * @return array Diaspora data
1050 private static function diaspora($webfinger) {
1054 foreach ($webfinger["links"] as $link) {
1055 if (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
1056 $hcard_url = $link["href"];
1057 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
1058 $data["baseurl"] = trim($link["href"], '/');
1059 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
1060 $data["guid"] = $link["href"];
1061 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
1062 $data["url"] = $link["href"];
1063 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1064 $data["poll"] = $link["href"];
1065 } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
1066 $data["poco"] = $link["href"];
1067 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1068 $data["notify"] = $link["href"];
1069 } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
1070 $data["pubkey"] = base64_decode($link["href"]);
1072 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1073 if (strstr($data["pubkey"], 'RSA ')) {
1074 $data["pubkey"] = rsatopem($data["pubkey"]);
1079 if (!isset($data["url"]) || ($hcard_url == "")) {
1083 if (is_array($webfinger["aliases"])) {
1084 foreach ($webfinger["aliases"] as $alias) {
1085 if (normalise_link($alias) != normalise_link($data["url"]) && ! strstr($alias, "@")) {
1086 $data["alias"] = $alias;
1091 // Fetch further information from the hcard
1092 $data = self::pollHcard($hcard_url, $data);
1098 if (isset($data["url"])
1099 && isset($data["guid"])
1100 && isset($data["baseurl"])
1101 && isset($data["pubkey"])
1102 && ($hcard_url != "")
1104 $data["network"] = NETWORK_DIASPORA;
1106 // The Diaspora handle must always be lowercase
1107 $data["addr"] = strtolower($data["addr"]);
1109 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1110 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1111 $data["batch"] = $data["baseurl"] . "/receive/public";
1120 * @brief Check for OStatus contact
1122 * @param array $webfinger Webfinger data
1123 * @param bool $short Short detection mode
1125 * @return array|bool OStatus data or "false" on error or "true" on short mode
1127 private static function ostatus($webfinger, $short = false) {
1129 if (is_array($webfinger["aliases"])) {
1130 foreach ($webfinger["aliases"] as $alias) {
1131 if (strstr($alias, "@")) {
1132 $data["addr"] = str_replace('acct:', '', $alias);
1137 if (is_string($webfinger["subject"]) && strstr($webfinger["subject"], "@")) {
1138 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1141 foreach ($webfinger["links"] as $link) {
1142 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1143 && ($link["type"] == "text/html")
1144 && ($link["href"] != "")
1146 $data["url"] = $link["href"];
1147 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1148 $data["notify"] = $link["href"];
1149 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1150 $data["poll"] = $link["href"];
1151 } elseif (($link["rel"] == "magic-public-key") && ($link["href"] != "")) {
1152 $pubkey = $link["href"];
1154 if (substr($pubkey, 0, 5) === 'data:') {
1155 if (strstr($pubkey, ',')) {
1156 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1158 $pubkey = substr($pubkey, 5);
1160 } elseif (normalise_link($pubkey) == 'http://') {
1161 $ret = z_fetch_url($pubkey);
1162 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1165 $pubkey = $ret['body'];
1168 $key = explode(".", $pubkey);
1170 if (sizeof($key) >= 3) {
1171 $m = base64url_decode($key[1]);
1172 $e = base64url_decode($key[2]);
1173 $data["pubkey"] = metopem($m, $e);
1178 if (isset($data["notify"]) && isset($data["pubkey"])
1179 && isset($data["poll"])
1180 && isset($data["url"])
1182 $data["network"] = NETWORK_OSTATUS;
1191 // Fetch all additional data from the feed
1192 $ret = z_fetch_url($data["poll"]);
1193 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1196 $feed = $ret['body'];
1197 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1202 if ($feed_data["header"]["author-name"] != "") {
1203 $data["name"] = $feed_data["header"]["author-name"];
1205 if ($feed_data["header"]["author-nick"] != "") {
1206 $data["nick"] = $feed_data["header"]["author-nick"];
1208 if ($feed_data["header"]["author-avatar"] != "") {
1209 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1211 if ($feed_data["header"]["author-id"] != "") {
1212 $data["alias"] = $feed_data["header"]["author-id"];
1214 if ($feed_data["header"]["author-location"] != "") {
1215 $data["location"] = $feed_data["header"]["author-location"];
1217 if ($feed_data["header"]["author-about"] != "") {
1218 $data["about"] = $feed_data["header"]["author-about"];
1220 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1221 // So we take the value that we just fetched, although the other one worked as well
1222 if ($feed_data["header"]["author-link"] != "") {
1223 $data["url"] = $feed_data["header"]["author-link"];
1226 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1227 $data['url'] = $data["alias"];
1228 $data["alias"] = '';
1231 /// @todo Fetch location and "about" from the feed as well
1236 * @brief Fetch data from a pump.io profile page
1238 * @param string $profile_link Link to the profile page
1240 * @return array profile data
1242 private static function pumpioProfileData($profile_link) {
1244 $doc = new DOMDocument();
1245 if (!@$doc->loadHTMLFile($profile_link)) {
1249 $xpath = new DomXPath($doc);
1253 // This is ugly - but pump.io doesn't seem to know a better way for it
1254 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1255 $pos = strpos($data["name"], chr(10));
1257 $data["name"] = trim(substr($data["name"], 0, $pos));
1260 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1262 foreach ($avatar->attributes as $attribute) {
1263 if ($attribute->name == "src") {
1264 $data["photo"] = trim($attribute->value);
1269 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
1270 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
1276 * @brief Check for pump.io contact
1278 * @param array $webfinger Webfinger data
1280 * @return array pump.io data
1282 private static function pumpio($webfinger) {
1285 foreach ($webfinger["links"] as $link) {
1286 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1287 && ($link["type"] == "text/html")
1288 && ($link["href"] != "")
1290 $data["url"] = $link["href"];
1291 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1292 $data["notify"] = $link["href"];
1293 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1294 $data["poll"] = $link["href"];
1295 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1296 $data["dialback"] = $link["href"];
1299 if (isset($data["poll"]) && isset($data["notify"])
1300 && isset($data["dialback"])
1301 && isset($data["url"])
1303 // by now we use these fields only for the network type detection
1304 // So we unset all data that isn't used at the moment
1305 unset($data["dialback"]);
1307 $data["network"] = NETWORK_PUMPIO;
1312 $profile_data = self::pumpioProfileData($data["url"]);
1314 if (!$profile_data) {
1318 $data = array_merge($data, $profile_data);
1324 * @brief Check page for feed link
1326 * @param string $url Page link
1328 * @return string feed link
1330 private static function getFeedLink($url) {
1331 $doc = new DOMDocument();
1333 if (!@$doc->loadHTMLFile($url)) {
1337 $xpath = new DomXPath($doc);
1339 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1340 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1341 if (!is_object($feeds)) {
1345 if ($feeds->length == 0) {
1351 foreach ($feeds as $feed) {
1353 foreach ($feed->attributes as $attribute) {
1354 $attr[$attribute->name] = trim($attribute->value);
1357 if ($feed_url == "") {
1358 $feed_url = $attr["href"];
1366 * @brief Check for feed contact
1368 * @param string $url Profile link
1369 * @param boolean $probe Do a probe if the page contains a feed link
1371 * @return array feed data
1373 private static function feed($url, $probe = true) {
1374 $ret = z_fetch_url($url);
1375 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1378 $feed = $ret['body'];
1379 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1386 $feed_url = self::getFeedLink($url);
1392 return self::feed($feed_url, false);
1395 if ($feed_data["header"]["author-name"] != "") {
1396 $data["name"] = $feed_data["header"]["author-name"];
1399 if ($feed_data["header"]["author-nick"] != "") {
1400 $data["nick"] = $feed_data["header"]["author-nick"];
1403 if ($feed_data["header"]["author-avatar"] != "") {
1404 $data["photo"] = $feed_data["header"]["author-avatar"];
1407 if ($feed_data["header"]["author-id"] != "") {
1408 $data["alias"] = $feed_data["header"]["author-id"];
1411 $data["url"] = $url;
1412 $data["poll"] = $url;
1414 if ($feed_data["header"]["author-link"] != "") {
1415 $data["baseurl"] = $feed_data["header"]["author-link"];
1417 $data["baseurl"] = $data["url"];
1420 $data["network"] = NETWORK_FEED;
1426 * @brief Check for mail contact
1428 * @param string $uri Profile link
1429 * @param integer $uid User ID
1431 * @return array mail data
1433 private static function mail($uri, $uid) {
1435 if (!validate_email($uri)) {
1439 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1441 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1443 if (dbm::is_result($x) && dbm::is_result($r)) {
1444 $mailbox = construct_mailbox_name($r[0]);
1446 openssl_private_decrypt(hex2bin($r[0]['pass']), $password, $x[0]['prvkey']);
1447 $mbox = email_connect($mailbox, $r[0]['user'], $password);
1453 $msgs = email_poll($mbox, $uri);
1454 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1456 if (!count($msgs)) {
1460 $phost = substr($uri, strpos($uri, '@') + 1);
1463 $data["addr"] = $uri;
1464 $data["network"] = NETWORK_MAIL;
1465 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1466 $data["nick"] = $data["name"];
1467 $data["photo"] = avatar_img($uri);
1468 $data["url"] = 'http://'.$phost."/".$data["nick"];
1469 $data["notify"] = 'smtp '.random_string();
1470 $data["poll"] = 'email '.random_string();
1472 $x = email_msg_meta($mbox, $msgs[0]);
1473 if (stristr($x[0]->from, $uri)) {
1474 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1475 } elseif (stristr($x[0]->to, $uri)) {
1476 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1479 foreach ($adr as $feadr) {
1480 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1481 &&(strcasecmp($feadr->host, $phost) == 0)
1482 && (strlen($feadr->personal))
1484 $personal = imap_mime_header_decode($feadr->personal);
1486 foreach ($personal as $perspart) {
1487 if ($perspart->charset != "default") {
1488 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1490 $data["name"] .= $perspart->text;
1494 $data["name"] = notags($data["name"]);
1504 * @brief Mix two paths together to possibly fix missing parts
1506 * @param string $avatar Path to the avatar
1507 * @param string $base Another path that is hopefully complete
1509 * @return string fixed avatar path
1511 public static function fixAvatar($avatar, $base) {
1512 $base_parts = parse_url($base);
1514 // Remove all parts that could create a problem
1515 unset($base_parts['path']);
1516 unset($base_parts['query']);
1517 unset($base_parts['fragment']);
1519 $avatar_parts = parse_url($avatar);
1522 $parts = array_merge($base_parts, $avatar_parts);
1524 // And put them together again
1525 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1526 $host = isset($parts['host']) ? $parts['host'] : '';
1527 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1528 $path = isset($parts['path']) ? $parts['path'] : '';
1529 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1530 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1532 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1534 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);