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;
22 require_once 'include/feed.php';
23 require_once 'include/email.php';
24 require_once 'include/network.php';
27 * @brief This class contain functions for probing URL
32 private static $baseurl;
35 * @brief Rearrange the array so that it always has the same order
37 * @param array $data Unordered data
39 * @return array Ordered data
41 private static function rearrangeData($data) {
42 $fields = array("name", "nick", "guid", "url", "addr", "alias",
43 "photo", "community", "keywords", "location", "about",
44 "batch", "notify", "poll", "request", "confirm", "poco",
45 "priority", "network", "pubkey", "baseurl");
48 foreach ($fields as $field) {
49 if (isset($data[$field])) {
50 $newdata[$field] = $data[$field];
52 $newdata[$field] = "";
56 // We don't use the "priority" field anymore and replace it with a dummy.
57 $newdata["priority"] = 0;
63 * @brief Check if the hostname belongs to the own server
65 * @param string $host The hostname that is to be checked
67 * @return bool Does the testes hostname belongs to the own server?
69 private static function ownHost($host) {
70 $own_host = get_app()->get_hostname();
72 $parts = parse_url($host);
74 if (!isset($parts['scheme'])) {
75 $parts = parse_url('http://'.$host);
78 if (!isset($parts['host'])) {
81 return $parts['host'] == $own_host;
85 * @brief Probes for XRD data
87 * @param string $host The host part of an url
90 * 'lrdd' => Link to LRDD endpoint
91 * 'lrdd-xml' => Link to LRDD endpoint in XML format
92 * 'lrdd-json' => Link to LRDD endpoint in JSON format
94 private static function xrd($host) {
96 // Reset the static variable
99 $ssl_url = "https://".$host."/.well-known/host-meta";
100 $url = "http://".$host."/.well-known/host-meta";
102 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
105 logger("Probing for ".$host, LOGGER_DEBUG);
107 $ret = z_fetch_url($ssl_url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
108 if ($ret['success']) {
110 $xrd = parse_xml_string($xml, false);
113 if (!is_object($xrd)) {
114 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
115 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
116 logger("Probing timeout for ".$url, LOGGER_DEBUG);
120 $xrd = parse_xml_string($xml, false);
122 if (!is_object($xrd)) {
123 logger("No xrd object found for ".$host, LOGGER_DEBUG);
127 $links = xml::element_to_array($xrd);
128 if (!isset($links["xrd"]["link"])) {
129 logger("No xrd data found for ".$host, LOGGER_DEBUG);
135 foreach ($links["xrd"]["link"] as $value => $link) {
136 if (!empty($link["@attributes"])) {
137 $attributes = $link["@attributes"];
138 } elseif ($value == "@attributes") {
144 if (($attributes["rel"] == "lrdd")
145 && ($attributes["type"] == "application/xrd+xml")
147 $xrd_data["lrdd-xml"] = $attributes["template"];
148 } elseif (($attributes["rel"] == "lrdd")
149 && ($attributes["type"] == "application/json")
151 $xrd_data["lrdd-json"] = $attributes["template"];
152 } elseif ($attributes["rel"] == "lrdd") {
153 $xrd_data["lrdd"] = $attributes["template"];
157 self::$baseurl = "http://".$host;
159 logger("Probing successful for ".$host, LOGGER_DEBUG);
165 * @brief Perform Webfinger lookup and return DFRN data
167 * Given an email style address, perform webfinger lookup and
168 * return the resulting DFRN profile URL, or if no DFRN profile URL
169 * is located, returns an OStatus subscription template (prefixed
170 * with the string 'stat:' to identify it as on OStatus template).
171 * If this isn't an email style address just return $webbie.
172 * Return an empty string if email-style addresses but webfinger fails,
173 * or if the resultant personal XRD doesn't contain a supported
174 * subscription/friend-request attribute.
176 * amended 7/9/2011 to return an hcard which could save potentially loading
177 * a lengthy content page to scrape dfrn attributes
179 * @param string $webbie Address that should be probed
180 * @param string $hcard_url Link to the hcard - is returned by reference
182 * @return string profile link
184 public static function webfingerDfrn($webbie, &$hcard_url) {
188 $links = self::lrdd($webbie);
189 logger('webfingerDfrn: '.$webbie.':'.print_r($links, true), LOGGER_DATA);
191 foreach ($links as $link) {
192 if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
193 $profile_link = $link['@attributes']['href'];
195 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) && ($profile_link == "")) {
196 $profile_link = 'stat:'.$link['@attributes']['template'];
198 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
199 $hcard_url = $link['@attributes']['href'];
203 return $profile_link;
207 * @brief Check an URI for LRDD data
209 * this is a replacement for the "lrdd" function in include/network.php.
210 * It isn't used in this class and has some redundancies in the code.
211 * When time comes we can check the existing calls for "lrdd" if we can rework them.
213 * @param string $uri Address that should be probed
215 * @return array uri data
217 public static function lrdd($uri) {
219 $lrdd = self::xrd($uri);
222 if (is_bool($lrdd)) {
227 $parts = @parse_url($uri);
232 $host = $parts["host"];
233 if (!empty($parts["port"])) {
234 $host .= ':'.$parts["port"];
237 $path_parts = explode("/", trim($parts["path"], "/"));
239 $nick = array_pop($path_parts);
242 $lrdd = self::xrd($host);
243 $host .= "/".array_shift($path_parts);
244 } while (!$lrdd && (sizeof($path_parts) > 0));
248 logger("No lrdd data found for ".$uri, LOGGER_DEBUG);
252 foreach ($lrdd as $key => $link) {
257 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
261 $path = str_replace('{uri}', urlencode($uri), $link);
262 $webfinger = self::webfinger($path);
264 if (!$webfinger && (strstr($uri, "@"))) {
265 $path = str_replace('{uri}', urlencode("acct:".$uri), $link);
266 $webfinger = self::webfinger($path);
269 // Special treatment for Mastodon
270 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
271 // But the webfinger for this format fails.
272 if (!$webfinger && !empty($nick)) {
273 // Mastodon uses a "@" as prefix for usernames in their url format
274 $nick = ltrim($nick, '@');
276 $addr = $nick."@".$host;
278 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
279 $webfinger = self::webfinger($path);
283 if (!is_array($webfinger["links"])) {
284 logger("No webfinger links found for ".$uri, LOGGER_DEBUG);
290 foreach ($webfinger["links"] as $link) {
291 $data[] = array("@attributes" => $link);
294 if (is_array($webfinger["aliases"])) {
295 foreach ($webfinger["aliases"] as $alias) {
296 $data[] = array("@attributes" =>
297 array("rel" => "alias",
306 * @brief Fetch information (protocol endpoints and user information) about a given uri
308 * @param string $uri Address that should be probed
309 * @param string $network Test for this specific network
310 * @param integer $uid User ID for the probe (only used for mails)
311 * @param boolean $cache Use cached values?
313 * @return array uri data
315 public static function uri($uri, $network = "", $uid = 0, $cache = true) {
318 $result = Cache::get("probe_url:".$network.":".$uri);
319 if (!is_null($result)) {
328 $data = self::detect($uri, $network, $uid);
330 if (!isset($data["url"])) {
334 if ($data["photo"] != "") {
335 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
337 $data["photo"] = System::baseUrl().'/images/person-175.jpg';
340 if (empty($data["name"])) {
341 if (!empty($data["nick"])) {
342 $data["name"] = $data["nick"];
345 if ($data["name"] == "") {
346 $data["name"] = $data["url"];
350 if (empty($data["nick"])) {
351 $data["nick"] = strtolower($data["name"]);
353 if (strpos($data['nick'], ' ')) {
354 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
358 if (self::$baseurl != "") {
359 $data["baseurl"] = self::$baseurl;
362 if (!isset($data["network"])) {
363 $data["network"] = NETWORK_PHANTOM;
366 $data = self::rearrangeData($data);
368 // Only store into the cache if the value seems to be valid
369 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
370 Cache::set("probe_url:".$network.":".$uri, $data, CACHE_DAY);
372 /// @todo temporary fix - we need a real contact update function that updates only changing fields
373 /// The biggest problem is the avatar picture that could have a reduced image size.
374 /// It should only be updated if the existing picture isn't existing anymore.
375 /// We only update the contact when it is no probing for a specific network.
376 if (($data['network'] != NETWORK_FEED)
384 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `url` = '%s', `addr` = '%s',
385 `notify` = '%s', `poll` = '%s', `alias` = '%s', `success_update` = '%s'
386 WHERE `nurl` = '%s' AND NOT `self` AND `uid` = 0",
387 dbesc($data["name"]),
388 dbesc($data["nick"]),
390 dbesc($data["addr"]),
391 dbesc($data["notify"]),
392 dbesc($data["poll"]),
393 dbesc($data["alias"]),
394 dbesc(datetime_convert()),
395 dbesc(normalise_link($data['url']))
404 * @brief Switch the scheme of an url between http and https
406 * @param string $url URL
408 * @return string switched URL
410 private static function switchScheme($url) {
411 $parts = parse_url($url);
413 if (!isset($parts['scheme'])) {
417 if ($parts['scheme'] == 'http') {
418 $url = str_replace('http://', 'https://', $url);
419 } elseif ($parts['scheme'] == 'https') {
420 $url = str_replace('https://', 'http://', $url);
427 * @brief Checks if a profile url should be OStatus but only provides partial information
429 * @param array $webfinger Webfinger data
430 * @param string $lrdd Path template for webfinger request
432 * @return array fixed webfinger data
434 private static function fixOstatus($webfinger, $lrdd) {
435 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
442 foreach ($webfinger['links'] as $link) {
443 if ($link['rel'] == NAMESPACE_OSTATUSSUB) {
446 if ($link['rel'] == 'magic-public-key') {
451 if (!$is_ostatus || $has_key) {
455 $url = self::switchScheme($webfinger['subject']);
456 $path = str_replace('{uri}', urlencode($url), $lrdd);
457 $webfinger2 = self::webfinger($path);
459 // Is the new webfinger detectable as OStatus?
460 if (self::ostatus($webfinger2, true)) {
461 $webfinger = $webfinger2;
468 * @brief Fetch information (protocol endpoints and user information) about a given uri
470 * This function is only called by the "uri" function that adds caching and rearranging of data.
472 * @param string $uri Address that should be probed
473 * @param string $network Test for this specific network
474 * @param integer $uid User ID for the probe (only used for mails)
476 * @return array uri data
478 private static function detect($uri, $network, $uid) {
479 $parts = parse_url($uri);
481 if (!empty($parts["scheme"]) && !empty($parts["host"]) && !empty($parts["path"])) {
482 $host = $parts["host"];
483 if (!empty($parts["port"])) {
484 $host .= ':'.$parts["port"];
487 if ($host == 'twitter.com') {
488 return array("network" => NETWORK_TWITTER);
490 $lrdd = self::xrd($host);
492 if (is_bool($lrdd)) {
496 $path_parts = explode("/", trim($parts["path"], "/"));
498 while (!$lrdd && (sizeof($path_parts) > 1)) {
499 $host .= "/".array_shift($path_parts);
500 $lrdd = self::xrd($host);
503 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
504 return self::feed($uri);
506 $nick = array_pop($path_parts);
508 // Mastodon uses a "@" as prefix for usernames in their url format
509 $nick = ltrim($nick, '@');
511 $addr = $nick."@".$host;
513 } elseif (strstr($uri, '@')) {
514 // If the URI starts with "mailto:" then jump directly to the mail detection
515 if (strpos($uri, 'mailto:') !== false) {
516 $uri = str_replace('mailto:', '', $uri);
517 return self::mail($uri, $uid);
520 if ($network == NETWORK_MAIL) {
521 return self::mail($uri, $uid);
523 // Remove "acct:" from the URI
524 $uri = str_replace('acct:', '', $uri);
526 $host = substr($uri, strpos($uri, '@') + 1);
527 $nick = substr($uri, 0, strpos($uri, '@'));
529 if (strpos($uri, '@twitter.com')) {
530 return array("network" => NETWORK_TWITTER);
532 $lrdd = self::xrd($host);
534 if (is_bool($lrdd)) {
539 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
540 return self::mail($uri, $uid);
545 logger("Uri ".$uri." was not detectable", LOGGER_DEBUG);
551 /// @todo Do we need the prefix "acct:" or "acct://"?
553 foreach ($lrdd as $key => $link) {
557 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
560 // At first try it with the given uri
561 $path = str_replace('{uri}', urlencode($uri), $link);
562 $webfinger = self::webfinger($path);
564 // Fix possible problems with GNU Social probing to wrong scheme
565 $webfinger = self::fixOstatus($webfinger, $link);
567 // We cannot be sure that the detected address was correct, so we don't use the values
568 if ($webfinger && ($uri != $addr)) {
573 // Try webfinger with the address (user@domain.tld)
575 $path = str_replace('{uri}', urlencode($addr), $link);
576 $webfinger = self::webfinger($path);
579 // Mastodon needs to have it with "acct:"
581 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
582 $webfinger = self::webfinger($path);
586 return self::feed($uri);
591 logger("Probing ".$uri, LOGGER_DEBUG);
593 if (in_array($network, array("", NETWORK_DFRN))) {
594 $result = self::dfrn($webfinger);
596 if ((!$result && ($network == "")) || ($network == NETWORK_DIASPORA)) {
597 $result = self::diaspora($webfinger);
599 if ((!$result && ($network == "")) || ($network == NETWORK_OSTATUS)) {
600 $result = self::ostatus($webfinger);
602 if ((!$result && ($network == "")) || ($network == NETWORK_PUMPIO)) {
603 $result = self::pumpio($webfinger);
605 if ((!$result && ($network == "")) || ($network == NETWORK_FEED)) {
606 $result = self::feed($uri);
608 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
609 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
610 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
611 $result["nick"] = $nick;
614 if (empty($result["addr"]) && ($addr != "")) {
615 $result["addr"] = $addr;
619 logger($uri." is ".$result["network"], LOGGER_DEBUG);
621 if (empty($result["baseurl"])) {
622 $pos = strpos($result["url"], $host);
624 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
632 * @brief Perform a webfinger request.
634 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
636 * @param string $url Address that should be probed
638 * @return array webfinger data
640 private static function webfinger($url) {
642 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
645 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
646 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
649 $data = $ret['body'];
651 $xrd = parse_xml_string($data, false);
653 if (!is_object($xrd)) {
654 // If it is not XML, maybe it is JSON
655 $webfinger = json_decode($data, true);
657 if (!isset($webfinger["links"])) {
658 logger("No json webfinger links for ".$url, LOGGER_DEBUG);
665 $xrd_arr = xml::element_to_array($xrd);
666 if (!isset($xrd_arr["xrd"]["link"])) {
667 logger("No XML webfinger links for ".$url, LOGGER_DEBUG);
671 $webfinger = array();
673 if (!empty($xrd_arr["xrd"]["subject"])) {
674 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
677 if (!empty($xrd_arr["xrd"]["alias"])) {
678 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
681 $webfinger["links"] = array();
683 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
684 if (!empty($data["@attributes"])) {
685 $attributes = $data["@attributes"];
686 } elseif ($value == "@attributes") {
692 $webfinger["links"][] = $attributes;
698 * @brief Poll the Friendica specific noscrape page.
700 * "noscrape" is a faster alternative to fetch the data from the hcard.
701 * This functionality was originally created for the directory.
703 * @param string $noscrape_url Link to the noscrape page
704 * @param array $data The already fetched data
706 * @return array noscrape data
708 private static function pollNoscrape($noscrape_url, $data) {
709 $ret = z_fetch_url($noscrape_url);
710 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
713 $content = $ret['body'];
715 logger("Empty body for ".$noscrape_url, LOGGER_DEBUG);
719 $json = json_decode($content, true);
720 if (!is_array($json)) {
721 logger("No json data for ".$noscrape_url, LOGGER_DEBUG);
725 if (!empty($json["fn"])) {
726 $data["name"] = $json["fn"];
729 if (!empty($json["addr"])) {
730 $data["addr"] = $json["addr"];
733 if (!empty($json["nick"])) {
734 $data["nick"] = $json["nick"];
737 if (!empty($json["comm"])) {
738 $data["community"] = $json["comm"];
741 if (!empty($json["tags"])) {
742 $keywords = implode(" ", $json["tags"]);
743 if ($keywords != "") {
744 $data["keywords"] = $keywords;
748 $location = formatted_location($json);
750 $data["location"] = $location;
753 if (!empty($json["about"])) {
754 $data["about"] = $json["about"];
757 if (!empty($json["key"])) {
758 $data["pubkey"] = $json["key"];
761 if (!empty($json["photo"])) {
762 $data["photo"] = $json["photo"];
765 if (!empty($json["dfrn-request"])) {
766 $data["request"] = $json["dfrn-request"];
769 if (!empty($json["dfrn-confirm"])) {
770 $data["confirm"] = $json["dfrn-confirm"];
773 if (!empty($json["dfrn-notify"])) {
774 $data["notify"] = $json["dfrn-notify"];
777 if (!empty($json["dfrn-poll"])) {
778 $data["poll"] = $json["dfrn-poll"];
785 * @brief Check for valid DFRN data
787 * @param array $data DFRN data
789 * @return int Number of errors
791 public static function validDfrn($data) {
793 if (!isset($data['key'])) {
796 if (!isset($data['dfrn-request'])) {
799 if (!isset($data['dfrn-confirm'])) {
802 if (!isset($data['dfrn-notify'])) {
805 if (!isset($data['dfrn-poll'])) {
812 * @brief Fetch data from a DFRN profile page and via "noscrape"
814 * @param string $profile_link Link to the profile page
816 * @return array profile data
818 public static function profile($profile_link) {
822 logger("Check profile ".$profile_link, LOGGER_DEBUG);
824 // Fetch data via noscrape - this is faster
825 $noscrape_url = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile_link);
826 $data = self::pollNoscrape($noscrape_url, $data);
828 if (!isset($data["notify"])
829 || !isset($data["confirm"])
830 || !isset($data["request"])
831 || !isset($data["poll"])
832 || !isset($data["poco"])
833 || !isset($data["name"])
834 || !isset($data["photo"])
836 $data = self::pollHcard($profile_link, $data, true);
839 $prof_data = array();
840 $prof_data["addr"] = $data["addr"];
841 $prof_data["nick"] = $data["nick"];
842 $prof_data["dfrn-request"] = $data["request"];
843 $prof_data["dfrn-confirm"] = $data["confirm"];
844 $prof_data["dfrn-notify"] = $data["notify"];
845 $prof_data["dfrn-poll"] = $data["poll"];
846 $prof_data["dfrn-poco"] = $data["poco"];
847 $prof_data["photo"] = $data["photo"];
848 $prof_data["fn"] = $data["name"];
849 $prof_data["key"] = $data["pubkey"];
851 logger("Result for profile ".$profile_link.": ".print_r($prof_data, true), LOGGER_DEBUG);
857 * @brief Check for DFRN contact
859 * @param array $webfinger Webfinger data
861 * @return array DFRN data
863 private static function dfrn($webfinger) {
867 foreach ($webfinger["links"] as $link) {
868 if (($link["rel"] == NAMESPACE_DFRN) && ($link["href"] != "")) {
869 $data["network"] = NETWORK_DFRN;
870 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
871 $data["poll"] = $link["href"];
872 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
873 $data["url"] = $link["href"];
874 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
875 $hcard_url = $link["href"];
876 } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
877 $data["poco"] = $link["href"];
878 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && ($link["href"] != "")) {
879 $data["photo"] = $link["href"];
880 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
881 $data["baseurl"] = trim($link["href"], '/');
882 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
883 $data["guid"] = $link["href"];
884 } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
885 $data["pubkey"] = base64_decode($link["href"]);
887 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
888 if (strstr($data["pubkey"], 'RSA ')) {
889 $data["pubkey"] = rsatopem($data["pubkey"]);
894 if (is_array($webfinger["aliases"])) {
895 foreach ($webfinger["aliases"] as $alias) {
896 if (substr($alias, 0, 5) == 'acct:') {
897 $data["addr"] = substr($alias, 5);
902 if (!isset($data["network"]) || ($hcard_url == "")) {
906 // Fetch data via noscrape - this is faster
907 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
908 $data = self::pollNoscrape($noscrape_url, $data);
910 if (isset($data["notify"])
911 && isset($data["confirm"])
912 && isset($data["request"])
913 && isset($data["poll"])
914 && isset($data["name"])
915 && isset($data["photo"])
920 $data = self::pollHcard($hcard_url, $data, true);
926 * @brief Poll the hcard page (Diaspora and Friendica specific)
928 * @param string $hcard_url Link to the hcard page
929 * @param array $data The already fetched data
930 * @param boolean $dfrn Poll DFRN specific data
932 * @return array hcard data
934 private static function pollHcard($hcard_url, $data, $dfrn = false) {
935 $ret = z_fetch_url($hcard_url);
936 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
939 $content = $ret['body'];
944 $doc = new DOMDocument();
945 if (!@$doc->loadHTML($content)) {
949 $xpath = new DomXPath($doc);
951 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
952 if (!is_object($vcards)) {
956 if ($vcards->length > 0) {
957 $vcard = $vcards->item(0);
959 // We have to discard the guid from the hcard in favour of the guid from lrdd
960 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
961 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
962 if (($search->length > 0) && ($data["guid"] == "")) {
963 $data["guid"] = $search->item(0)->nodeValue;
966 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
967 if ($search->length > 0) {
968 $data["nick"] = $search->item(0)->nodeValue;
971 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
972 if ($search->length > 0) {
973 $data["name"] = $search->item(0)->nodeValue;
976 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
977 if ($search->length > 0) {
978 $data["searchable"] = $search->item(0)->nodeValue;
981 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
982 if ($search->length > 0) {
983 $data["pubkey"] = $search->item(0)->nodeValue;
984 if (strstr($data["pubkey"], 'RSA ')) {
985 $data["pubkey"] = rsatopem($data["pubkey"]);
989 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
990 if ($search->length > 0) {
991 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
996 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
997 foreach ($photos as $photo) {
999 foreach ($photo->attributes as $attribute) {
1000 $attr[$attribute->name] = trim($attribute->value);
1003 if (isset($attr["src"]) && isset($attr["width"])) {
1004 $avatar[$attr["width"]] = $attr["src"];
1007 // We don't have a width. So we just take everything that we got.
1008 // This is a Hubzilla workaround which doesn't send a width.
1009 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1010 $avatar[] = $attr["src"];
1014 if (sizeof($avatar)) {
1016 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1020 // Poll DFRN specific data
1021 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1022 if ($search->length > 0) {
1023 foreach ($search as $link) {
1024 //$data["request"] = $search->item(0)->nodeValue;
1026 foreach ($link->attributes as $attribute) {
1027 $attr[$attribute->name] = trim($attribute->value);
1030 $data[substr($attr["rel"], 5)] = $attr["href"];
1034 // Older Friendica versions had used the "uid" field differently than newer versions
1035 if ($data["nick"] == $data["guid"]) {
1036 unset($data["guid"]);
1045 * @brief Check for Diaspora contact
1047 * @param array $webfinger Webfinger data
1049 * @return array Diaspora data
1051 private static function diaspora($webfinger) {
1055 foreach ($webfinger["links"] as $link) {
1056 if (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
1057 $hcard_url = $link["href"];
1058 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
1059 $data["baseurl"] = trim($link["href"], '/');
1060 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
1061 $data["guid"] = $link["href"];
1062 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
1063 $data["url"] = $link["href"];
1064 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1065 $data["poll"] = $link["href"];
1066 } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
1067 $data["poco"] = $link["href"];
1068 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1069 $data["notify"] = $link["href"];
1070 } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
1071 $data["pubkey"] = base64_decode($link["href"]);
1073 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1074 if (strstr($data["pubkey"], 'RSA ')) {
1075 $data["pubkey"] = rsatopem($data["pubkey"]);
1080 if (!isset($data["url"]) || ($hcard_url == "")) {
1084 if (is_array($webfinger["aliases"])) {
1085 foreach ($webfinger["aliases"] as $alias) {
1086 if (normalise_link($alias) != normalise_link($data["url"]) && ! strstr($alias, "@")) {
1087 $data["alias"] = $alias;
1092 // Fetch further information from the hcard
1093 $data = self::pollHcard($hcard_url, $data);
1099 if (isset($data["url"])
1100 && isset($data["guid"])
1101 && isset($data["baseurl"])
1102 && isset($data["pubkey"])
1103 && ($hcard_url != "")
1105 $data["network"] = NETWORK_DIASPORA;
1107 // The Diaspora handle must always be lowercase
1108 $data["addr"] = strtolower($data["addr"]);
1110 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1111 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1112 $data["batch"] = $data["baseurl"] . "/receive/public";
1121 * @brief Check for OStatus contact
1123 * @param array $webfinger Webfinger data
1124 * @param bool $short Short detection mode
1126 * @return array|bool OStatus data or "false" on error or "true" on short mode
1128 private static function ostatus($webfinger, $short = false) {
1130 if (is_array($webfinger["aliases"])) {
1131 foreach ($webfinger["aliases"] as $alias) {
1132 if (strstr($alias, "@")) {
1133 $data["addr"] = str_replace('acct:', '', $alias);
1138 if (is_string($webfinger["subject"]) && strstr($webfinger["subject"], "@")) {
1139 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1142 foreach ($webfinger["links"] as $link) {
1143 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1144 && ($link["type"] == "text/html")
1145 && ($link["href"] != "")
1147 $data["url"] = $link["href"];
1148 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1149 $data["notify"] = $link["href"];
1150 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1151 $data["poll"] = $link["href"];
1152 } elseif (($link["rel"] == "magic-public-key") && ($link["href"] != "")) {
1153 $pubkey = $link["href"];
1155 if (substr($pubkey, 0, 5) === 'data:') {
1156 if (strstr($pubkey, ',')) {
1157 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1159 $pubkey = substr($pubkey, 5);
1161 } elseif (normalise_link($pubkey) == 'http://') {
1162 $ret = z_fetch_url($pubkey);
1163 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1166 $pubkey = $ret['body'];
1169 $key = explode(".", $pubkey);
1171 if (sizeof($key) >= 3) {
1172 $m = base64url_decode($key[1]);
1173 $e = base64url_decode($key[2]);
1174 $data["pubkey"] = metopem($m, $e);
1179 if (isset($data["notify"]) && isset($data["pubkey"])
1180 && isset($data["poll"])
1181 && isset($data["url"])
1183 $data["network"] = NETWORK_OSTATUS;
1192 // Fetch all additional data from the feed
1193 $ret = z_fetch_url($data["poll"]);
1194 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1197 $feed = $ret['body'];
1198 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1203 if ($feed_data["header"]["author-name"] != "") {
1204 $data["name"] = $feed_data["header"]["author-name"];
1206 if ($feed_data["header"]["author-nick"] != "") {
1207 $data["nick"] = $feed_data["header"]["author-nick"];
1209 if ($feed_data["header"]["author-avatar"] != "") {
1210 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1212 if ($feed_data["header"]["author-id"] != "") {
1213 $data["alias"] = $feed_data["header"]["author-id"];
1215 if ($feed_data["header"]["author-location"] != "") {
1216 $data["location"] = $feed_data["header"]["author-location"];
1218 if ($feed_data["header"]["author-about"] != "") {
1219 $data["about"] = $feed_data["header"]["author-about"];
1221 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1222 // So we take the value that we just fetched, although the other one worked as well
1223 if ($feed_data["header"]["author-link"] != "") {
1224 $data["url"] = $feed_data["header"]["author-link"];
1227 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1228 $data['url'] = $data["alias"];
1229 $data["alias"] = '';
1232 /// @todo Fetch location and "about" from the feed as well
1237 * @brief Fetch data from a pump.io profile page
1239 * @param string $profile_link Link to the profile page
1241 * @return array profile data
1243 private static function pumpioProfileData($profile_link) {
1245 $doc = new DOMDocument();
1246 if (!@$doc->loadHTMLFile($profile_link)) {
1250 $xpath = new DomXPath($doc);
1254 // This is ugly - but pump.io doesn't seem to know a better way for it
1255 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1256 $pos = strpos($data["name"], chr(10));
1258 $data["name"] = trim(substr($data["name"], 0, $pos));
1261 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1263 foreach ($avatar->attributes as $attribute) {
1264 if ($attribute->name == "src") {
1265 $data["photo"] = trim($attribute->value);
1270 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
1271 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
1277 * @brief Check for pump.io contact
1279 * @param array $webfinger Webfinger data
1281 * @return array pump.io data
1283 private static function pumpio($webfinger) {
1286 foreach ($webfinger["links"] as $link) {
1287 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1288 && ($link["type"] == "text/html")
1289 && ($link["href"] != "")
1291 $data["url"] = $link["href"];
1292 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1293 $data["notify"] = $link["href"];
1294 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1295 $data["poll"] = $link["href"];
1296 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1297 $data["dialback"] = $link["href"];
1300 if (isset($data["poll"]) && isset($data["notify"])
1301 && isset($data["dialback"])
1302 && isset($data["url"])
1304 // by now we use these fields only for the network type detection
1305 // So we unset all data that isn't used at the moment
1306 unset($data["dialback"]);
1308 $data["network"] = NETWORK_PUMPIO;
1313 $profile_data = self::pumpioProfileData($data["url"]);
1315 if (!$profile_data) {
1319 $data = array_merge($data, $profile_data);
1325 * @brief Check page for feed link
1327 * @param string $url Page link
1329 * @return string feed link
1331 private static function getFeedLink($url) {
1332 $doc = new DOMDocument();
1334 if (!@$doc->loadHTMLFile($url)) {
1338 $xpath = new DomXPath($doc);
1340 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1341 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1342 if (!is_object($feeds)) {
1346 if ($feeds->length == 0) {
1352 foreach ($feeds as $feed) {
1354 foreach ($feed->attributes as $attribute) {
1355 $attr[$attribute->name] = trim($attribute->value);
1358 if ($feed_url == "") {
1359 $feed_url = $attr["href"];
1367 * @brief Check for feed contact
1369 * @param string $url Profile link
1370 * @param boolean $probe Do a probe if the page contains a feed link
1372 * @return array feed data
1374 private static function feed($url, $probe = true) {
1375 $ret = z_fetch_url($url);
1376 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1379 $feed = $ret['body'];
1380 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1387 $feed_url = self::getFeedLink($url);
1393 return self::feed($feed_url, false);
1396 if ($feed_data["header"]["author-name"] != "") {
1397 $data["name"] = $feed_data["header"]["author-name"];
1400 if ($feed_data["header"]["author-nick"] != "") {
1401 $data["nick"] = $feed_data["header"]["author-nick"];
1404 if ($feed_data["header"]["author-avatar"] != "") {
1405 $data["photo"] = $feed_data["header"]["author-avatar"];
1408 if ($feed_data["header"]["author-id"] != "") {
1409 $data["alias"] = $feed_data["header"]["author-id"];
1412 $data["url"] = $url;
1413 $data["poll"] = $url;
1415 if ($feed_data["header"]["author-link"] != "") {
1416 $data["baseurl"] = $feed_data["header"]["author-link"];
1418 $data["baseurl"] = $data["url"];
1421 $data["network"] = NETWORK_FEED;
1427 * @brief Check for mail contact
1429 * @param string $uri Profile link
1430 * @param integer $uid User ID
1432 * @return array mail data
1434 private static function mail($uri, $uid) {
1436 if (!validate_email($uri)) {
1440 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1442 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1444 if (dbm::is_result($x) && dbm::is_result($r)) {
1445 $mailbox = construct_mailbox_name($r[0]);
1447 openssl_private_decrypt(hex2bin($r[0]['pass']), $password, $x[0]['prvkey']);
1448 $mbox = email_connect($mailbox, $r[0]['user'], $password);
1454 $msgs = email_poll($mbox, $uri);
1455 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1457 if (!count($msgs)) {
1461 $phost = substr($uri, strpos($uri, '@') + 1);
1464 $data["addr"] = $uri;
1465 $data["network"] = NETWORK_MAIL;
1466 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1467 $data["nick"] = $data["name"];
1468 $data["photo"] = avatar_img($uri);
1469 $data["url"] = 'http://'.$phost."/".$data["nick"];
1470 $data["notify"] = 'smtp '.random_string();
1471 $data["poll"] = 'email '.random_string();
1473 $x = email_msg_meta($mbox, $msgs[0]);
1474 if (stristr($x[0]->from, $uri)) {
1475 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1476 } elseif (stristr($x[0]->to, $uri)) {
1477 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1480 foreach ($adr as $feadr) {
1481 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1482 &&(strcasecmp($feadr->host, $phost) == 0)
1483 && (strlen($feadr->personal))
1485 $personal = imap_mime_header_decode($feadr->personal);
1487 foreach ($personal as $perspart) {
1488 if ($perspart->charset != "default") {
1489 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1491 $data["name"] .= $perspart->text;
1495 $data["name"] = notags($data["name"]);
1505 * @brief Mix two paths together to possibly fix missing parts
1507 * @param string $avatar Path to the avatar
1508 * @param string $base Another path that is hopefully complete
1510 * @return string fixed avatar path
1512 public static function fixAvatar($avatar, $base) {
1513 $base_parts = parse_url($base);
1515 // Remove all parts that could create a problem
1516 unset($base_parts['path']);
1517 unset($base_parts['query']);
1518 unset($base_parts['fragment']);
1520 $avatar_parts = parse_url($avatar);
1523 $parts = array_merge($base_parts, $avatar_parts);
1525 // And put them together again
1526 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1527 $host = isset($parts['host']) ? $parts['host'] : '';
1528 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1529 $path = isset($parts['path']) ? $parts['path'] : '';
1530 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1531 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1533 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1535 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);