3 * @file src/Network/Probe.php
5 namespace Friendica\Network;
8 * @file src/Network/Probe.php
9 * @brief Functions for probing URL
13 use Friendica\Core\System;
14 use Friendica\Core\Cache;
15 use Friendica\Core\Config;
16 use Friendica\Database\DBM;
17 use Friendica\Model\Profile;
18 use Friendica\Protocol\Email;
19 use Friendica\Protocol\Feed;
20 use Friendica\Util\Crypto;
21 use Friendica\Util\Network;
22 use Friendica\Util\XML;
28 require_once 'include/dba.php';
31 * @brief This class contain functions for probing URL
36 private static $baseurl;
39 * @brief Rearrange the array so that it always has the same order
41 * @param array $data Unordered data
43 * @return array Ordered data
45 private static function rearrangeData($data)
47 $fields = ["name", "nick", "guid", "url", "addr", "alias",
48 "photo", "community", "keywords", "location", "about",
49 "batch", "notify", "poll", "request", "confirm", "poco",
50 "priority", "network", "pubkey", "baseurl"];
53 foreach ($fields as $field) {
54 if (isset($data[$field])) {
55 $newdata[$field] = $data[$field];
57 $newdata[$field] = "";
61 // We don't use the "priority" field anymore and replace it with a dummy.
62 $newdata["priority"] = 0;
68 * @brief Check if the hostname belongs to the own server
70 * @param string $host The hostname that is to be checked
72 * @return bool Does the testes hostname belongs to the own server?
74 private static function ownHost($host)
76 $own_host = get_app()->get_hostname();
78 $parts = parse_url($host);
80 if (!isset($parts['scheme'])) {
81 $parts = parse_url('http://'.$host);
84 if (!isset($parts['host'])) {
87 return $parts['host'] == $own_host;
91 * @brief Probes for webfinger path via "host-meta"
93 * We have to check if the servers in the future still will offer this.
94 * It seems as if it was dropped from the standard.
96 * @param string $host The host part of an url
98 * @return array with template and type of the webfinger template for JSON or XML
100 private static function hostMeta($host)
102 // Reset the static variable
105 $ssl_url = "https://".$host."/.well-known/host-meta";
106 $url = "http://".$host."/.well-known/host-meta";
108 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
111 logger("Probing for ".$host, LOGGER_DEBUG);
113 $ret = Network::curl($ssl_url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
114 if ($ret['success']) {
116 $xrd = XML::parseString($xml, false);
117 $host_url = 'https://'.$host;
120 if (!is_object($xrd)) {
121 $ret = Network::curl($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
122 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
123 logger("Probing timeout for ".$url, LOGGER_DEBUG);
127 $xrd = XML::parseString($xml, false);
128 $host_url = 'http://'.$host;
130 if (!is_object($xrd)) {
131 logger("No xrd object found for ".$host, LOGGER_DEBUG);
135 $links = XML::elementToArray($xrd);
136 if (!isset($links["xrd"]["link"])) {
137 logger("No xrd data found for ".$host, LOGGER_DEBUG);
142 // The following webfinger path is defined in RFC 7033 https://tools.ietf.org/html/rfc7033
143 // Problem is that Hubzilla currently doesn't provide all data in the JSON webfinger
144 // compared to the XML webfinger. So this is commented out by now.
145 // $lrdd = array("application/jrd+json" => $host_url.'/.well-known/webfinger?resource={uri}');
147 foreach ($links["xrd"]["link"] as $value => $link) {
148 if (!empty($link["@attributes"])) {
149 $attributes = $link["@attributes"];
150 } elseif ($value == "@attributes") {
156 if (($attributes["rel"] == "lrdd") && !empty($attributes["template"])) {
157 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
159 $lrdd[$type] = $attributes["template"];
163 self::$baseurl = "http://".$host;
165 logger("Probing successful for ".$host, LOGGER_DEBUG);
171 * @brief Perform Webfinger lookup and return DFRN data
173 * Given an email style address, perform webfinger lookup and
174 * return the resulting DFRN profile URL, or if no DFRN profile URL
175 * is located, returns an OStatus subscription template (prefixed
176 * with the string 'stat:' to identify it as on OStatus template).
177 * If this isn't an email style address just return $webbie.
178 * Return an empty string if email-style addresses but webfinger fails,
179 * or if the resultant personal XRD doesn't contain a supported
180 * subscription/friend-request attribute.
182 * amended 7/9/2011 to return an hcard which could save potentially loading
183 * a lengthy content page to scrape dfrn attributes
185 * @param string $webbie Address that should be probed
186 * @param string $hcard_url Link to the hcard - is returned by reference
188 * @return string profile link
190 public static function webfingerDfrn($webbie, &$hcard_url)
194 $links = self::lrdd($webbie);
195 logger('webfingerDfrn: '.$webbie.':'.print_r($links, true), LOGGER_DATA);
197 foreach ($links as $link) {
198 if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
199 $profile_link = $link['@attributes']['href'];
201 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) && ($profile_link == "")) {
202 $profile_link = 'stat:'.$link['@attributes']['template'];
204 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
205 $hcard_url = $link['@attributes']['href'];
209 return $profile_link;
213 * @brief Check an URI for LRDD data
215 * this is a replacement for the "lrdd" function.
216 * It isn't used in this class and has some redundancies in the code.
217 * When time comes we can check the existing calls for "lrdd" if we can rework them.
219 * @param string $uri Address that should be probed
221 * @return array uri data
223 public static function lrdd($uri)
225 $lrdd = self::hostMeta($uri);
228 if (is_bool($lrdd)) {
233 $parts = @parse_url($uri);
238 $host = $parts["host"];
239 if (!empty($parts["port"])) {
240 $host .= ':'.$parts["port"];
243 $path_parts = explode("/", trim($parts["path"], "/"));
245 $nick = array_pop($path_parts);
248 $lrdd = self::hostMeta($host);
249 $host .= "/".array_shift($path_parts);
250 } while (!$lrdd && (sizeof($path_parts) > 0));
254 logger("No lrdd data found for ".$uri, LOGGER_DEBUG);
258 foreach ($lrdd as $type => $template) {
263 $path = str_replace('{uri}', urlencode($uri), $template);
264 $webfinger = self::webfinger($path, $type);
266 if (!$webfinger && (strstr($uri, "@"))) {
267 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
268 $webfinger = self::webfinger($path, $type);
271 // Special treatment for Mastodon
272 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
273 // But the webfinger for this format fails.
274 if (!$webfinger && !empty($nick)) {
275 // Mastodon uses a "@" as prefix for usernames in their url format
276 $nick = ltrim($nick, '@');
278 $addr = $nick."@".$host;
280 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
281 $webfinger = self::webfinger($path, $type);
285 if (!is_array($webfinger["links"])) {
286 logger("No webfinger links found for ".$uri, LOGGER_DEBUG);
292 foreach ($webfinger["links"] as $link) {
293 $data[] = ["@attributes" => $link];
296 if (is_array($webfinger["aliases"])) {
297 foreach ($webfinger["aliases"] as $alias) {
298 $data[] = ["@attributes" =>
308 * @brief Fetch information (protocol endpoints and user information) about a given uri
310 * @param string $uri Address that should be probed
311 * @param string $network Test for this specific network
312 * @param integer $uid User ID for the probe (only used for mails)
313 * @param boolean $cache Use cached values?
315 * @return array uri data
317 public static function uri($uri, $network = "", $uid = -1, $cache = true)
320 $result = Cache::get("Probe::uri:".$network.":".$uri);
321 if (!is_null($result)) {
330 $data = self::detect($uri, $network, $uid);
332 if (!isset($data["url"])) {
336 if (x($data, "photo")) {
337 $data["baseurl"] = Network::getUrlMatch(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
339 $data["photo"] = System::baseUrl().'/images/person-175.jpg';
342 if (empty($data["name"])) {
343 if (!empty($data["nick"])) {
344 $data["name"] = $data["nick"];
347 if (!x($data, "name")) {
348 $data["name"] = $data["url"];
352 if (empty($data["nick"])) {
353 $data["nick"] = strtolower($data["name"]);
355 if (strpos($data['nick'], ' ')) {
356 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
360 if (self::$baseurl != "") {
361 $data["baseurl"] = self::$baseurl;
364 if (!isset($data["network"])) {
365 $data["network"] = NETWORK_PHANTOM;
368 $data = self::rearrangeData($data);
370 // Only store into the cache if the value seems to be valid
371 if (!in_array($data['network'], [NETWORK_PHANTOM, NETWORK_MAIL])) {
372 Cache::set("Probe::uri:".$network.":".$uri, $data, CACHE_DAY);
374 /// @todo temporary fix - we need a real contact update function that updates only changing fields
375 /// The biggest problem is the avatar picture that could have a reduced image size.
376 /// It should only be updated if the existing picture isn't existing anymore.
377 /// We only update the contact when it is no probing for a specific network.
378 if (($data['network'] != NETWORK_FEED)
386 $fields = ['name' => $data['name'],
387 'nick' => $data['nick'],
388 'url' => $data['url'],
389 'addr' => $data['addr'],
390 'photo' => $data['photo'],
391 'keywords' => $data['keywords'],
392 'location' => $data['location'],
393 'about' => $data['about'],
394 'notify' => $data['notify'],
395 'network' => $data['network'],
396 'server_url' => $data['baseurl']];
400 foreach ($fields as $key => $val) {
402 unset($fields[$key]);
404 $fieldnames[] = $key;
408 $fields['updated'] = DBM::date();
410 $condition = ['nurl' => normalise_link($data["url"])];
412 $old_fields = dba::selectFirst('gcontact', $fieldnames, $condition);
414 dba::update('gcontact', $fields, $condition, $old_fields);
416 $fields = ['name' => $data['name'],
417 'nick' => $data['nick'],
418 'url' => $data['url'],
419 'addr' => $data['addr'],
420 'alias' => $data['alias'],
421 'keywords' => $data['keywords'],
422 'location' => $data['location'],
423 'about' => $data['about'],
424 'batch' => $data['batch'],
425 'notify' => $data['notify'],
426 'poll' => $data['poll'],
427 'request' => $data['request'],
428 'confirm' => $data['confirm'],
429 'poco' => $data['poco'],
430 'network' => $data['network'],
431 'success_update' => DBM::date()];
435 foreach ($fields as $key => $val) {
437 unset($fields[$key]);
439 $fieldnames[] = $key;
443 $condition = ['nurl' => normalise_link($data["url"]), 'self' => false, 'uid' => 0];
445 $old_fields = dba::selectFirst('contact', $fieldnames, $condition);
447 dba::update('contact', $fields, $condition, $old_fields);
455 * @brief Switch the scheme of an url between http and https
457 * @param string $url URL
459 * @return string switched URL
461 private static function switchScheme($url)
463 $parts = parse_url($url);
465 if (!isset($parts['scheme'])) {
469 if ($parts['scheme'] == 'http') {
470 $url = str_replace('http://', 'https://', $url);
471 } elseif ($parts['scheme'] == 'https') {
472 $url = str_replace('https://', 'http://', $url);
479 * @brief Checks if a profile url should be OStatus but only provides partial information
481 * @param array $webfinger Webfinger data
482 * @param string $lrdd Path template for webfinger request
483 * @param string $type type
485 * @return array fixed webfinger data
487 private static function fixOStatus($webfinger, $lrdd, $type)
489 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
496 foreach ($webfinger['links'] as $link) {
497 if ($link['rel'] == NAMESPACE_OSTATUSSUB) {
500 if ($link['rel'] == 'magic-public-key') {
505 if (!$is_ostatus || $has_key) {
509 $url = self::switchScheme($webfinger['subject']);
510 $path = str_replace('{uri}', urlencode($url), $lrdd);
511 $webfinger2 = self::webfinger($path, $type);
513 // Is the new webfinger detectable as OStatus?
514 if (self::ostatus($webfinger2, true)) {
515 $webfinger = $webfinger2;
522 * @brief Fetch information (protocol endpoints and user information) about a given uri
524 * This function is only called by the "uri" function that adds caching and rearranging of data.
526 * @param string $uri Address that should be probed
527 * @param string $network Test for this specific network
528 * @param integer $uid User ID for the probe (only used for mails)
530 * @return array uri data
532 private static function detect($uri, $network, $uid)
534 $parts = parse_url($uri);
536 if (!empty($parts["scheme"]) && !empty($parts["host"]) && !empty($parts["path"])) {
537 $host = $parts["host"];
538 if (!empty($parts["port"])) {
539 $host .= ':'.$parts["port"];
542 if ($host == 'twitter.com') {
543 return ["network" => NETWORK_TWITTER];
545 $lrdd = self::hostMeta($host);
547 if (is_bool($lrdd)) {
551 $path_parts = explode("/", trim($parts["path"], "/"));
553 while (!$lrdd && (sizeof($path_parts) > 1)) {
554 $host .= "/".array_shift($path_parts);
555 $lrdd = self::hostMeta($host);
558 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
559 return self::feed($uri);
561 $nick = array_pop($path_parts);
563 // Mastodon uses a "@" as prefix for usernames in their url format
564 $nick = ltrim($nick, '@');
566 $addr = $nick."@".$host;
567 } elseif (strstr($uri, '@')) {
568 // If the URI starts with "mailto:" then jump directly to the mail detection
569 if (strpos($uri, 'mailto:') !== false) {
570 $uri = str_replace('mailto:', '', $uri);
571 return self::mail($uri, $uid);
574 if ($network == NETWORK_MAIL) {
575 return self::mail($uri, $uid);
577 // Remove "acct:" from the URI
578 $uri = str_replace('acct:', '', $uri);
580 $host = substr($uri, strpos($uri, '@') + 1);
581 $nick = substr($uri, 0, strpos($uri, '@'));
583 if (strpos($uri, '@twitter.com')) {
584 return ["network" => NETWORK_TWITTER];
586 $lrdd = self::hostMeta($host);
588 if (is_bool($lrdd)) {
593 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
594 return self::mail($uri, $uid);
598 logger("Uri ".$uri." was not detectable", LOGGER_DEBUG);
604 /// @todo Do we need the prefix "acct:" or "acct://"?
606 foreach ($lrdd as $type => $template) {
611 // At first try it with the given uri
612 $path = str_replace('{uri}', urlencode($uri), $template);
613 $webfinger = self::webfinger($path, $type);
615 // Fix possible problems with GNU Social probing to wrong scheme
616 $webfinger = self::fixOStatus($webfinger, $template, $type);
618 // We cannot be sure that the detected address was correct, so we don't use the values
619 if ($webfinger && ($uri != $addr)) {
624 // Try webfinger with the address (user@domain.tld)
626 $path = str_replace('{uri}', urlencode($addr), $template);
627 $webfinger = self::webfinger($path, $type);
630 // Mastodon needs to have it with "acct:"
632 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
633 $webfinger = self::webfinger($path, $type);
638 return self::feed($uri);
643 logger("Probing ".$uri, LOGGER_DEBUG);
645 if (in_array($network, ["", NETWORK_DFRN])) {
646 $result = self::dfrn($webfinger);
648 if ((!$result && ($network == "")) || ($network == NETWORK_DIASPORA)) {
649 $result = self::diaspora($webfinger);
651 if ((!$result && ($network == "")) || ($network == NETWORK_OSTATUS)) {
652 $result = self::ostatus($webfinger);
654 if ((!$result && ($network == "")) || ($network == NETWORK_PUMPIO)) {
655 $result = self::pumpio($webfinger, $addr);
657 if ((!$result && ($network == "")) || ($network == NETWORK_FEED)) {
658 $result = self::feed($uri);
660 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
661 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
662 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
663 $result["nick"] = $nick;
666 if (empty($result["addr"]) && ($addr != "")) {
667 $result["addr"] = $addr;
671 logger($uri." is ".$result["network"], LOGGER_DEBUG);
673 if (empty($result["baseurl"])) {
674 $pos = strpos($result["url"], $host);
676 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
683 * @brief Perform a webfinger request.
685 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
687 * @param string $url Address that should be probed
688 * @param string $type type
690 * @return array webfinger data
692 private static function webfinger($url, $type)
694 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
697 $ret = Network::curl($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
698 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
701 $data = $ret['body'];
703 $webfinger = json_decode($data, true);
704 if (is_array($webfinger)) {
705 if (!isset($webfinger["links"])) {
706 logger("No json webfinger links for ".$url, LOGGER_DEBUG);
712 // If it is not JSON, maybe it is XML
713 $xrd = XML::parseString($data, false);
714 if (!is_object($xrd)) {
715 logger("No webfinger data retrievable for ".$url, LOGGER_DEBUG);
719 $xrd_arr = XML::elementToArray($xrd);
720 if (!isset($xrd_arr["xrd"]["link"])) {
721 logger("No XML webfinger links for ".$url, LOGGER_DEBUG);
727 if (!empty($xrd_arr["xrd"]["subject"])) {
728 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
731 if (!empty($xrd_arr["xrd"]["alias"])) {
732 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
735 $webfinger["links"] = [];
737 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
738 if (!empty($data["@attributes"])) {
739 $attributes = $data["@attributes"];
740 } elseif ($value == "@attributes") {
746 $webfinger["links"][] = $attributes;
752 * @brief Poll the Friendica specific noscrape page.
754 * "noscrape" is a faster alternative to fetch the data from the hcard.
755 * This functionality was originally created for the directory.
757 * @param string $noscrape_url Link to the noscrape page
758 * @param array $data The already fetched data
760 * @return array noscrape data
762 private static function pollNoscrape($noscrape_url, $data)
764 $ret = Network::curl($noscrape_url);
765 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
768 $content = $ret['body'];
770 logger("Empty body for ".$noscrape_url, LOGGER_DEBUG);
774 $json = json_decode($content, true);
775 if (!is_array($json)) {
776 logger("No json data for ".$noscrape_url, LOGGER_DEBUG);
780 if (!empty($json["fn"])) {
781 $data["name"] = $json["fn"];
784 if (!empty($json["addr"])) {
785 $data["addr"] = $json["addr"];
788 if (!empty($json["nick"])) {
789 $data["nick"] = $json["nick"];
792 if (!empty($json["guid"])) {
793 $data["guid"] = $json["guid"];
796 if (!empty($json["comm"])) {
797 $data["community"] = $json["comm"];
800 if (!empty($json["tags"])) {
801 $keywords = implode(" ", $json["tags"]);
802 if ($keywords != "") {
803 $data["keywords"] = $keywords;
807 $location = Profile::formatLocation($json);
809 $data["location"] = $location;
812 if (!empty($json["about"])) {
813 $data["about"] = $json["about"];
816 if (!empty($json["key"])) {
817 $data["pubkey"] = $json["key"];
820 if (!empty($json["photo"])) {
821 $data["photo"] = $json["photo"];
824 if (!empty($json["dfrn-request"])) {
825 $data["request"] = $json["dfrn-request"];
828 if (!empty($json["dfrn-confirm"])) {
829 $data["confirm"] = $json["dfrn-confirm"];
832 if (!empty($json["dfrn-notify"])) {
833 $data["notify"] = $json["dfrn-notify"];
836 if (!empty($json["dfrn-poll"])) {
837 $data["poll"] = $json["dfrn-poll"];
844 * @brief Check for valid DFRN data
846 * @param array $data DFRN data
848 * @return int Number of errors
850 public static function validDfrn($data)
853 if (!isset($data['key'])) {
856 if (!isset($data['dfrn-request'])) {
859 if (!isset($data['dfrn-confirm'])) {
862 if (!isset($data['dfrn-notify'])) {
865 if (!isset($data['dfrn-poll'])) {
872 * @brief Fetch data from a DFRN profile page and via "noscrape"
874 * @param string $profile_link Link to the profile page
876 * @return array profile data
878 public static function profile($profile_link)
882 logger("Check profile ".$profile_link, LOGGER_DEBUG);
884 // Fetch data via noscrape - this is faster
885 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
886 $data = self::pollNoscrape($noscrape_url, $data);
888 if (!isset($data["notify"])
889 || !isset($data["confirm"])
890 || !isset($data["request"])
891 || !isset($data["poll"])
892 || !isset($data["poco"])
893 || !isset($data["name"])
894 || !isset($data["photo"])
896 $data = self::pollHcard($profile_link, $data, true);
900 $prof_data["addr"] = $data["addr"];
901 $prof_data["nick"] = $data["nick"];
902 $prof_data["dfrn-request"] = $data["request"];
903 $prof_data["dfrn-confirm"] = $data["confirm"];
904 $prof_data["dfrn-notify"] = $data["notify"];
905 $prof_data["dfrn-poll"] = $data["poll"];
906 $prof_data["dfrn-poco"] = $data["poco"];
907 $prof_data["photo"] = $data["photo"];
908 $prof_data["fn"] = $data["name"];
909 $prof_data["key"] = $data["pubkey"];
911 logger("Result for profile ".$profile_link.": ".print_r($prof_data, true), LOGGER_DEBUG);
917 * @brief Check for DFRN contact
919 * @param array $webfinger Webfinger data
921 * @return array DFRN data
923 private static function dfrn($webfinger)
927 foreach ($webfinger["links"] as $link) {
928 if (($link["rel"] == NAMESPACE_DFRN) && ($link["href"] != "")) {
929 $data["network"] = NETWORK_DFRN;
930 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
931 $data["poll"] = $link["href"];
932 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
933 $data["url"] = $link["href"];
934 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
935 $hcard_url = $link["href"];
936 } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
937 $data["poco"] = $link["href"];
938 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && ($link["href"] != "")) {
939 $data["photo"] = $link["href"];
940 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
941 $data["baseurl"] = trim($link["href"], '/');
942 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
943 $data["guid"] = $link["href"];
944 } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
945 $data["pubkey"] = base64_decode($link["href"]);
947 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
948 if (strstr($data["pubkey"], 'RSA ')) {
949 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
954 if (is_array($webfinger["aliases"])) {
955 foreach ($webfinger["aliases"] as $alias) {
956 if (normalise_link($alias) != normalise_link($data["url"]) && ! strstr($alias, "@")) {
957 $data["alias"] = $alias;
958 } elseif (substr($alias, 0, 5) == 'acct:') {
959 $data["addr"] = substr($alias, 5);
964 if (substr($webfinger["subject"], 0, 5) == "acct:") {
965 $data["addr"] = substr($webfinger["subject"], 5);
968 if (!isset($data["network"]) || ($hcard_url == "")) {
972 // Fetch data via noscrape - this is faster
973 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
974 $data = self::pollNoscrape($noscrape_url, $data);
976 if (isset($data["notify"])
977 && isset($data["confirm"])
978 && isset($data["request"])
979 && isset($data["poll"])
980 && isset($data["name"])
981 && isset($data["photo"])
986 $data = self::pollHcard($hcard_url, $data, true);
992 * @brief Poll the hcard page (Diaspora and Friendica specific)
994 * @param string $hcard_url Link to the hcard page
995 * @param array $data The already fetched data
996 * @param boolean $dfrn Poll DFRN specific data
998 * @return array hcard data
1000 private static function pollHcard($hcard_url, $data, $dfrn = false)
1002 $ret = Network::curl($hcard_url);
1003 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1006 $content = $ret['body'];
1011 $doc = new DOMDocument();
1012 if (!@$doc->loadHTML($content)) {
1016 $xpath = new DomXPath($doc);
1018 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1019 if (!is_object($vcards)) {
1023 if ($vcards->length > 0) {
1024 $vcard = $vcards->item(0);
1026 // We have to discard the guid from the hcard in favour of the guid from lrdd
1027 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1028 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1029 if (($search->length > 0) && ($data["guid"] == "")) {
1030 $data["guid"] = $search->item(0)->nodeValue;
1033 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1034 if ($search->length > 0) {
1035 $data["nick"] = $search->item(0)->nodeValue;
1038 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1039 if ($search->length > 0) {
1040 $data["name"] = $search->item(0)->nodeValue;
1043 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1044 if ($search->length > 0) {
1045 $data["searchable"] = $search->item(0)->nodeValue;
1048 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1049 if ($search->length > 0) {
1050 $data["pubkey"] = $search->item(0)->nodeValue;
1051 if (strstr($data["pubkey"], 'RSA ')) {
1052 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1056 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1057 if ($search->length > 0) {
1058 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1063 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1064 foreach ($photos as $photo) {
1066 foreach ($photo->attributes as $attribute) {
1067 $attr[$attribute->name] = trim($attribute->value);
1070 if (isset($attr["src"]) && isset($attr["width"])) {
1071 $avatar[$attr["width"]] = $attr["src"];
1074 // We don't have a width. So we just take everything that we got.
1075 // This is a Hubzilla workaround which doesn't send a width.
1076 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1077 $avatar[] = $attr["src"];
1081 if (sizeof($avatar)) {
1083 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1087 // Poll DFRN specific data
1088 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1089 if ($search->length > 0) {
1090 foreach ($search as $link) {
1091 //$data["request"] = $search->item(0)->nodeValue;
1093 foreach ($link->attributes as $attribute) {
1094 $attr[$attribute->name] = trim($attribute->value);
1097 $data[substr($attr["rel"], 5)] = $attr["href"];
1101 // Older Friendica versions had used the "uid" field differently than newer versions
1102 if ($data["nick"] == $data["guid"]) {
1103 unset($data["guid"]);
1112 * @brief Check for Diaspora contact
1114 * @param array $webfinger Webfinger data
1116 * @return array Diaspora data
1118 private static function diaspora($webfinger)
1122 foreach ($webfinger["links"] as $link) {
1123 if (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
1124 $hcard_url = $link["href"];
1125 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
1126 $data["baseurl"] = trim($link["href"], '/');
1127 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
1128 $data["guid"] = $link["href"];
1129 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
1130 $data["url"] = $link["href"];
1131 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1132 $data["poll"] = $link["href"];
1133 } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
1134 $data["poco"] = $link["href"];
1135 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1136 $data["notify"] = $link["href"];
1137 } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
1138 $data["pubkey"] = base64_decode($link["href"]);
1140 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1141 if (strstr($data["pubkey"], 'RSA ')) {
1142 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1147 if (!isset($data["url"]) || ($hcard_url == "")) {
1151 if (is_array($webfinger["aliases"])) {
1152 foreach ($webfinger["aliases"] as $alias) {
1153 if (normalise_link($alias) != normalise_link($data["url"]) && ! strstr($alias, "@")) {
1154 $data["alias"] = $alias;
1155 } elseif (substr($alias, 0, 5) == 'acct:') {
1156 $data["addr"] = substr($alias, 5);
1161 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1162 $data["addr"] = substr($webfinger["subject"], 5);
1165 // Fetch further information from the hcard
1166 $data = self::pollHcard($hcard_url, $data);
1172 if (isset($data["url"])
1173 && isset($data["guid"])
1174 && isset($data["baseurl"])
1175 && isset($data["pubkey"])
1176 && ($hcard_url != "")
1178 $data["network"] = NETWORK_DIASPORA;
1180 // The Diaspora handle must always be lowercase
1181 $data["addr"] = strtolower($data["addr"]);
1183 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1184 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1185 $data["batch"] = $data["baseurl"] . "/receive/public";
1194 * @brief Check for OStatus contact
1196 * @param array $webfinger Webfinger data
1197 * @param bool $short Short detection mode
1199 * @return array|bool OStatus data or "false" on error or "true" on short mode
1201 private static function ostatus($webfinger, $short = false)
1205 if (is_array($webfinger["aliases"])) {
1206 foreach ($webfinger["aliases"] as $alias) {
1207 if (strstr($alias, "@") && !strstr(normalise_link($alias), "http://")) {
1208 $data["addr"] = str_replace('acct:', '', $alias);
1213 if (is_string($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1214 && !strstr(normalise_link($webfinger["subject"]), "http://")
1216 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1220 if (is_array($webfinger["links"])) {
1221 foreach ($webfinger["links"] as $link) {
1222 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1223 && ($link["type"] == "text/html")
1224 && ($link["href"] != "")
1226 $data["url"] = $link["href"];
1227 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1228 $data["notify"] = $link["href"];
1229 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1230 $data["poll"] = $link["href"];
1231 } elseif (($link["rel"] == "magic-public-key") && ($link["href"] != "")) {
1232 $pubkey = $link["href"];
1234 if (substr($pubkey, 0, 5) === 'data:') {
1235 if (strstr($pubkey, ',')) {
1236 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1238 $pubkey = substr($pubkey, 5);
1240 } elseif (normalise_link($pubkey) == 'http://') {
1241 $ret = Network::curl($pubkey);
1242 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1245 $pubkey = $ret['body'];
1248 $key = explode(".", $pubkey);
1250 if (sizeof($key) >= 3) {
1251 $m = base64url_decode($key[1]);
1252 $e = base64url_decode($key[2]);
1253 $data["pubkey"] = Crypto::meToPem($m, $e);
1259 if (isset($data["notify"]) && isset($data["pubkey"])
1260 && isset($data["poll"])
1261 && isset($data["url"])
1263 $data["network"] = NETWORK_OSTATUS;
1272 // Fetch all additional data from the feed
1273 $ret = Network::curl($data["poll"]);
1274 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1277 $feed = $ret['body'];
1278 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1283 if ($feed_data["header"]["author-name"] != "") {
1284 $data["name"] = $feed_data["header"]["author-name"];
1286 if ($feed_data["header"]["author-nick"] != "") {
1287 $data["nick"] = $feed_data["header"]["author-nick"];
1289 if ($feed_data["header"]["author-avatar"] != "") {
1290 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1292 if ($feed_data["header"]["author-id"] != "") {
1293 $data["alias"] = $feed_data["header"]["author-id"];
1295 if ($feed_data["header"]["author-location"] != "") {
1296 $data["location"] = $feed_data["header"]["author-location"];
1298 if ($feed_data["header"]["author-about"] != "") {
1299 $data["about"] = $feed_data["header"]["author-about"];
1301 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1302 // So we take the value that we just fetched, although the other one worked as well
1303 if ($feed_data["header"]["author-link"] != "") {
1304 $data["url"] = $feed_data["header"]["author-link"];
1307 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1308 $data['url'] = $data["alias"];
1309 $data["alias"] = '';
1312 /// @todo Fetch location and "about" from the feed as well
1317 * @brief Fetch data from a pump.io profile page
1319 * @param string $profile_link Link to the profile page
1321 * @return array profile data
1323 private static function pumpioProfileData($profile_link)
1325 $doc = new DOMDocument();
1326 if (!@$doc->loadHTMLFile($profile_link)) {
1330 $xpath = new DomXPath($doc);
1334 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1336 if ($data["name"] == '') {
1337 // This is ugly - but pump.io doesn't seem to know a better way for it
1338 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1339 $pos = strpos($data["name"], chr(10));
1341 $data["name"] = trim(substr($data["name"], 0, $pos));
1345 $data["location"] = $xpath->query("//p[contains(@class, 'p-locality')]")->item(0)->nodeValue;
1347 if ($data["location"] == '') {
1348 $data["location"] = $xpath->query("//p[contains(@class, 'location')]")->item(0)->nodeValue;
1351 $data["about"] = $xpath->query("//p[contains(@class, 'p-note')]")->item(0)->nodeValue;
1353 if ($data["about"] == '') {
1354 $data["about"] = $xpath->query("//p[contains(@class, 'summary')]")->item(0)->nodeValue;
1357 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1359 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1362 foreach ($avatar->attributes as $attribute) {
1363 if ($attribute->name == "src") {
1364 $data["photo"] = trim($attribute->value);
1373 * @brief Check for pump.io contact
1375 * @param array $webfinger Webfinger data
1377 * @return array pump.io data
1379 private static function pumpio($webfinger, $addr)
1382 foreach ($webfinger["links"] as $link) {
1383 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1384 && ($link["type"] == "text/html")
1385 && ($link["href"] != "")
1387 $data["url"] = $link["href"];
1388 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1389 $data["notify"] = $link["href"];
1390 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1391 $data["poll"] = $link["href"];
1392 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1393 $data["dialback"] = $link["href"];
1396 if (isset($data["poll"]) && isset($data["notify"])
1397 && isset($data["dialback"])
1398 && isset($data["url"])
1400 // by now we use these fields only for the network type detection
1401 // So we unset all data that isn't used at the moment
1402 unset($data["dialback"]);
1404 $data["network"] = NETWORK_PUMPIO;
1409 $profile_data = self::pumpioProfileData($data["url"]);
1411 if (!$profile_data) {
1415 $data = array_merge($data, $profile_data);
1417 if (($addr != '') && ($data['name'] != '')) {
1418 $name = trim(str_replace($addr, '', $data['name']));
1420 $data['name'] = $name;
1428 * @brief Check page for feed link
1430 * @param string $url Page link
1432 * @return string feed link
1434 private static function getFeedLink($url)
1436 $doc = new DOMDocument();
1438 if (!@$doc->loadHTMLFile($url)) {
1442 $xpath = new DomXPath($doc);
1444 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1445 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1446 if (!is_object($feeds)) {
1450 if ($feeds->length == 0) {
1456 foreach ($feeds as $feed) {
1458 foreach ($feed->attributes as $attribute) {
1459 $attr[$attribute->name] = trim($attribute->value);
1462 if ($feed_url == "") {
1463 $feed_url = $attr["href"];
1471 * @brief Check for feed contact
1473 * @param string $url Profile link
1474 * @param boolean $probe Do a probe if the page contains a feed link
1476 * @return array feed data
1478 private static function feed($url, $probe = true)
1480 $ret = Network::curl($url);
1481 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1484 $feed = $ret['body'];
1485 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1492 $feed_url = self::getFeedLink($url);
1498 return self::feed($feed_url, false);
1501 if ($feed_data["header"]["author-name"] != "") {
1502 $data["name"] = $feed_data["header"]["author-name"];
1505 if ($feed_data["header"]["author-nick"] != "") {
1506 $data["nick"] = $feed_data["header"]["author-nick"];
1509 if ($feed_data["header"]["author-avatar"] != "") {
1510 $data["photo"] = $feed_data["header"]["author-avatar"];
1513 if ($feed_data["header"]["author-id"] != "") {
1514 $data["alias"] = $feed_data["header"]["author-id"];
1517 $data["url"] = $url;
1518 $data["poll"] = $url;
1520 if ($feed_data["header"]["author-link"] != "") {
1521 $data["baseurl"] = $feed_data["header"]["author-link"];
1523 $data["baseurl"] = $data["url"];
1526 $data["network"] = NETWORK_FEED;
1532 * @brief Check for mail contact
1534 * @param string $uri Profile link
1535 * @param integer $uid User ID
1537 * @return array mail data
1539 private static function mail($uri, $uid)
1541 if (!Network::isEmailDomainValid($uri)) {
1549 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1551 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1553 if (DBM::is_result($x) && DBM::is_result($r)) {
1554 $mailbox = Email::constructMailboxName($r[0]);
1556 openssl_private_decrypt(hex2bin($r[0]['pass']), $password, $x[0]['prvkey']);
1557 $mbox = Email::connect($mailbox, $r[0]['user'], $password);
1563 $msgs = Email::poll($mbox, $uri);
1564 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1566 if (!count($msgs)) {
1570 $phost = substr($uri, strpos($uri, '@') + 1);
1573 $data["addr"] = $uri;
1574 $data["network"] = NETWORK_MAIL;
1575 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1576 $data["nick"] = $data["name"];
1577 $data["photo"] = Network::lookupAvatarByEmail($uri);
1578 $data["url"] = 'mailto:'.$uri;
1579 $data["notify"] = 'smtp '.random_string();
1580 $data["poll"] = 'email '.random_string();
1582 $x = Email::messageMeta($mbox, $msgs[0]);
1583 if (stristr($x[0]->from, $uri)) {
1584 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1585 } elseif (stristr($x[0]->to, $uri)) {
1586 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1589 foreach ($adr as $feadr) {
1590 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1591 &&(strcasecmp($feadr->host, $phost) == 0)
1592 && (strlen($feadr->personal))
1594 $personal = imap_mime_header_decode($feadr->personal);
1596 foreach ($personal as $perspart) {
1597 if ($perspart->charset != "default") {
1598 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1600 $data["name"] .= $perspart->text;
1604 $data["name"] = notags($data["name"]);
1608 if (!empty($mbox)) {
1616 * @brief Mix two paths together to possibly fix missing parts
1618 * @param string $avatar Path to the avatar
1619 * @param string $base Another path that is hopefully complete
1621 * @return string fixed avatar path
1623 public static function fixAvatar($avatar, $base)
1625 $base_parts = parse_url($base);
1627 // Remove all parts that could create a problem
1628 unset($base_parts['path']);
1629 unset($base_parts['query']);
1630 unset($base_parts['fragment']);
1632 $avatar_parts = parse_url($avatar);
1635 $parts = array_merge($base_parts, $avatar_parts);
1637 // And put them together again
1638 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1639 $host = isset($parts['host']) ? $parts['host'] : '';
1640 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1641 $path = isset($parts['path']) ? $parts['path'] : '';
1642 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1643 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1645 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1647 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);