3 namespace Friendica\Network;
6 * @file src/Network/Probe.php
7 * @brief Functions for probing URL
12 use Friendica\Core\System;
13 use Friendica\Core\Config;
23 require_once 'include/feed.php';
24 require_once 'include/email.php';
25 require_once 'include/network.php';
28 * @brief This class contain functions for probing URL
33 private static $baseurl;
36 * @brief Rearrange the array so that it always has the same order
38 * @param array $data Unordered data
40 * @return array Ordered data
42 private static function rearrangeData($data) {
43 $fields = array("name", "nick", "guid", "url", "addr", "alias",
44 "photo", "community", "keywords", "location", "about",
45 "batch", "notify", "poll", "request", "confirm", "poco",
46 "priority", "network", "pubkey", "baseurl");
49 foreach ($fields as $field) {
50 if (isset($data[$field])) {
51 $newdata[$field] = $data[$field];
53 $newdata[$field] = "";
57 // We don't use the "priority" field anymore and replace it with a dummy.
58 $newdata["priority"] = 0;
64 * @brief Check if the hostname belongs to the own server
66 * @param string $host The hostname that is to be checked
68 * @return bool Does the testes hostname belongs to the own server?
70 private static function ownHost($host) {
71 $own_host = get_app()->get_hostname();
73 $parts = parse_url($host);
75 if (!isset($parts['scheme'])) {
76 $parts = parse_url('http://'.$host);
79 if (!isset($parts['host'])) {
82 return $parts['host'] == $own_host;
86 * @brief Probes for webfinger path via "host-meta"
88 * @param string $host The host part of an url
90 * @return array with template and type of the webfinger template for JSON or XML
92 private static function hostMeta($host) {
94 // Reset the static variable
97 $ssl_url = "https://".$host."/.well-known/host-meta";
98 $url = "http://".$host."/.well-known/host-meta";
100 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
103 logger("Probing for ".$host, LOGGER_DEBUG);
105 $ret = z_fetch_url($ssl_url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
106 if ($ret['success']) {
108 $xrd = parse_xml_string($xml, false);
109 $host_url = 'https://'.$host;
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);
120 $host_url = 'http://'.$host;
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);
134 // The following webfinger path is defined in RFC 7033 https://tools.ietf.org/html/rfc7033
135 // Problem is that Hubzilla currently doesn't provide all data in the JSON webfinger
136 // compared to the XML webfinger. So this is commented out by now.
137 // $lrdd = array("application/jrd+json" => $host_url.'/.well-known/webfinger?resource={uri}');
139 foreach ($links["xrd"]["link"] as $value => $link) {
140 if (!empty($link["@attributes"])) {
141 $attributes = $link["@attributes"];
142 } elseif ($value == "@attributes") {
148 if (($attributes["rel"] == "lrdd") && !empty($attributes["template"])) {
149 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
151 $lrdd[$type] = $attributes["template"];
155 self::$baseurl = "http://".$host;
157 logger("Probing successful for ".$host, LOGGER_DEBUG);
163 * @brief Perform Webfinger lookup and return DFRN data
165 * Given an email style address, perform webfinger lookup and
166 * return the resulting DFRN profile URL, or if no DFRN profile URL
167 * is located, returns an OStatus subscription template (prefixed
168 * with the string 'stat:' to identify it as on OStatus template).
169 * If this isn't an email style address just return $webbie.
170 * Return an empty string if email-style addresses but webfinger fails,
171 * or if the resultant personal XRD doesn't contain a supported
172 * subscription/friend-request attribute.
174 * amended 7/9/2011 to return an hcard which could save potentially loading
175 * a lengthy content page to scrape dfrn attributes
177 * @param string $webbie Address that should be probed
178 * @param string $hcard_url Link to the hcard - is returned by reference
180 * @return string profile link
182 public static function webfingerDfrn($webbie, &$hcard_url) {
186 $links = self::lrdd($webbie);
187 logger('webfingerDfrn: '.$webbie.':'.print_r($links, true), LOGGER_DATA);
189 foreach ($links as $link) {
190 if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
191 $profile_link = $link['@attributes']['href'];
193 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) && ($profile_link == "")) {
194 $profile_link = 'stat:'.$link['@attributes']['template'];
196 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
197 $hcard_url = $link['@attributes']['href'];
201 return $profile_link;
205 * @brief Check an URI for LRDD data
207 * this is a replacement for the "lrdd" function in include/network.php.
208 * It isn't used in this class and has some redundancies in the code.
209 * When time comes we can check the existing calls for "lrdd" if we can rework them.
211 * @param string $uri Address that should be probed
213 * @return array uri data
215 public static function lrdd($uri) {
217 $lrdd = self::hostMeta($uri);
220 if (is_bool($lrdd)) {
225 $parts = @parse_url($uri);
230 $host = $parts["host"];
231 if (!empty($parts["port"])) {
232 $host .= ':'.$parts["port"];
235 $path_parts = explode("/", trim($parts["path"], "/"));
237 $nick = array_pop($path_parts);
240 $lrdd = self::hostMeta($host);
241 $host .= "/".array_shift($path_parts);
242 } while (!$lrdd && (sizeof($path_parts) > 0));
246 logger("No lrdd data found for ".$uri, LOGGER_DEBUG);
250 foreach ($lrdd AS $type => $template) {
255 $path = str_replace('{uri}', urlencode($uri), $template);
256 $webfinger = self::webfinger($path, $type);
258 if (!$webfinger && (strstr($uri, "@"))) {
259 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
260 $webfinger = self::webfinger($path, $type);
263 // Special treatment for Mastodon
264 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
265 // But the webfinger for this format fails.
266 if (!$webfinger && !empty($nick)) {
267 // Mastodon uses a "@" as prefix for usernames in their url format
268 $nick = ltrim($nick, '@');
270 $addr = $nick."@".$host;
272 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
273 $webfinger = self::webfinger($path, $type);
277 if (!is_array($webfinger["links"])) {
278 logger("No webfinger links found for ".$uri, LOGGER_DEBUG);
284 foreach ($webfinger["links"] as $link) {
285 $data[] = array("@attributes" => $link);
288 if (is_array($webfinger["aliases"])) {
289 foreach ($webfinger["aliases"] as $alias) {
290 $data[] = array("@attributes" =>
291 array("rel" => "alias",
300 * @brief Fetch information (protocol endpoints and user information) about a given uri
302 * @param string $uri Address that should be probed
303 * @param string $network Test for this specific network
304 * @param integer $uid User ID for the probe (only used for mails)
305 * @param boolean $cache Use cached values?
307 * @return array uri data
309 public static function uri($uri, $network = "", $uid = -1, $cache = true) {
312 $result = Cache::get("probe_url:".$network.":".$uri);
313 if (!is_null($result)) {
322 $data = self::detect($uri, $network, $uid);
324 if (!isset($data["url"])) {
328 if ($data["photo"] != "") {
329 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
331 $data["photo"] = System::baseUrl().'/images/person-175.jpg';
334 if (empty($data["name"])) {
335 if (!empty($data["nick"])) {
336 $data["name"] = $data["nick"];
339 if ($data["name"] == "") {
340 $data["name"] = $data["url"];
344 if (empty($data["nick"])) {
345 $data["nick"] = strtolower($data["name"]);
347 if (strpos($data['nick'], ' ')) {
348 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
352 if (self::$baseurl != "") {
353 $data["baseurl"] = self::$baseurl;
356 if (!isset($data["network"])) {
357 $data["network"] = NETWORK_PHANTOM;
360 $data = self::rearrangeData($data);
362 // Only store into the cache if the value seems to be valid
363 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
364 Cache::set("probe_url:".$network.":".$uri, $data, CACHE_DAY);
366 /// @todo temporary fix - we need a real contact update function that updates only changing fields
367 /// The biggest problem is the avatar picture that could have a reduced image size.
368 /// It should only be updated if the existing picture isn't existing anymore.
369 /// We only update the contact when it is no probing for a specific network.
370 if (($data['network'] != NETWORK_FEED)
378 $fields = array('name' => $data['name'],
379 'nick' => $data['nick'],
380 'url' => $data['url'],
381 'addr' => $data['addr'],
382 'photo' => $data['photo'],
383 'keywords' => $data['keywords'],
384 'location' => $data['location'],
385 'about' => $data['about'],
386 'notify' => $data['notify'],
387 'network' => $data['network'],
388 'server_url' => $data['baseurl']);
390 $fieldnames = array();
392 foreach ($fields AS $key => $val) {
394 unset($fields[$key]);
396 $fieldnames[] = $key;
400 $fields['updated'] = dbm::date();
402 $condition = array('nurl' => normalise_link($data["url"]));
404 $old_fields = dba::select('gcontact', $fieldnames, $condition, array('limit' => 1));
406 dba::update('gcontact', $fields, $condition, $old_fields);
408 $fields = array('name' => $data['name'],
409 'nick' => $data['nick'],
410 'url' => $data['url'],
411 'addr' => $data['addr'],
412 'alias' => $data['alias'],
413 'keywords' => $data['keywords'],
414 'location' => $data['location'],
415 'about' => $data['about'],
416 'batch' => $data['batch'],
417 'notify' => $data['notify'],
418 'poll' => $data['poll'],
419 'request' => $data['request'],
420 'confirm' => $data['confirm'],
421 'poco' => $data['poco'],
422 'network' => $data['network'],
423 'success_update' => dbm::date());
425 $fieldnames = array();
427 foreach ($fields AS $key => $val) {
429 unset($fields[$key]);
431 $fieldnames[] = $key;
435 $condition = array('nurl' => normalise_link($data["url"]), 'self' => false, 'uid' => 0);
437 $old_fields = dba::select('contact', $fieldnames, $condition, array('limit' => 1));
439 dba::update('contact', $fields, $condition, $old_fields);
447 * @brief Switch the scheme of an url between http and https
449 * @param string $url URL
451 * @return string switched URL
453 private static function switchScheme($url) {
454 $parts = parse_url($url);
456 if (!isset($parts['scheme'])) {
460 if ($parts['scheme'] == 'http') {
461 $url = str_replace('http://', 'https://', $url);
462 } elseif ($parts['scheme'] == 'https') {
463 $url = str_replace('https://', 'http://', $url);
470 * @brief Checks if a profile url should be OStatus but only provides partial information
472 * @param array $webfinger Webfinger data
473 * @param string $lrdd Path template for webfinger request
475 * @return array fixed webfinger data
477 private static function fixOstatus($webfinger, $lrdd, $type) {
478 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
485 foreach ($webfinger['links'] as $link) {
486 if ($link['rel'] == NAMESPACE_OSTATUSSUB) {
489 if ($link['rel'] == 'magic-public-key') {
494 if (!$is_ostatus || $has_key) {
498 $url = self::switchScheme($webfinger['subject']);
499 $path = str_replace('{uri}', urlencode($url), $lrdd);
500 $webfinger2 = self::webfinger($path, $type);
502 // Is the new webfinger detectable as OStatus?
503 if (self::ostatus($webfinger2, true)) {
504 $webfinger = $webfinger2;
511 * @brief Fetch information (protocol endpoints and user information) about a given uri
513 * This function is only called by the "uri" function that adds caching and rearranging of data.
515 * @param string $uri Address that should be probed
516 * @param string $network Test for this specific network
517 * @param integer $uid User ID for the probe (only used for mails)
519 * @return array uri data
521 private static function detect($uri, $network, $uid) {
522 $parts = parse_url($uri);
524 if (!empty($parts["scheme"]) && !empty($parts["host"]) && !empty($parts["path"])) {
525 $host = $parts["host"];
526 if (!empty($parts["port"])) {
527 $host .= ':'.$parts["port"];
530 if ($host == 'twitter.com') {
531 return array("network" => NETWORK_TWITTER);
533 $lrdd = self::hostMeta($host);
535 if (is_bool($lrdd)) {
539 $path_parts = explode("/", trim($parts["path"], "/"));
541 while (!$lrdd && (sizeof($path_parts) > 1)) {
542 $host .= "/".array_shift($path_parts);
543 $lrdd = self::hostMeta($host);
546 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
547 return self::feed($uri);
549 $nick = array_pop($path_parts);
551 // Mastodon uses a "@" as prefix for usernames in their url format
552 $nick = ltrim($nick, '@');
554 $addr = $nick."@".$host;
556 } elseif (strstr($uri, '@')) {
557 // If the URI starts with "mailto:" then jump directly to the mail detection
558 if (strpos($uri, 'mailto:') !== false) {
559 $uri = str_replace('mailto:', '', $uri);
560 return self::mail($uri, $uid);
563 if ($network == NETWORK_MAIL) {
564 return self::mail($uri, $uid);
566 // Remove "acct:" from the URI
567 $uri = str_replace('acct:', '', $uri);
569 $host = substr($uri, strpos($uri, '@') + 1);
570 $nick = substr($uri, 0, strpos($uri, '@'));
572 if (strpos($uri, '@twitter.com')) {
573 return array("network" => NETWORK_TWITTER);
575 $lrdd = self::hostMeta($host);
577 if (is_bool($lrdd)) {
582 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
583 return self::mail($uri, $uid);
588 logger("Uri ".$uri." was not detectable", LOGGER_DEBUG);
594 /// @todo Do we need the prefix "acct:" or "acct://"?
596 foreach ($lrdd AS $type => $template) {
601 // At first try it with the given uri
602 $path = str_replace('{uri}', urlencode($uri), $template);
603 $webfinger = self::webfinger($path, $type);
605 // Fix possible problems with GNU Social probing to wrong scheme
606 $webfinger = self::fixOstatus($webfinger, $template, $type);
608 // We cannot be sure that the detected address was correct, so we don't use the values
609 if ($webfinger && ($uri != $addr)) {
614 // Try webfinger with the address (user@domain.tld)
616 $path = str_replace('{uri}', urlencode($addr), $template);
617 $webfinger = self::webfinger($path, $type);
620 // Mastodon needs to have it with "acct:"
622 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
623 $webfinger = self::webfinger($path, $type);
628 return self::feed($uri);
633 logger("Probing ".$uri, LOGGER_DEBUG);
635 if (in_array($network, array("", NETWORK_DFRN))) {
636 $result = self::dfrn($webfinger);
638 if ((!$result && ($network == "")) || ($network == NETWORK_DIASPORA)) {
639 $result = self::diaspora($webfinger);
641 if ((!$result && ($network == "")) || ($network == NETWORK_OSTATUS)) {
642 $result = self::ostatus($webfinger);
644 if ((!$result && ($network == "")) || ($network == NETWORK_PUMPIO)) {
645 $result = self::pumpio($webfinger);
647 if ((!$result && ($network == "")) || ($network == NETWORK_FEED)) {
648 $result = self::feed($uri);
650 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
651 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
652 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
653 $result["nick"] = $nick;
656 if (empty($result["addr"]) && ($addr != "")) {
657 $result["addr"] = $addr;
661 logger($uri." is ".$result["network"], LOGGER_DEBUG);
663 if (empty($result["baseurl"])) {
664 $pos = strpos($result["url"], $host);
666 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
674 * @brief Perform a webfinger request.
676 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
678 * @param string $url Address that should be probed
680 * @return array webfinger data
682 private static function webfinger($url, $type) {
684 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
687 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => $type));
688 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
691 $data = $ret['body'];
693 $webfinger = json_decode($data, true);
694 if (is_array($webfinger)) {
695 if (!isset($webfinger["links"])) {
696 logger("No json webfinger links for ".$url, LOGGER_DEBUG);
702 // If it is not JSON, maybe it is XML
703 $xrd = parse_xml_string($data, false);
704 if (!is_object($xrd)) {
705 logger("No webfinger data retrievable for ".$url, LOGGER_DEBUG);
709 $xrd_arr = xml::element_to_array($xrd);
710 if (!isset($xrd_arr["xrd"]["link"])) {
711 logger("No XML webfinger links for ".$url, LOGGER_DEBUG);
715 $webfinger = array();
717 if (!empty($xrd_arr["xrd"]["subject"])) {
718 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
721 if (!empty($xrd_arr["xrd"]["alias"])) {
722 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
725 $webfinger["links"] = array();
727 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
728 if (!empty($data["@attributes"])) {
729 $attributes = $data["@attributes"];
730 } elseif ($value == "@attributes") {
736 $webfinger["links"][] = $attributes;
742 * @brief Poll the Friendica specific noscrape page.
744 * "noscrape" is a faster alternative to fetch the data from the hcard.
745 * This functionality was originally created for the directory.
747 * @param string $noscrape_url Link to the noscrape page
748 * @param array $data The already fetched data
750 * @return array noscrape data
752 private static function pollNoscrape($noscrape_url, $data) {
753 $ret = z_fetch_url($noscrape_url);
754 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
757 $content = $ret['body'];
759 logger("Empty body for ".$noscrape_url, LOGGER_DEBUG);
763 $json = json_decode($content, true);
764 if (!is_array($json)) {
765 logger("No json data for ".$noscrape_url, LOGGER_DEBUG);
769 if (!empty($json["fn"])) {
770 $data["name"] = $json["fn"];
773 if (!empty($json["addr"])) {
774 $data["addr"] = $json["addr"];
777 if (!empty($json["nick"])) {
778 $data["nick"] = $json["nick"];
781 if (!empty($json["comm"])) {
782 $data["community"] = $json["comm"];
785 if (!empty($json["tags"])) {
786 $keywords = implode(" ", $json["tags"]);
787 if ($keywords != "") {
788 $data["keywords"] = $keywords;
792 $location = formatted_location($json);
794 $data["location"] = $location;
797 if (!empty($json["about"])) {
798 $data["about"] = $json["about"];
801 if (!empty($json["key"])) {
802 $data["pubkey"] = $json["key"];
805 if (!empty($json["photo"])) {
806 $data["photo"] = $json["photo"];
809 if (!empty($json["dfrn-request"])) {
810 $data["request"] = $json["dfrn-request"];
813 if (!empty($json["dfrn-confirm"])) {
814 $data["confirm"] = $json["dfrn-confirm"];
817 if (!empty($json["dfrn-notify"])) {
818 $data["notify"] = $json["dfrn-notify"];
821 if (!empty($json["dfrn-poll"])) {
822 $data["poll"] = $json["dfrn-poll"];
829 * @brief Check for valid DFRN data
831 * @param array $data DFRN data
833 * @return int Number of errors
835 public static function validDfrn($data) {
837 if (!isset($data['key'])) {
840 if (!isset($data['dfrn-request'])) {
843 if (!isset($data['dfrn-confirm'])) {
846 if (!isset($data['dfrn-notify'])) {
849 if (!isset($data['dfrn-poll'])) {
856 * @brief Fetch data from a DFRN profile page and via "noscrape"
858 * @param string $profile_link Link to the profile page
860 * @return array profile data
862 public static function profile($profile_link) {
866 logger("Check profile ".$profile_link, LOGGER_DEBUG);
868 // Fetch data via noscrape - this is faster
869 $noscrape_url = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile_link);
870 $data = self::pollNoscrape($noscrape_url, $data);
872 if (!isset($data["notify"])
873 || !isset($data["confirm"])
874 || !isset($data["request"])
875 || !isset($data["poll"])
876 || !isset($data["poco"])
877 || !isset($data["name"])
878 || !isset($data["photo"])
880 $data = self::pollHcard($profile_link, $data, true);
883 $prof_data = array();
884 $prof_data["addr"] = $data["addr"];
885 $prof_data["nick"] = $data["nick"];
886 $prof_data["dfrn-request"] = $data["request"];
887 $prof_data["dfrn-confirm"] = $data["confirm"];
888 $prof_data["dfrn-notify"] = $data["notify"];
889 $prof_data["dfrn-poll"] = $data["poll"];
890 $prof_data["dfrn-poco"] = $data["poco"];
891 $prof_data["photo"] = $data["photo"];
892 $prof_data["fn"] = $data["name"];
893 $prof_data["key"] = $data["pubkey"];
895 logger("Result for profile ".$profile_link.": ".print_r($prof_data, true), LOGGER_DEBUG);
901 * @brief Check for DFRN contact
903 * @param array $webfinger Webfinger data
905 * @return array DFRN data
907 private static function dfrn($webfinger) {
911 foreach ($webfinger["links"] as $link) {
912 if (($link["rel"] == NAMESPACE_DFRN) && ($link["href"] != "")) {
913 $data["network"] = NETWORK_DFRN;
914 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
915 $data["poll"] = $link["href"];
916 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
917 $data["url"] = $link["href"];
918 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
919 $hcard_url = $link["href"];
920 } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
921 $data["poco"] = $link["href"];
922 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && ($link["href"] != "")) {
923 $data["photo"] = $link["href"];
924 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
925 $data["baseurl"] = trim($link["href"], '/');
926 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
927 $data["guid"] = $link["href"];
928 } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
929 $data["pubkey"] = base64_decode($link["href"]);
931 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
932 if (strstr($data["pubkey"], 'RSA ')) {
933 $data["pubkey"] = rsatopem($data["pubkey"]);
938 if (is_array($webfinger["aliases"])) {
939 foreach ($webfinger["aliases"] as $alias) {
940 if (substr($alias, 0, 5) == 'acct:') {
941 $data["addr"] = substr($alias, 5);
946 if (!isset($data["network"]) || ($hcard_url == "")) {
950 // Fetch data via noscrape - this is faster
951 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
952 $data = self::pollNoscrape($noscrape_url, $data);
954 if (isset($data["notify"])
955 && isset($data["confirm"])
956 && isset($data["request"])
957 && isset($data["poll"])
958 && isset($data["name"])
959 && isset($data["photo"])
964 $data = self::pollHcard($hcard_url, $data, true);
970 * @brief Poll the hcard page (Diaspora and Friendica specific)
972 * @param string $hcard_url Link to the hcard page
973 * @param array $data The already fetched data
974 * @param boolean $dfrn Poll DFRN specific data
976 * @return array hcard data
978 private static function pollHcard($hcard_url, $data, $dfrn = false) {
979 $ret = z_fetch_url($hcard_url);
980 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
983 $content = $ret['body'];
988 $doc = new DOMDocument();
989 if (!@$doc->loadHTML($content)) {
993 $xpath = new DomXPath($doc);
995 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
996 if (!is_object($vcards)) {
1000 if ($vcards->length > 0) {
1001 $vcard = $vcards->item(0);
1003 // We have to discard the guid from the hcard in favour of the guid from lrdd
1004 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1005 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1006 if (($search->length > 0) && ($data["guid"] == "")) {
1007 $data["guid"] = $search->item(0)->nodeValue;
1010 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1011 if ($search->length > 0) {
1012 $data["nick"] = $search->item(0)->nodeValue;
1015 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1016 if ($search->length > 0) {
1017 $data["name"] = $search->item(0)->nodeValue;
1020 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1021 if ($search->length > 0) {
1022 $data["searchable"] = $search->item(0)->nodeValue;
1025 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1026 if ($search->length > 0) {
1027 $data["pubkey"] = $search->item(0)->nodeValue;
1028 if (strstr($data["pubkey"], 'RSA ')) {
1029 $data["pubkey"] = rsatopem($data["pubkey"]);
1033 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1034 if ($search->length > 0) {
1035 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1040 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1041 foreach ($photos as $photo) {
1043 foreach ($photo->attributes as $attribute) {
1044 $attr[$attribute->name] = trim($attribute->value);
1047 if (isset($attr["src"]) && isset($attr["width"])) {
1048 $avatar[$attr["width"]] = $attr["src"];
1051 // We don't have a width. So we just take everything that we got.
1052 // This is a Hubzilla workaround which doesn't send a width.
1053 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1054 $avatar[] = $attr["src"];
1058 if (sizeof($avatar)) {
1060 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1064 // Poll DFRN specific data
1065 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1066 if ($search->length > 0) {
1067 foreach ($search as $link) {
1068 //$data["request"] = $search->item(0)->nodeValue;
1070 foreach ($link->attributes as $attribute) {
1071 $attr[$attribute->name] = trim($attribute->value);
1074 $data[substr($attr["rel"], 5)] = $attr["href"];
1078 // Older Friendica versions had used the "uid" field differently than newer versions
1079 if ($data["nick"] == $data["guid"]) {
1080 unset($data["guid"]);
1089 * @brief Check for Diaspora contact
1091 * @param array $webfinger Webfinger data
1093 * @return array Diaspora data
1095 private static function diaspora($webfinger) {
1099 foreach ($webfinger["links"] as $link) {
1100 if (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
1101 $hcard_url = $link["href"];
1102 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
1103 $data["baseurl"] = trim($link["href"], '/');
1104 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
1105 $data["guid"] = $link["href"];
1106 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
1107 $data["url"] = $link["href"];
1108 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1109 $data["poll"] = $link["href"];
1110 } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
1111 $data["poco"] = $link["href"];
1112 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1113 $data["notify"] = $link["href"];
1114 } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
1115 $data["pubkey"] = base64_decode($link["href"]);
1117 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1118 if (strstr($data["pubkey"], 'RSA ')) {
1119 $data["pubkey"] = rsatopem($data["pubkey"]);
1124 if (!isset($data["url"]) || ($hcard_url == "")) {
1128 if (is_array($webfinger["aliases"])) {
1129 foreach ($webfinger["aliases"] as $alias) {
1130 if (normalise_link($alias) != normalise_link($data["url"]) && ! strstr($alias, "@")) {
1131 $data["alias"] = $alias;
1136 // Fetch further information from the hcard
1137 $data = self::pollHcard($hcard_url, $data);
1143 if (isset($data["url"])
1144 && isset($data["guid"])
1145 && isset($data["baseurl"])
1146 && isset($data["pubkey"])
1147 && ($hcard_url != "")
1149 $data["network"] = NETWORK_DIASPORA;
1151 // The Diaspora handle must always be lowercase
1152 $data["addr"] = strtolower($data["addr"]);
1154 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1155 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1156 $data["batch"] = $data["baseurl"] . "/receive/public";
1165 * @brief Check for OStatus contact
1167 * @param array $webfinger Webfinger data
1168 * @param bool $short Short detection mode
1170 * @return array|bool OStatus data or "false" on error or "true" on short mode
1172 private static function ostatus($webfinger, $short = false) {
1174 if (is_array($webfinger["aliases"])) {
1175 foreach ($webfinger["aliases"] as $alias) {
1176 if (strstr($alias, "@")) {
1177 $data["addr"] = str_replace('acct:', '', $alias);
1182 if (is_string($webfinger["subject"]) && strstr($webfinger["subject"], "@")) {
1183 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1186 if (is_array($webfinger["links"])) {
1187 foreach ($webfinger["links"] as $link) {
1188 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1189 && ($link["type"] == "text/html")
1190 && ($link["href"] != "")
1192 $data["url"] = $link["href"];
1193 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1194 $data["notify"] = $link["href"];
1195 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1196 $data["poll"] = $link["href"];
1197 } elseif (($link["rel"] == "magic-public-key") && ($link["href"] != "")) {
1198 $pubkey = $link["href"];
1200 if (substr($pubkey, 0, 5) === 'data:') {
1201 if (strstr($pubkey, ',')) {
1202 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1204 $pubkey = substr($pubkey, 5);
1206 } elseif (normalise_link($pubkey) == 'http://') {
1207 $ret = z_fetch_url($pubkey);
1208 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1211 $pubkey = $ret['body'];
1214 $key = explode(".", $pubkey);
1216 if (sizeof($key) >= 3) {
1217 $m = base64url_decode($key[1]);
1218 $e = base64url_decode($key[2]);
1219 $data["pubkey"] = metopem($m, $e);
1225 if (isset($data["notify"]) && isset($data["pubkey"])
1226 && isset($data["poll"])
1227 && isset($data["url"])
1229 $data["network"] = NETWORK_OSTATUS;
1238 // Fetch all additional data from the feed
1239 $ret = z_fetch_url($data["poll"]);
1240 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1243 $feed = $ret['body'];
1244 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1249 if ($feed_data["header"]["author-name"] != "") {
1250 $data["name"] = $feed_data["header"]["author-name"];
1252 if ($feed_data["header"]["author-nick"] != "") {
1253 $data["nick"] = $feed_data["header"]["author-nick"];
1255 if ($feed_data["header"]["author-avatar"] != "") {
1256 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1258 if ($feed_data["header"]["author-id"] != "") {
1259 $data["alias"] = $feed_data["header"]["author-id"];
1261 if ($feed_data["header"]["author-location"] != "") {
1262 $data["location"] = $feed_data["header"]["author-location"];
1264 if ($feed_data["header"]["author-about"] != "") {
1265 $data["about"] = $feed_data["header"]["author-about"];
1267 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1268 // So we take the value that we just fetched, although the other one worked as well
1269 if ($feed_data["header"]["author-link"] != "") {
1270 $data["url"] = $feed_data["header"]["author-link"];
1273 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1274 $data['url'] = $data["alias"];
1275 $data["alias"] = '';
1278 /// @todo Fetch location and "about" from the feed as well
1283 * @brief Fetch data from a pump.io profile page
1285 * @param string $profile_link Link to the profile page
1287 * @return array profile data
1289 private static function pumpioProfileData($profile_link) {
1291 $doc = new DOMDocument();
1292 if (!@$doc->loadHTMLFile($profile_link)) {
1296 $xpath = new DomXPath($doc);
1300 // This is ugly - but pump.io doesn't seem to know a better way for it
1301 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1302 $pos = strpos($data["name"], chr(10));
1304 $data["name"] = trim(substr($data["name"], 0, $pos));
1307 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1309 foreach ($avatar->attributes as $attribute) {
1310 if ($attribute->name == "src") {
1311 $data["photo"] = trim($attribute->value);
1316 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
1317 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
1323 * @brief Check for pump.io contact
1325 * @param array $webfinger Webfinger data
1327 * @return array pump.io data
1329 private static function pumpio($webfinger) {
1332 foreach ($webfinger["links"] as $link) {
1333 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1334 && ($link["type"] == "text/html")
1335 && ($link["href"] != "")
1337 $data["url"] = $link["href"];
1338 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1339 $data["notify"] = $link["href"];
1340 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1341 $data["poll"] = $link["href"];
1342 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1343 $data["dialback"] = $link["href"];
1346 if (isset($data["poll"]) && isset($data["notify"])
1347 && isset($data["dialback"])
1348 && isset($data["url"])
1350 // by now we use these fields only for the network type detection
1351 // So we unset all data that isn't used at the moment
1352 unset($data["dialback"]);
1354 $data["network"] = NETWORK_PUMPIO;
1359 $profile_data = self::pumpioProfileData($data["url"]);
1361 if (!$profile_data) {
1365 $data = array_merge($data, $profile_data);
1371 * @brief Check page for feed link
1373 * @param string $url Page link
1375 * @return string feed link
1377 private static function getFeedLink($url) {
1378 $doc = new DOMDocument();
1380 if (!@$doc->loadHTMLFile($url)) {
1384 $xpath = new DomXPath($doc);
1386 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1387 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1388 if (!is_object($feeds)) {
1392 if ($feeds->length == 0) {
1398 foreach ($feeds as $feed) {
1400 foreach ($feed->attributes as $attribute) {
1401 $attr[$attribute->name] = trim($attribute->value);
1404 if ($feed_url == "") {
1405 $feed_url = $attr["href"];
1413 * @brief Check for feed contact
1415 * @param string $url Profile link
1416 * @param boolean $probe Do a probe if the page contains a feed link
1418 * @return array feed data
1420 private static function feed($url, $probe = true) {
1421 $ret = z_fetch_url($url);
1422 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1425 $feed = $ret['body'];
1426 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1433 $feed_url = self::getFeedLink($url);
1439 return self::feed($feed_url, false);
1442 if ($feed_data["header"]["author-name"] != "") {
1443 $data["name"] = $feed_data["header"]["author-name"];
1446 if ($feed_data["header"]["author-nick"] != "") {
1447 $data["nick"] = $feed_data["header"]["author-nick"];
1450 if ($feed_data["header"]["author-avatar"] != "") {
1451 $data["photo"] = $feed_data["header"]["author-avatar"];
1454 if ($feed_data["header"]["author-id"] != "") {
1455 $data["alias"] = $feed_data["header"]["author-id"];
1458 $data["url"] = $url;
1459 $data["poll"] = $url;
1461 if ($feed_data["header"]["author-link"] != "") {
1462 $data["baseurl"] = $feed_data["header"]["author-link"];
1464 $data["baseurl"] = $data["url"];
1467 $data["network"] = NETWORK_FEED;
1473 * @brief Check for mail contact
1475 * @param string $uri Profile link
1476 * @param integer $uid User ID
1478 * @return array mail data
1480 private static function mail($uri, $uid) {
1482 if (!validate_email($uri)) {
1487 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1489 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1491 if (dbm::is_result($x) && dbm::is_result($r)) {
1492 $mailbox = construct_mailbox_name($r[0]);
1494 openssl_private_decrypt(hex2bin($r[0]['pass']), $password, $x[0]['prvkey']);
1495 $mbox = email_connect($mailbox, $r[0]['user'], $password);
1501 $msgs = email_poll($mbox, $uri);
1502 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1504 if (!count($msgs)) {
1509 $phost = substr($uri, strpos($uri, '@') + 1);
1512 $data["addr"] = $uri;
1513 $data["network"] = NETWORK_MAIL;
1514 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1515 $data["nick"] = $data["name"];
1516 $data["photo"] = avatar_img($uri);
1517 $data["url"] = 'mailto:'.$uri;
1518 $data["notify"] = 'smtp '.random_string();
1519 $data["poll"] = 'email '.random_string();
1521 $x = email_msg_meta($mbox, $msgs[0]);
1522 if (stristr($x[0]->from, $uri)) {
1523 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1524 } elseif (stristr($x[0]->to, $uri)) {
1525 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1528 foreach ($adr as $feadr) {
1529 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1530 &&(strcasecmp($feadr->host, $phost) == 0)
1531 && (strlen($feadr->personal))
1533 $personal = imap_mime_header_decode($feadr->personal);
1535 foreach ($personal as $perspart) {
1536 if ($perspart->charset != "default") {
1537 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1539 $data["name"] .= $perspart->text;
1543 $data["name"] = notags($data["name"]);
1547 if (!empty($mbox)) {
1555 * @brief Mix two paths together to possibly fix missing parts
1557 * @param string $avatar Path to the avatar
1558 * @param string $base Another path that is hopefully complete
1560 * @return string fixed avatar path
1562 public static function fixAvatar($avatar, $base) {
1563 $base_parts = parse_url($base);
1565 // Remove all parts that could create a problem
1566 unset($base_parts['path']);
1567 unset($base_parts['query']);
1568 unset($base_parts['fragment']);
1570 $avatar_parts = parse_url($avatar);
1573 $parts = array_merge($base_parts, $avatar_parts);
1575 // And put them together again
1576 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1577 $host = isset($parts['host']) ? $parts['host'] : '';
1578 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1579 $path = isset($parts['path']) ? $parts['path'] : '';
1580 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1581 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1583 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1585 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);