3 namespace Friendica\Network;
6 * @file src/Network/Probe.php
7 * @brief Functions for probing URL
12 use Friendica\Core\Config;
21 require_once 'include/feed.php';
22 require_once 'include/email.php';
23 require_once 'include/network.php';
26 * @brief This class contain functions for probing URL
31 private static $baseurl;
34 * @brief Rearrange the array so that it always has the same order
36 * @param array $data Unordered data
38 * @return array Ordered data
40 private function rearrangeData($data) {
41 $fields = array("name", "nick", "guid", "url", "addr", "alias",
42 "photo", "community", "keywords", "location", "about",
43 "batch", "notify", "poll", "request", "confirm", "poco",
44 "priority", "network", "pubkey", "baseurl");
47 foreach ($fields as $field) {
48 if (isset($data[$field])) {
49 $newdata[$field] = $data[$field];
51 $newdata[$field] = "";
55 // We don't use the "priority" field anymore and replace it with a dummy.
56 $newdata["priority"] = 0;
62 * @brief Check if the hostname belongs to the own server
64 * @param string $host The hostname that is to be checked
66 * @return bool Does the testes hostname belongs to the own server?
68 private function ownHost($host) {
69 $own_host = get_app()->get_hostname();
71 $parts = parse_url($host);
73 if (!isset($parts['scheme'])) {
74 $parts = parse_url('http://'.$host);
77 if (!isset($parts['host'])) {
80 return $parts['host'] == $own_host;
84 * @brief Probes for XRD data
86 * @param string $host The host part of an url
89 * 'lrdd' => Link to LRDD endpoint
90 * 'lrdd-xml' => Link to LRDD endpoint in XML format
91 * 'lrdd-json' => Link to LRDD endpoint in JSON format
93 private function xrd($host) {
95 // Reset the static variable
98 $ssl_url = "https://".$host."/.well-known/host-meta";
99 $url = "http://".$host."/.well-known/host-meta";
101 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
104 logger("Probing for ".$host, LOGGER_DEBUG);
106 $ret = z_fetch_url($ssl_url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
107 if (($ret['errno'] == CURLE_OPERATION_TIMEDOUT) && !self::ownHost($ssl_url)) {
108 logger("Probing timeout for ".$ssl_url, LOGGER_DEBUG);
113 $xrd = parse_xml_string($xml, false);
115 if (!is_object($xrd)) {
116 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
117 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
118 logger("Probing timeout for ".$url, LOGGER_DEBUG);
122 $xrd = parse_xml_string($xml, false);
124 if (!is_object($xrd)) {
125 logger("No xrd object found for ".$host, LOGGER_DEBUG);
129 $links = xml::element_to_array($xrd);
130 if (!isset($links["xrd"]["link"])) {
131 logger("No xrd data found for ".$host, LOGGER_DEBUG);
137 foreach ($links["xrd"]["link"] as $value => $link) {
138 if (isset($link["@attributes"])) {
139 $attributes = $link["@attributes"];
140 } elseif ($value == "@attributes") {
146 if (($attributes["rel"] == "lrdd")
147 && ($attributes["type"] == "application/xrd+xml")
149 $xrd_data["lrdd-xml"] = $attributes["template"];
150 } elseif (($attributes["rel"] == "lrdd")
151 && ($attributes["type"] == "application/json")
153 $xrd_data["lrdd-json"] = $attributes["template"];
154 } elseif ($attributes["rel"] == "lrdd") {
155 $xrd_data["lrdd"] = $attributes["template"];
159 self::$baseurl = "http://".$host;
161 logger("Probing successful for ".$host, LOGGER_DEBUG);
167 * @brief Perform Webfinger lookup and return DFRN data
169 * Given an email style address, perform webfinger lookup and
170 * return the resulting DFRN profile URL, or if no DFRN profile URL
171 * is located, returns an OStatus subscription template (prefixed
172 * with the string 'stat:' to identify it as on OStatus template).
173 * If this isn't an email style address just return $webbie.
174 * Return an empty string if email-style addresses but webfinger fails,
175 * or if the resultant personal XRD doesn't contain a supported
176 * subscription/friend-request attribute.
178 * amended 7/9/2011 to return an hcard which could save potentially loading
179 * a lengthy content page to scrape dfrn attributes
181 * @param string $webbie Address that should be probed
182 * @param string $hcard_url Link to the hcard - is returned by reference
184 * @return string profile link
187 public static function webfingerDfrn($webbie, &$hcard_url) {
191 $links = self::lrdd($webbie);
192 logger('webfingerDfrn: '.$webbie.':'.print_r($links, true), LOGGER_DATA);
194 foreach ($links as $link) {
195 if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
196 $profile_link = $link['@attributes']['href'];
198 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) && ($profile_link == "")) {
199 $profile_link = 'stat:'.$link['@attributes']['template'];
201 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
202 $hcard_url = $link['@attributes']['href'];
206 return $profile_link;
210 * @brief Check an URI for LRDD data
212 * this is a replacement for the "lrdd" function in include/network.php.
213 * It isn't used in this class and has some redundancies in the code.
214 * When time comes we can check the existing calls for "lrdd" if we can rework them.
216 * @param string $uri Address that should be probed
218 * @return array uri data
220 public static function lrdd($uri) {
222 $lrdd = self::xrd($uri);
225 if (is_bool($lrdd)) {
230 $parts = @parse_url($uri);
235 $host = $parts["host"];
236 if (isset($parts["port"])) {
237 $host .= ':'.$parts["port"];
240 $path_parts = explode("/", trim($parts["path"], "/"));
242 $nick = array_pop($path_parts);
245 $lrdd = self::xrd($host);
246 $host .= "/".array_shift($path_parts);
247 } while (!$lrdd && (sizeof($path_parts) > 0));
251 logger("No lrdd data found for ".$uri, LOGGER_DEBUG);
255 foreach ($lrdd as $key => $link) {
260 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
264 $path = str_replace('{uri}', urlencode($uri), $link);
265 $webfinger = self::webfinger($path);
267 if (!$webfinger && (strstr($uri, "@"))) {
268 $path = str_replace('{uri}', urlencode("acct:".$uri), $link);
269 $webfinger = self::webfinger($path);
272 // Special treatment for Mastodon
273 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
274 // But the webfinger for this format fails.
275 if (!$webfinger && isset($nick)) {
276 // Mastodon uses a "@" as prefix for usernames in their url format
277 $nick = ltrim($nick, '@');
279 $addr = $nick."@".$host;
281 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
282 $webfinger = self::webfinger($path);
286 if (!is_array($webfinger["links"])) {
287 logger("No webfinger links found for ".$uri, LOGGER_DEBUG);
293 foreach ($webfinger["links"] as $link) {
294 $data[] = array("@attributes" => $link);
297 if (is_array($webfinger["aliases"])) {
298 foreach ($webfinger["aliases"] as $alias) {
299 $data[] = array("@attributes" =>
300 array("rel" => "alias",
309 * @brief Fetch information (protocol endpoints and user information) about a given uri
311 * @param string $uri Address that should be probed
312 * @param string $network Test for this specific network
313 * @param integer $uid User ID for the probe (only used for mails)
314 * @param boolean $cache Use cached values?
316 * @return array uri data
318 public static function uri($uri, $network = "", $uid = 0, $cache = true) {
321 $result = Cache::get("probe_url:".$network.":".$uri);
322 if (!is_null($result)) {
331 $data = self::detect($uri, $network, $uid);
333 if (!isset($data["url"])) {
337 if ($data["photo"] != "") {
338 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
340 $data["photo"] = App::get_baseurl().'/images/person-175.jpg';
343 if (!isset($data["name"]) || ($data["name"] == "")) {
344 if (isset($data["nick"])) {
345 $data["name"] = $data["nick"];
348 if ($data["name"] == "") {
349 $data["name"] = $data["url"];
353 if (!isset($data["nick"]) || ($data["nick"] == "")) {
354 $data["nick"] = strtolower($data["name"]);
356 if (strpos($data['nick'], ' ')) {
357 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
361 if (self::$baseurl != "") {
362 $data["baseurl"] = self::$baseurl;
365 if (!isset($data["network"])) {
366 $data["network"] = NETWORK_PHANTOM;
369 $data = self::rearrangeData($data);
371 // Only store into the cache if the value seems to be valid
372 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
373 Cache::set("probe_url:".$network.":".$uri, $data, CACHE_DAY);
375 /// @todo temporary fix - we need a real contact update function that updates only changing fields
376 /// The biggest problem is the avatar picture that could have a reduced image size.
377 /// It should only be updated if the existing picture isn't existing anymore.
378 /// We only update the contact when it is no probing for a specific network.
379 if (($data['network'] != NETWORK_FEED)
387 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `url` = '%s', `addr` = '%s',
388 `notify` = '%s', `poll` = '%s', `alias` = '%s', `success_update` = '%s'
389 WHERE `nurl` = '%s' AND NOT `self` AND `uid` = 0",
390 dbesc($data["name"]),
391 dbesc($data["nick"]),
393 dbesc($data["addr"]),
394 dbesc($data["notify"]),
395 dbesc($data["poll"]),
396 dbesc($data["alias"]),
397 dbesc(datetime_convert()),
398 dbesc(normalise_link($data['url']))
407 * @brief Fetch information (protocol endpoints and user information) about a given uri
409 * This function is only called by the "uri" function that adds caching and rearranging of data.
411 * @param string $uri Address that should be probed
412 * @param string $network Test for this specific network
413 * @param integer $uid User ID for the probe (only used for mails)
415 * @return array uri data
417 private function detect($uri, $network, $uid) {
418 $parts = parse_url($uri);
420 if (isset($parts["scheme"]) && isset($parts["host"]) && isset($parts["path"])) {
421 $host = $parts["host"];
422 if (isset($parts["port"])) {
423 $host .= ':'.$parts["port"];
426 if ($host == 'twitter.com') {
427 return array("network" => NETWORK_TWITTER);
429 $lrdd = self::xrd($host);
431 if (is_bool($lrdd)) {
435 $path_parts = explode("/", trim($parts["path"], "/"));
437 while (!$lrdd && (sizeof($path_parts) > 1)) {
438 $host .= "/".array_shift($path_parts);
439 $lrdd = self::xrd($host);
442 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
443 return self::feed($uri);
445 $nick = array_pop($path_parts);
447 // Mastodon uses a "@" as prefix for usernames in their url format
448 $nick = ltrim($nick, '@');
450 $addr = $nick."@".$host;
452 } elseif (strstr($uri, '@')) {
453 // If the URI starts with "mailto:" then jump directly to the mail detection
454 if (strpos($uri, 'mailto:') !== false) {
455 $uri = str_replace('mailto:', '', $uri);
456 return self::mail($uri, $uid);
459 if ($network == NETWORK_MAIL) {
460 return self::mail($uri, $uid);
462 // Remove "acct:" from the URI
463 $uri = str_replace('acct:', '', $uri);
465 $host = substr($uri, strpos($uri, '@') + 1);
466 $nick = substr($uri, 0, strpos($uri, '@'));
468 if (strpos($uri, '@twitter.com')) {
469 return array("network" => NETWORK_TWITTER);
471 $lrdd = self::xrd($host);
473 if (is_bool($lrdd)) {
478 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
479 return self::mail($uri, $uid);
484 logger("Uri ".$uri." was not detectable", LOGGER_DEBUG);
490 /// @todo Do we need the prefix "acct:" or "acct://"?
492 foreach ($lrdd as $key => $link) {
496 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
499 // At first try it with the given uri
500 $path = str_replace('{uri}', urlencode($uri), $link);
501 $webfinger = self::webfinger($path);
503 // We cannot be sure that the detected address was correct, so we don't use the values
504 if ($webfinger && ($uri != $addr)) {
509 // Try webfinger with the address (user@domain.tld)
511 $path = str_replace('{uri}', urlencode($addr), $link);
512 $webfinger = self::webfinger($path);
515 // Mastodon needs to have it with "acct:"
517 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
518 $webfinger = self::webfinger($path);
522 return self::feed($uri);
527 logger("Probing ".$uri, LOGGER_DEBUG);
529 if (in_array($network, array("", NETWORK_DFRN))) {
530 $result = self::dfrn($webfinger);
532 if ((!$result && ($network == "")) || ($network == NETWORK_DIASPORA)) {
533 $result = self::diaspora($webfinger);
535 if ((!$result && ($network == "")) || ($network == NETWORK_OSTATUS)) {
536 $result = self::ostatus($webfinger);
538 if ((!$result && ($network == "")) || ($network == NETWORK_PUMPIO)) {
539 $result = self::pumpio($webfinger);
541 if ((!$result && ($network == "")) || ($network == NETWORK_FEED)) {
542 $result = self::feed($uri);
544 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
545 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
546 if ((!isset($result["nick"]) || ($result["nick"] == "") || (strstr($result["nick"], " "))) && ($nick != "")) {
547 $result["nick"] = $nick;
550 if ((!isset($result["addr"]) || ($result["addr"] == "")) && ($addr != "")) {
551 $result["addr"] = $addr;
555 logger($uri." is ".$result["network"], LOGGER_DEBUG);
557 if (!isset($result["baseurl"]) || ($result["baseurl"] == "")) {
558 $pos = strpos($result["url"], $host);
560 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
568 * @brief Perform a webfinger request.
570 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
572 * @param string $url Address that should be probed
574 * @return array webfinger data
576 private function webfinger($url) {
578 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
581 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
582 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
585 $data = $ret['body'];
587 $xrd = parse_xml_string($data, false);
589 if (!is_object($xrd)) {
590 // If it is not XML, maybe it is JSON
591 $webfinger = json_decode($data, true);
593 if (!isset($webfinger["links"])) {
594 logger("No json webfinger links for ".$url, LOGGER_DEBUG);
601 $xrd_arr = xml::element_to_array($xrd);
602 if (!isset($xrd_arr["xrd"]["link"])) {
603 logger("No XML webfinger links for ".$url, LOGGER_DEBUG);
607 $webfinger = array();
609 if (isset($xrd_arr["xrd"]["subject"])) {
610 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
613 if (isset($xrd_arr["xrd"]["alias"])) {
614 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
617 $webfinger["links"] = array();
619 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
620 if (isset($data["@attributes"])) {
621 $attributes = $data["@attributes"];
622 } elseif ($value == "@attributes") {
628 $webfinger["links"][] = $attributes;
634 * @brief Poll the Friendica specific noscrape page.
636 * "noscrape" is a faster alternative to fetch the data from the hcard.
637 * This functionality was originally created for the directory.
639 * @param string $noscrape_url Link to the noscrape page
640 * @param array $data The already fetched data
642 * @return array noscrape data
644 private function pollNoscrape($noscrape_url, $data) {
645 $ret = z_fetch_url($noscrape_url);
646 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
649 $content = $ret['body'];
651 logger("Empty body for ".$noscrape_url, LOGGER_DEBUG);
655 $json = json_decode($content, true);
656 if (!is_array($json)) {
657 logger("No json data for ".$noscrape_url, LOGGER_DEBUG);
661 if (isset($json["fn"])) {
662 $data["name"] = $json["fn"];
665 if (isset($json["addr"])) {
666 $data["addr"] = $json["addr"];
669 if (isset($json["nick"])) {
670 $data["nick"] = $json["nick"];
673 if (isset($json["comm"])) {
674 $data["community"] = $json["comm"];
677 if (isset($json["tags"])) {
678 $keywords = implode(" ", $json["tags"]);
679 if ($keywords != "") {
680 $data["keywords"] = $keywords;
684 $location = formatted_location($json);
686 $data["location"] = $location;
689 if (isset($json["about"])) {
690 $data["about"] = $json["about"];
693 if (isset($json["key"])) {
694 $data["pubkey"] = $json["key"];
697 if (isset($json["photo"])) {
698 $data["photo"] = $json["photo"];
701 if (isset($json["dfrn-request"])) {
702 $data["request"] = $json["dfrn-request"];
705 if (isset($json["dfrn-confirm"])) {
706 $data["confirm"] = $json["dfrn-confirm"];
709 if (isset($json["dfrn-notify"])) {
710 $data["notify"] = $json["dfrn-notify"];
713 if (isset($json["dfrn-poll"])) {
714 $data["poll"] = $json["dfrn-poll"];
721 * @brief Check for valid DFRN data
723 * @param array $data DFRN data
725 * @return int Number of errors
727 public static function validDfrn($data) {
729 if (!isset($data['key'])) {
732 if (!isset($data['dfrn-request'])) {
735 if (!isset($data['dfrn-confirm'])) {
738 if (!isset($data['dfrn-notify'])) {
741 if (!isset($data['dfrn-poll'])) {
748 * @brief Fetch data from a DFRN profile page and via "noscrape"
750 * @param string $profile_link Link to the profile page
752 * @return array profile data
754 public static function profile($profile_link) {
758 logger("Check profile ".$profile_link, LOGGER_DEBUG);
760 // Fetch data via noscrape - this is faster
761 $noscrape_url = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile_link);
762 $data = self::pollNoscrape($noscrape_url, $data);
764 if (!isset($data["notify"])
765 || !isset($data["confirm"])
766 || !isset($data["request"])
767 || !isset($data["poll"])
768 || !isset($data["poco"])
769 || !isset($data["name"])
770 || !isset($data["photo"])
772 $data = self::pollHcard($profile_link, $data, true);
775 $prof_data = array();
776 $prof_data["addr"] = $data["addr"];
777 $prof_data["nick"] = $data["nick"];
778 $prof_data["dfrn-request"] = $data["request"];
779 $prof_data["dfrn-confirm"] = $data["confirm"];
780 $prof_data["dfrn-notify"] = $data["notify"];
781 $prof_data["dfrn-poll"] = $data["poll"];
782 $prof_data["dfrn-poco"] = $data["poco"];
783 $prof_data["photo"] = $data["photo"];
784 $prof_data["fn"] = $data["name"];
785 $prof_data["key"] = $data["pubkey"];
787 logger("Result for profile ".$profile_link.": ".print_r($prof_data, true), LOGGER_DEBUG);
793 * @brief Check for DFRN contact
795 * @param array $webfinger Webfinger data
797 * @return array DFRN data
799 private function dfrn($webfinger) {
803 foreach ($webfinger["links"] as $link) {
804 if (($link["rel"] == NAMESPACE_DFRN) && ($link["href"] != "")) {
805 $data["network"] = NETWORK_DFRN;
806 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
807 $data["poll"] = $link["href"];
808 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
809 $data["url"] = $link["href"];
810 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
811 $hcard_url = $link["href"];
812 } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
813 $data["poco"] = $link["href"];
814 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && ($link["href"] != "")) {
815 $data["photo"] = $link["href"];
816 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
817 $data["baseurl"] = trim($link["href"], '/');
818 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
819 $data["guid"] = $link["href"];
820 } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
821 $data["pubkey"] = base64_decode($link["href"]);
823 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
824 if (strstr($data["pubkey"], 'RSA ')) {
825 $data["pubkey"] = rsatopem($data["pubkey"]);
830 foreach ($webfinger["aliases"] as $alias) {
831 if (substr($alias, 0, 5) == 'acct:') {
832 $data["addr"] = substr($alias, 5);
836 if (!isset($data["network"]) || ($hcard_url == "")) {
840 // Fetch data via noscrape - this is faster
841 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
842 $data = self::pollNoscrape($noscrape_url, $data);
844 if (isset($data["notify"])
845 && isset($data["confirm"])
846 && isset($data["request"])
847 && isset($data["poll"])
848 && isset($data["name"])
849 && isset($data["photo"])
854 $data = self::pollHcard($hcard_url, $data, true);
860 * @brief Poll the hcard page (Diaspora and Friendica specific)
862 * @param string $hcard_url Link to the hcard page
863 * @param array $data The already fetched data
864 * @param boolean $dfrn Poll DFRN specific data
866 * @return array hcard data
868 private function pollHcard($hcard_url, $data, $dfrn = false) {
869 $ret = z_fetch_url($hcard_url);
870 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
873 $content = $ret['body'];
878 $doc = new DOMDocument();
879 if (!@$doc->loadHTML($content)) {
883 $xpath = new DomXPath($doc);
885 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
886 if (!is_object($vcards)) {
890 if ($vcards->length > 0) {
891 $vcard = $vcards->item(0);
893 // We have to discard the guid from the hcard in favour of the guid from lrdd
894 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
895 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
896 if (($search->length > 0) && ($data["guid"] == "")) {
897 $data["guid"] = $search->item(0)->nodeValue;
900 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
901 if ($search->length > 0) {
902 $data["nick"] = $search->item(0)->nodeValue;
905 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
906 if ($search->length > 0) {
907 $data["name"] = $search->item(0)->nodeValue;
910 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
911 if ($search->length > 0) {
912 $data["searchable"] = $search->item(0)->nodeValue;
915 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
916 if ($search->length > 0) {
917 $data["pubkey"] = $search->item(0)->nodeValue;
918 if (strstr($data["pubkey"], 'RSA ')) {
919 $data["pubkey"] = rsatopem($data["pubkey"]);
923 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
924 if ($search->length > 0) {
925 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
930 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
931 foreach ($photos as $photo) {
933 foreach ($photo->attributes as $attribute) {
934 $attr[$attribute->name] = trim($attribute->value);
937 if (isset($attr["src"]) && isset($attr["width"])) {
938 $avatar[$attr["width"]] = $attr["src"];
941 // We don't have a width. So we just take everything that we got.
942 // This is a Hubzilla workaround which doesn't send a width.
943 if ((sizeof($avatar) == 0) && isset($attr["src"])) {
944 $avatar[] = $attr["src"];
948 if (sizeof($avatar)) {
950 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
954 // Poll DFRN specific data
955 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
956 if ($search->length > 0) {
957 foreach ($search as $link) {
958 //$data["request"] = $search->item(0)->nodeValue;
960 foreach ($link->attributes as $attribute) {
961 $attr[$attribute->name] = trim($attribute->value);
964 $data[substr($attr["rel"], 5)] = $attr["href"];
968 // Older Friendica versions had used the "uid" field differently than newer versions
969 if ($data["nick"] == $data["guid"]) {
970 unset($data["guid"]);
979 * @brief Check for Diaspora contact
981 * @param array $webfinger Webfinger data
983 * @return array Diaspora data
985 private function diaspora($webfinger) {
989 foreach ($webfinger["links"] as $link) {
990 if (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
991 $hcard_url = $link["href"];
992 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
993 $data["baseurl"] = trim($link["href"], '/');
994 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
995 $data["guid"] = $link["href"];
996 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
997 $data["url"] = $link["href"];
998 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
999 $data["poll"] = $link["href"];
1000 } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
1001 $data["poco"] = $link["href"];
1002 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1003 $data["notify"] = $link["href"];
1004 } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
1005 $data["pubkey"] = base64_decode($link["href"]);
1007 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1008 if (strstr($data["pubkey"], 'RSA ')) {
1009 $data["pubkey"] = rsatopem($data["pubkey"]);
1014 if (!isset($data["url"]) || ($hcard_url == "")) {
1018 if (is_array($webfinger["aliases"])) {
1019 foreach ($webfinger["aliases"] as $alias) {
1020 if (normalise_link($alias) != normalise_link($data["url"]) && ! strstr($alias, "@")) {
1021 $data["alias"] = $alias;
1026 // Fetch further information from the hcard
1027 $data = self::pollHcard($hcard_url, $data);
1033 if (isset($data["url"])
1034 && isset($data["guid"])
1035 && isset($data["baseurl"])
1036 && isset($data["pubkey"])
1037 && ($hcard_url != "")
1039 $data["network"] = NETWORK_DIASPORA;
1041 // The Diaspora handle must always be lowercase
1042 $data["addr"] = strtolower($data["addr"]);
1044 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1045 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1046 $data["batch"] = $data["baseurl"] . "/receive/public";
1055 * @brief Check for OStatus contact
1057 * @param array $webfinger Webfinger data
1059 * @return array OStatus data
1061 private function ostatus($webfinger) {
1063 if (is_array($webfinger["aliases"])) {
1064 foreach ($webfinger["aliases"] as $alias) {
1065 if (strstr($alias, "@")) {
1066 $data["addr"] = str_replace('acct:', '', $alias);
1071 if (is_string($webfinger["subject"]) && strstr($webfinger["subject"], "@")) {
1072 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1075 foreach ($webfinger["links"] as $link) {
1076 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1077 && ($link["type"] == "text/html")
1078 && ($link["href"] != "")
1080 $data["url"] = $link["href"];
1081 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1082 $data["notify"] = $link["href"];
1083 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1084 $data["poll"] = $link["href"];
1085 } elseif (($link["rel"] == "magic-public-key") && ($link["href"] != "")) {
1086 $pubkey = $link["href"];
1088 if (substr($pubkey, 0, 5) === 'data:') {
1089 if (strstr($pubkey, ',')) {
1090 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1092 $pubkey = substr($pubkey, 5);
1094 } elseif (normalise_link($pubkey) == 'http://') {
1095 $ret = z_fetch_url($pubkey);
1096 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1099 $pubkey = $ret['body'];
1102 $key = explode(".", $pubkey);
1104 if (sizeof($key) >= 3) {
1105 $m = base64url_decode($key[1]);
1106 $e = base64url_decode($key[2]);
1107 $data["pubkey"] = metopem($m, $e);
1112 if (isset($data["notify"]) && isset($data["pubkey"])
1113 && isset($data["poll"])
1114 && isset($data["url"])
1116 $data["network"] = NETWORK_OSTATUS;
1120 // Fetch all additional data from the feed
1121 $ret = z_fetch_url($data["poll"]);
1122 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1125 $feed = $ret['body'];
1126 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1130 if ($feed_data["header"]["author-name"] != "") {
1131 $data["name"] = $feed_data["header"]["author-name"];
1133 if ($feed_data["header"]["author-nick"] != "") {
1134 $data["nick"] = $feed_data["header"]["author-nick"];
1136 if ($feed_data["header"]["author-avatar"] != "") {
1137 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1139 if ($feed_data["header"]["author-id"] != "") {
1140 $data["alias"] = $feed_data["header"]["author-id"];
1142 if ($feed_data["header"]["author-location"] != "") {
1143 $data["location"] = $feed_data["header"]["author-location"];
1145 if ($feed_data["header"]["author-about"] != "") {
1146 $data["about"] = $feed_data["header"]["author-about"];
1148 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1149 // So we take the value that we just fetched, although the other one worked as well
1150 if ($feed_data["header"]["author-link"] != "") {
1151 $data["url"] = $feed_data["header"]["author-link"];
1153 /// @todo Fetch location and "about" from the feed as well
1158 * @brief Fetch data from a pump.io profile page
1160 * @param string $profile_link Link to the profile page
1162 * @return array profile data
1164 private function pumpioProfileData($profile_link) {
1166 $doc = new DOMDocument();
1167 if (!@$doc->loadHTMLFile($profile_link)) {
1171 $xpath = new DomXPath($doc);
1175 // This is ugly - but pump.io doesn't seem to know a better way for it
1176 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1177 $pos = strpos($data["name"], chr(10));
1179 $data["name"] = trim(substr($data["name"], 0, $pos));
1182 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1184 foreach ($avatar->attributes as $attribute) {
1185 if ($attribute->name == "src") {
1186 $data["photo"] = trim($attribute->value);
1191 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
1192 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
1198 * @brief Check for pump.io contact
1200 * @param array $webfinger Webfinger data
1202 * @return array pump.io data
1204 private function pumpio($webfinger) {
1207 foreach ($webfinger["links"] as $link) {
1208 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1209 && ($link["type"] == "text/html")
1210 && ($link["href"] != "")
1212 $data["url"] = $link["href"];
1213 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1214 $data["notify"] = $link["href"];
1215 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1216 $data["poll"] = $link["href"];
1217 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1218 $data["dialback"] = $link["href"];
1221 if (isset($data["poll"]) && isset($data["notify"])
1222 && isset($data["dialback"])
1223 && isset($data["url"])
1225 // by now we use these fields only for the network type detection
1226 // So we unset all data that isn't used at the moment
1227 unset($data["dialback"]);
1229 $data["network"] = NETWORK_PUMPIO;
1234 $profile_data = self::pumpioProfileData($data["url"]);
1236 if (!$profile_data) {
1240 $data = array_merge($data, $profile_data);
1246 * @brief Check page for feed link
1248 * @param string $url Page link
1250 * @return string feed link
1252 private function getFeedLink($url) {
1253 $doc = new DOMDocument();
1255 if (!@$doc->loadHTMLFile($url)) {
1259 $xpath = new DomXPath($doc);
1261 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1262 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1263 if (!is_object($feeds)) {
1267 if ($feeds->length == 0) {
1273 foreach ($feeds as $feed) {
1275 foreach ($feed->attributes as $attribute) {
1276 $attr[$attribute->name] = trim($attribute->value);
1279 if ($feed_url == "") {
1280 $feed_url = $attr["href"];
1288 * @brief Check for feed contact
1290 * @param string $url Profile link
1291 * @param boolean $probe Do a probe if the page contains a feed link
1293 * @return array feed data
1295 private function feed($url, $probe = true) {
1296 $ret = z_fetch_url($url);
1297 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1300 $feed = $ret['body'];
1301 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1308 $feed_url = self::getFeedLink($url);
1314 return self::feed($feed_url, false);
1317 if ($feed_data["header"]["author-name"] != "") {
1318 $data["name"] = $feed_data["header"]["author-name"];
1321 if ($feed_data["header"]["author-nick"] != "") {
1322 $data["nick"] = $feed_data["header"]["author-nick"];
1325 if ($feed_data["header"]["author-avatar"] != "") {
1326 $data["photo"] = $feed_data["header"]["author-avatar"];
1329 if ($feed_data["header"]["author-id"] != "") {
1330 $data["alias"] = $feed_data["header"]["author-id"];
1333 $data["url"] = $url;
1334 $data["poll"] = $url;
1336 if ($feed_data["header"]["author-link"] != "") {
1337 $data["baseurl"] = $feed_data["header"]["author-link"];
1339 $data["baseurl"] = $data["url"];
1342 $data["network"] = NETWORK_FEED;
1348 * @brief Check for mail contact
1350 * @param string $uri Profile link
1351 * @param integer $uid User ID
1353 * @return array mail data
1355 private function mail($uri, $uid) {
1357 if (!validate_email($uri)) {
1361 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1363 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1365 if (dbm::is_result($x) && dbm::is_result($r)) {
1366 $mailbox = construct_mailbox_name($r[0]);
1368 openssl_private_decrypt(hex2bin($r[0]['pass']), $password, $x[0]['prvkey']);
1369 $mbox = email_connect($mailbox, $r[0]['user'], $password);
1375 $msgs = email_poll($mbox, $uri);
1376 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1378 if (!count($msgs)) {
1382 $phost = substr($uri, strpos($uri, '@') + 1);
1385 $data["addr"] = $uri;
1386 $data["network"] = NETWORK_MAIL;
1387 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1388 $data["nick"] = $data["name"];
1389 $data["photo"] = avatar_img($uri);
1390 $data["url"] = 'http://'.$phost."/".$data["nick"];
1391 $data["notify"] = 'smtp '.random_string();
1392 $data["poll"] = 'email '.random_string();
1394 $x = email_msg_meta($mbox, $msgs[0]);
1395 if (stristr($x[0]->from, $uri)) {
1396 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1397 } elseif (stristr($x[0]->to, $uri)) {
1398 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1401 foreach ($adr as $feadr) {
1402 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1403 &&(strcasecmp($feadr->host, $phost) == 0)
1404 && (strlen($feadr->personal))
1406 $personal = imap_mime_header_decode($feadr->personal);
1408 foreach ($personal as $perspart) {
1409 if ($perspart->charset != "default") {
1410 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1412 $data["name"] .= $perspart->text;
1416 $data["name"] = notags($data["name"]);
1426 * @brief Mix two paths together to possibly fix missing parts
1428 * @param string $avatar Path to the avatar
1429 * @param string $base Another path that is hopefully complete
1431 * @return string fixed avatar path
1433 public static function fixAvatar($avatar, $base) {
1434 $base_parts = parse_url($base);
1436 // Remove all parts that could create a problem
1437 unset($base_parts['path']);
1438 unset($base_parts['query']);
1439 unset($base_parts['fragment']);
1441 $avatar_parts = parse_url($avatar);
1444 $parts = array_merge($base_parts, $avatar_parts);
1446 // And put them together again
1447 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1448 $host = isset($parts['host']) ? $parts['host'] : '';
1449 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1450 $path = isset($parts['path']) ? $parts['path'] : '';
1451 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1452 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1454 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1456 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);