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) AND !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 AND ($attributes["type"] == "application/xrd+xml")
149 $xrd_data["lrdd-xml"] = $attributes["template"];
150 } elseif (($attributes["rel"] == "lrdd")
151 AND ($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) AND ($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);
226 $parts = @parse_url($uri);
231 $host = $parts["host"];
232 if (isset($parts["port"])) {
233 $host .= ':'.$parts["port"];
236 $path_parts = explode("/", trim($parts["path"], "/"));
238 $nick = array_pop($path_parts);
241 $lrdd = self::xrd($host);
242 $host .= "/".array_shift($path_parts);
243 } while (!$lrdd AND (sizeof($path_parts) > 0));
247 logger("No lrdd data found for ".$uri, LOGGER_DEBUG);
251 foreach ($lrdd as $key => $link) {
256 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
260 $path = str_replace('{uri}', urlencode($uri), $link);
261 $webfinger = self::webfinger($path);
263 if (!$webfinger AND (strstr($uri, "@"))) {
264 $path = str_replace('{uri}', urlencode("acct:".$uri), $link);
265 $webfinger = self::webfinger($path);
268 // Special treatment for Mastodon
269 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
270 // But the webfinger for this format fails.
271 if (!$webfinger AND isset($nick)) {
272 // Mastodon uses a "@" as prefix for usernames in their url format
273 $nick = ltrim($nick, '@');
275 $addr = $nick."@".$host;
277 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
278 $webfinger = self::webfinger($path);
282 if (!is_array($webfinger["links"])) {
283 logger("No webfinger links found for ".$uri, LOGGER_DEBUG);
289 foreach ($webfinger["links"] as $link) {
290 $data[] = array("@attributes" => $link);
293 if (is_array($webfinger["aliases"])) {
294 foreach ($webfinger["aliases"] as $alias) {
295 $data[] = array("@attributes" =>
296 array("rel" => "alias",
305 * @brief Fetch information (protocol endpoints and user information) about a given uri
307 * @param string $uri Address that should be probed
308 * @param string $network Test for this specific network
309 * @param integer $uid User ID for the probe (only used for mails)
310 * @param boolean $cache Use cached values?
312 * @return array uri data
314 public static function uri($uri, $network = "", $uid = 0, $cache = true) {
317 $result = Cache::get("probe_url:".$network.":".$uri);
318 if (!is_null($result)) {
327 $data = self::detect($uri, $network, $uid);
329 if (!isset($data["url"])) {
333 if ($data["photo"] != "") {
334 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
336 $data["photo"] = App::get_baseurl().'/images/person-175.jpg';
339 if (!isset($data["name"]) OR ($data["name"] == "")) {
340 if (isset($data["nick"])) {
341 $data["name"] = $data["nick"];
344 if ($data["name"] == "") {
345 $data["name"] = $data["url"];
349 if (!isset($data["nick"]) OR ($data["nick"] == "")) {
350 $data["nick"] = strtolower($data["name"]);
352 if (strpos($data['nick'], ' ')) {
353 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
357 if (self::$baseurl != "") {
358 $data["baseurl"] = self::$baseurl;
361 if (!isset($data["network"])) {
362 $data["network"] = NETWORK_PHANTOM;
365 $data = self::rearrangeData($data);
367 // Only store into the cache if the value seems to be valid
368 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
369 Cache::set("probe_url:".$network.":".$uri, $data, CACHE_DAY);
371 /// @todo temporary fix - we need a real contact update function that updates only changing fields
372 /// The biggest problem is the avatar picture that could have a reduced image size.
373 /// It should only be updated if the existing picture isn't existing anymore.
374 /// We only update the contact when it is no probing for a specific network.
375 if (($data['network'] != NETWORK_FEED)
383 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `url` = '%s', `addr` = '%s',
384 `notify` = '%s', `poll` = '%s', `alias` = '%s', `success_update` = '%s'
385 WHERE `nurl` = '%s' AND NOT `self` AND `uid` = 0",
386 dbesc($data["name"]),
387 dbesc($data["nick"]),
389 dbesc($data["addr"]),
390 dbesc($data["notify"]),
391 dbesc($data["poll"]),
392 dbesc($data["alias"]),
393 dbesc(datetime_convert()),
394 dbesc(normalise_link($data['url']))
403 * @brief Fetch information (protocol endpoints and user information) about a given uri
405 * This function is only called by the "uri" function that adds caching and rearranging of data.
407 * @param string $uri Address that should be probed
408 * @param string $network Test for this specific network
409 * @param integer $uid User ID for the probe (only used for mails)
411 * @return array uri data
413 private function detect($uri, $network, $uid) {
414 $parts = parse_url($uri);
416 if (isset($parts["scheme"]) AND isset($parts["host"]) AND isset($parts["path"])) {
417 $host = $parts["host"];
418 if (isset($parts["port"])) {
419 $host .= ':'.$parts["port"];
422 if ($host == 'twitter.com') {
423 return array("network" => NETWORK_TWITTER);
425 $lrdd = self::xrd($host);
427 $path_parts = explode("/", trim($parts["path"], "/"));
429 while (!$lrdd AND (sizeof($path_parts) > 1)) {
430 $host .= "/".array_shift($path_parts);
431 $lrdd = self::xrd($host);
434 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
435 return self::feed($uri);
437 $nick = array_pop($path_parts);
439 // Mastodon uses a "@" as prefix for usernames in their url format
440 $nick = ltrim($nick, '@');
442 $addr = $nick."@".$host;
444 } elseif (strstr($uri, '@')) {
445 // If the URI starts with "mailto:" then jump directly to the mail detection
446 if (strpos($uri, 'mailto:') !== false) {
447 $uri = str_replace('mailto:', '', $uri);
448 return self::mail($uri, $uid);
451 if ($network == NETWORK_MAIL) {
452 return self::mail($uri, $uid);
454 // Remove "acct:" from the URI
455 $uri = str_replace('acct:', '', $uri);
457 $host = substr($uri, strpos($uri, '@') + 1);
458 $nick = substr($uri, 0, strpos($uri, '@'));
460 if (strpos($uri, '@twitter.com')) {
461 return array("network" => NETWORK_TWITTER);
463 $lrdd = self::xrd($host);
466 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
467 return self::mail($uri, $uid);
472 logger("Uri ".$uri." was not detectable", LOGGER_DEBUG);
478 /// @todo Do we need the prefix "acct:" or "acct://"?
480 foreach ($lrdd as $key => $link) {
484 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
487 // At first try it with the given uri
488 $path = str_replace('{uri}', urlencode($uri), $link);
489 $webfinger = self::webfinger($path);
491 // We cannot be sure that the detected address was correct, so we don't use the values
492 if ($webfinger AND ($uri != $addr)) {
497 // Try webfinger with the address (user@domain.tld)
499 $path = str_replace('{uri}', urlencode($addr), $link);
500 $webfinger = self::webfinger($path);
503 // Mastodon needs to have it with "acct:"
505 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
506 $webfinger = self::webfinger($path);
510 return self::feed($uri);
515 logger("Probing ".$uri, LOGGER_DEBUG);
517 if (in_array($network, array("", NETWORK_DFRN))) {
518 $result = self::dfrn($webfinger);
520 if ((!$result AND ($network == "")) OR ($network == NETWORK_DIASPORA)) {
521 $result = self::diaspora($webfinger);
523 if ((!$result AND ($network == "")) OR ($network == NETWORK_OSTATUS)) {
524 $result = self::ostatus($webfinger);
526 if ((!$result AND ($network == "")) OR ($network == NETWORK_PUMPIO)) {
527 $result = self::pumpio($webfinger);
529 if ((!$result AND ($network == "")) OR ($network == NETWORK_FEED)) {
530 $result = self::feed($uri);
532 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
533 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
534 if ((!isset($result["nick"]) OR ($result["nick"] == "") OR (strstr($result["nick"], " "))) AND ($nick != "")) {
535 $result["nick"] = $nick;
538 if ((!isset($result["addr"]) OR ($result["addr"] == "")) AND ($addr != "")) {
539 $result["addr"] = $addr;
543 logger($uri." is ".$result["network"], LOGGER_DEBUG);
545 if (!isset($result["baseurl"]) OR ($result["baseurl"] == "")) {
546 $pos = strpos($result["url"], $host);
548 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
556 * @brief Perform a webfinger request.
558 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
560 * @param string $url Address that should be probed
562 * @return array webfinger data
564 private function webfinger($url) {
566 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
569 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
570 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
573 $data = $ret['body'];
575 $xrd = parse_xml_string($data, false);
577 if (!is_object($xrd)) {
578 // If it is not XML, maybe it is JSON
579 $webfinger = json_decode($data, true);
581 if (!isset($webfinger["links"])) {
582 logger("No json webfinger links for ".$url, LOGGER_DEBUG);
589 $xrd_arr = xml::element_to_array($xrd);
590 if (!isset($xrd_arr["xrd"]["link"])) {
591 logger("No XML webfinger links for ".$url, LOGGER_DEBUG);
595 $webfinger = array();
597 if (isset($xrd_arr["xrd"]["subject"])) {
598 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
601 if (isset($xrd_arr["xrd"]["alias"])) {
602 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
605 $webfinger["links"] = array();
607 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
608 if (isset($data["@attributes"])) {
609 $attributes = $data["@attributes"];
610 } elseif ($value == "@attributes") {
616 $webfinger["links"][] = $attributes;
622 * @brief Poll the Friendica specific noscrape page.
624 * "noscrape" is a faster alternative to fetch the data from the hcard.
625 * This functionality was originally created for the directory.
627 * @param string $noscrape_url Link to the noscrape page
628 * @param array $data The already fetched data
630 * @return array noscrape data
632 private function pollNoscrape($noscrape_url, $data) {
633 $ret = z_fetch_url($noscrape_url);
634 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
637 $content = $ret['body'];
639 logger("Empty body for ".$noscrape_url, LOGGER_DEBUG);
643 $json = json_decode($content, true);
644 if (!is_array($json)) {
645 logger("No json data for ".$noscrape_url, LOGGER_DEBUG);
649 if (isset($json["fn"])) {
650 $data["name"] = $json["fn"];
653 if (isset($json["addr"])) {
654 $data["addr"] = $json["addr"];
657 if (isset($json["nick"])) {
658 $data["nick"] = $json["nick"];
661 if (isset($json["comm"])) {
662 $data["community"] = $json["comm"];
665 if (isset($json["tags"])) {
666 $keywords = implode(" ", $json["tags"]);
667 if ($keywords != "") {
668 $data["keywords"] = $keywords;
672 $location = formatted_location($json);
674 $data["location"] = $location;
677 if (isset($json["about"])) {
678 $data["about"] = $json["about"];
681 if (isset($json["key"])) {
682 $data["pubkey"] = $json["key"];
685 if (isset($json["photo"])) {
686 $data["photo"] = $json["photo"];
689 if (isset($json["dfrn-request"])) {
690 $data["request"] = $json["dfrn-request"];
693 if (isset($json["dfrn-confirm"])) {
694 $data["confirm"] = $json["dfrn-confirm"];
697 if (isset($json["dfrn-notify"])) {
698 $data["notify"] = $json["dfrn-notify"];
701 if (isset($json["dfrn-poll"])) {
702 $data["poll"] = $json["dfrn-poll"];
709 * @brief Check for valid DFRN data
711 * @param array $data DFRN data
713 * @return int Number of errors
715 public static function validDfrn($data) {
717 if (!isset($data['key'])) {
720 if (!isset($data['dfrn-request'])) {
723 if (!isset($data['dfrn-confirm'])) {
726 if (!isset($data['dfrn-notify'])) {
729 if (!isset($data['dfrn-poll'])) {
736 * @brief Fetch data from a DFRN profile page and via "noscrape"
738 * @param string $profile_link Link to the profile page
740 * @return array profile data
742 public static function profile($profile_link) {
746 logger("Check profile ".$profile_link, LOGGER_DEBUG);
748 // Fetch data via noscrape - this is faster
749 $noscrape_url = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile_link);
750 $data = self::pollNoscrape($noscrape_url, $data);
752 if (!isset($data["notify"])
753 OR !isset($data["confirm"])
754 OR !isset($data["request"])
755 OR !isset($data["poll"])
756 OR !isset($data["poco"])
757 OR !isset($data["name"])
758 OR !isset($data["photo"])
760 $data = self::pollHcard($profile_link, $data, true);
763 $prof_data = array();
764 $prof_data["addr"] = $data["addr"];
765 $prof_data["nick"] = $data["nick"];
766 $prof_data["dfrn-request"] = $data["request"];
767 $prof_data["dfrn-confirm"] = $data["confirm"];
768 $prof_data["dfrn-notify"] = $data["notify"];
769 $prof_data["dfrn-poll"] = $data["poll"];
770 $prof_data["dfrn-poco"] = $data["poco"];
771 $prof_data["photo"] = $data["photo"];
772 $prof_data["fn"] = $data["name"];
773 $prof_data["key"] = $data["pubkey"];
775 logger("Result for profile ".$profile_link.": ".print_r($prof_data, true), LOGGER_DEBUG);
781 * @brief Check for DFRN contact
783 * @param array $webfinger Webfinger data
785 * @return array DFRN data
787 private function dfrn($webfinger) {
791 foreach ($webfinger["links"] as $link) {
792 if (($link["rel"] == NAMESPACE_DFRN) AND ($link["href"] != "")) {
793 $data["network"] = NETWORK_DFRN;
794 } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
795 $data["poll"] = $link["href"];
796 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND ($link["type"] == "text/html") AND ($link["href"] != "")) {
797 $data["url"] = $link["href"];
798 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != "")) {
799 $hcard_url = $link["href"];
800 } elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != "")) {
801 $data["poco"] = $link["href"];
802 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") AND ($link["href"] != "")) {
803 $data["photo"] = $link["href"];
804 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != "")) {
805 $data["baseurl"] = trim($link["href"], '/');
806 } elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != "")) {
807 $data["guid"] = $link["href"];
808 } elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
809 $data["pubkey"] = base64_decode($link["href"]);
811 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
812 if (strstr($data["pubkey"], 'RSA ')) {
813 $data["pubkey"] = rsatopem($data["pubkey"]);
818 if (!isset($data["network"]) OR ($hcard_url == "")) {
822 // Fetch data via noscrape - this is faster
823 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
824 $data = self::pollNoscrape($noscrape_url, $data);
826 if (isset($data["notify"])
827 AND isset($data["confirm"])
828 AND isset($data["request"])
829 AND isset($data["poll"])
830 AND isset($data["name"])
831 AND isset($data["photo"])
836 $data = self::pollHcard($hcard_url, $data, true);
842 * @brief Poll the hcard page (Diaspora and Friendica specific)
844 * @param string $hcard_url Link to the hcard page
845 * @param array $data The already fetched data
846 * @param boolean $dfrn Poll DFRN specific data
848 * @return array hcard data
850 private function pollHcard($hcard_url, $data, $dfrn = false) {
851 $ret = z_fetch_url($hcard_url);
852 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
855 $content = $ret['body'];
860 $doc = new DOMDocument();
861 if (!@$doc->loadHTML($content)) {
865 $xpath = new DomXPath($doc);
867 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
868 if (!is_object($vcards)) {
872 if ($vcards->length > 0) {
873 $vcard = $vcards->item(0);
875 // We have to discard the guid from the hcard in favour of the guid from lrdd
876 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
877 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
878 if (($search->length > 0) AND ($data["guid"] == "")) {
879 $data["guid"] = $search->item(0)->nodeValue;
882 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
883 if ($search->length > 0) {
884 $data["nick"] = $search->item(0)->nodeValue;
887 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
888 if ($search->length > 0) {
889 $data["name"] = $search->item(0)->nodeValue;
892 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
893 if ($search->length > 0) {
894 $data["searchable"] = $search->item(0)->nodeValue;
897 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
898 if ($search->length > 0) {
899 $data["pubkey"] = $search->item(0)->nodeValue;
900 if (strstr($data["pubkey"], 'RSA ')) {
901 $data["pubkey"] = rsatopem($data["pubkey"]);
905 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
906 if ($search->length > 0) {
907 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
912 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
913 foreach ($photos as $photo) {
915 foreach ($photo->attributes as $attribute) {
916 $attr[$attribute->name] = trim($attribute->value);
919 if (isset($attr["src"]) AND isset($attr["width"])) {
920 $avatar[$attr["width"]] = $attr["src"];
923 // We don't have a width. So we just take everything that we got.
924 // This is a Hubzilla workaround which doesn't send a width.
925 if ((sizeof($avatar) == 0) AND isset($attr["src"])) {
926 $avatar[] = $attr["src"];
930 if (sizeof($avatar)) {
932 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
936 // Poll DFRN specific data
937 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
938 if ($search->length > 0) {
939 foreach ($search as $link) {
940 //$data["request"] = $search->item(0)->nodeValue;
942 foreach ($link->attributes as $attribute) {
943 $attr[$attribute->name] = trim($attribute->value);
946 $data[substr($attr["rel"], 5)] = $attr["href"];
950 // Older Friendica versions had used the "uid" field differently than newer versions
951 if ($data["nick"] == $data["guid"]) {
952 unset($data["guid"]);
961 * @brief Check for Diaspora contact
963 * @param array $webfinger Webfinger data
965 * @return array Diaspora data
967 private function diaspora($webfinger) {
971 foreach ($webfinger["links"] as $link) {
972 if (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != "")) {
973 $hcard_url = $link["href"];
974 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != "")) {
975 $data["baseurl"] = trim($link["href"], '/');
976 } elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != "")) {
977 $data["guid"] = $link["href"];
978 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND ($link["type"] == "text/html") AND ($link["href"] != "")) {
979 $data["url"] = $link["href"];
980 } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
981 $data["poll"] = $link["href"];
982 } elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != "")) {
983 $data["poco"] = $link["href"];
984 } elseif (($link["rel"] == "salmon") AND ($link["href"] != "")) {
985 $data["notify"] = $link["href"];
986 } elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
987 $data["pubkey"] = base64_decode($link["href"]);
989 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
990 if (strstr($data["pubkey"], 'RSA ')) {
991 $data["pubkey"] = rsatopem($data["pubkey"]);
996 if (!isset($data["url"]) OR ($hcard_url == "")) {
1000 if (is_array($webfinger["aliases"])) {
1001 foreach ($webfinger["aliases"] as $alias) {
1002 if (normalise_link($alias) != normalise_link($data["url"]) AND ! strstr($alias, "@")) {
1003 $data["alias"] = $alias;
1008 // Fetch further information from the hcard
1009 $data = self::pollHcard($hcard_url, $data);
1015 if (isset($data["url"])
1016 AND isset($data["guid"])
1017 AND isset($data["baseurl"])
1018 AND isset($data["pubkey"])
1019 AND ($hcard_url != "")
1021 $data["network"] = NETWORK_DIASPORA;
1023 // The Diaspora handle must always be lowercase
1024 $data["addr"] = strtolower($data["addr"]);
1026 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1027 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1028 $data["batch"] = $data["baseurl"] . "/receive/public";
1037 * @brief Check for OStatus contact
1039 * @param array $webfinger Webfinger data
1041 * @return array OStatus data
1043 private function ostatus($webfinger) {
1045 if (is_array($webfinger["aliases"])) {
1046 foreach ($webfinger["aliases"] as $alias) {
1047 if (strstr($alias, "@")) {
1048 $data["addr"] = str_replace('acct:', '', $alias);
1053 if (is_string($webfinger["subject"]) AND strstr($webfinger["subject"], "@")) {
1054 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1057 foreach ($webfinger["links"] as $link) {
1058 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1059 AND ($link["type"] == "text/html")
1060 AND ($link["href"] != "")
1062 $data["url"] = $link["href"];
1063 } elseif (($link["rel"] == "salmon") AND ($link["href"] != "")) {
1064 $data["notify"] = $link["href"];
1065 } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
1066 $data["poll"] = $link["href"];
1067 } elseif (($link["rel"] == "magic-public-key") AND ($link["href"] != "")) {
1068 $pubkey = $link["href"];
1070 if (substr($pubkey, 0, 5) === 'data:') {
1071 if (strstr($pubkey, ',')) {
1072 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1074 $pubkey = substr($pubkey, 5);
1076 } elseif (normalise_link($pubkey) == 'http://') {
1077 $ret = z_fetch_url($pubkey);
1078 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1081 $pubkey = $ret['body'];
1084 $key = explode(".", $pubkey);
1086 if (sizeof($key) >= 3) {
1087 $m = base64url_decode($key[1]);
1088 $e = base64url_decode($key[2]);
1089 $data["pubkey"] = metopem($m, $e);
1094 if (isset($data["notify"]) AND isset($data["pubkey"])
1095 AND isset($data["poll"])
1096 AND isset($data["url"])
1098 $data["network"] = NETWORK_OSTATUS;
1102 // Fetch all additional data from the feed
1103 $ret = z_fetch_url($data["poll"]);
1104 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1107 $feed = $ret['body'];
1108 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1112 if ($feed_data["header"]["author-name"] != "") {
1113 $data["name"] = $feed_data["header"]["author-name"];
1115 if ($feed_data["header"]["author-nick"] != "") {
1116 $data["nick"] = $feed_data["header"]["author-nick"];
1118 if ($feed_data["header"]["author-avatar"] != "") {
1119 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1121 if ($feed_data["header"]["author-id"] != "") {
1122 $data["alias"] = $feed_data["header"]["author-id"];
1124 if ($feed_data["header"]["author-location"] != "") {
1125 $data["location"] = $feed_data["header"]["author-location"];
1127 if ($feed_data["header"]["author-about"] != "") {
1128 $data["about"] = $feed_data["header"]["author-about"];
1130 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1131 // So we take the value that we just fetched, although the other one worked as well
1132 if ($feed_data["header"]["author-link"] != "") {
1133 $data["url"] = $feed_data["header"]["author-link"];
1135 /// @todo Fetch location and "about" from the feed as well
1140 * @brief Fetch data from a pump.io profile page
1142 * @param string $profile_link Link to the profile page
1144 * @return array profile data
1146 private function pumpioProfileData($profile_link) {
1148 $doc = new DOMDocument();
1149 if (!@$doc->loadHTMLFile($profile_link)) {
1153 $xpath = new DomXPath($doc);
1157 // This is ugly - but pump.io doesn't seem to know a better way for it
1158 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1159 $pos = strpos($data["name"], chr(10));
1161 $data["name"] = trim(substr($data["name"], 0, $pos));
1164 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1166 foreach ($avatar->attributes as $attribute) {
1167 if ($attribute->name == "src") {
1168 $data["photo"] = trim($attribute->value);
1173 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
1174 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
1180 * @brief Check for pump.io contact
1182 * @param array $webfinger Webfinger data
1184 * @return array pump.io data
1186 private function pumpio($webfinger) {
1189 foreach ($webfinger["links"] as $link) {
1190 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1191 AND ($link["type"] == "text/html")
1192 AND ($link["href"] != "")
1194 $data["url"] = $link["href"];
1195 } elseif (($link["rel"] == "activity-inbox") AND ($link["href"] != "")) {
1196 $data["notify"] = $link["href"];
1197 } elseif (($link["rel"] == "activity-outbox") AND ($link["href"] != "")) {
1198 $data["poll"] = $link["href"];
1199 } elseif (($link["rel"] == "dialback") AND ($link["href"] != "")) {
1200 $data["dialback"] = $link["href"];
1203 if (isset($data["poll"]) AND isset($data["notify"])
1204 AND isset($data["dialback"])
1205 AND isset($data["url"])
1207 // by now we use these fields only for the network type detection
1208 // So we unset all data that isn't used at the moment
1209 unset($data["dialback"]);
1211 $data["network"] = NETWORK_PUMPIO;
1216 $profile_data = self::pumpioProfileData($data["url"]);
1218 if (!$profile_data) {
1222 $data = array_merge($data, $profile_data);
1228 * @brief Check page for feed link
1230 * @param string $url Page link
1232 * @return string feed link
1234 private function getFeedLink($url) {
1235 $doc = new DOMDocument();
1237 if (!@$doc->loadHTMLFile($url)) {
1241 $xpath = new DomXPath($doc);
1243 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1244 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1245 if (!is_object($feeds)) {
1249 if ($feeds->length == 0) {
1255 foreach ($feeds as $feed) {
1257 foreach ($feed->attributes as $attribute) {
1258 $attr[$attribute->name] = trim($attribute->value);
1261 if ($feed_url == "") {
1262 $feed_url = $attr["href"];
1270 * @brief Check for feed contact
1272 * @param string $url Profile link
1273 * @param boolean $probe Do a probe if the page contains a feed link
1275 * @return array feed data
1277 private function feed($url, $probe = true) {
1278 $ret = z_fetch_url($url);
1279 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1282 $feed = $ret['body'];
1283 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1290 $feed_url = self::getFeedLink($url);
1296 return self::feed($feed_url, false);
1299 if ($feed_data["header"]["author-name"] != "") {
1300 $data["name"] = $feed_data["header"]["author-name"];
1303 if ($feed_data["header"]["author-nick"] != "") {
1304 $data["nick"] = $feed_data["header"]["author-nick"];
1307 if ($feed_data["header"]["author-avatar"] != "") {
1308 $data["photo"] = $feed_data["header"]["author-avatar"];
1311 if ($feed_data["header"]["author-id"] != "") {
1312 $data["alias"] = $feed_data["header"]["author-id"];
1315 $data["url"] = $url;
1316 $data["poll"] = $url;
1318 if ($feed_data["header"]["author-link"] != "") {
1319 $data["baseurl"] = $feed_data["header"]["author-link"];
1321 $data["baseurl"] = $data["url"];
1324 $data["network"] = NETWORK_FEED;
1330 * @brief Check for mail contact
1332 * @param string $uri Profile link
1333 * @param integer $uid User ID
1335 * @return array mail data
1337 private function mail($uri, $uid) {
1339 if (!validate_email($uri)) {
1343 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1345 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1347 if (dbm::is_result($x) && dbm::is_result($r)) {
1348 $mailbox = construct_mailbox_name($r[0]);
1350 openssl_private_decrypt(hex2bin($r[0]['pass']), $password, $x[0]['prvkey']);
1351 $mbox = email_connect($mailbox, $r[0]['user'], $password);
1357 $msgs = email_poll($mbox, $uri);
1358 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1360 if (!count($msgs)) {
1364 $phost = substr($uri, strpos($uri, '@') + 1);
1367 $data["addr"] = $uri;
1368 $data["network"] = NETWORK_MAIL;
1369 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1370 $data["nick"] = $data["name"];
1371 $data["photo"] = avatar_img($uri);
1372 $data["url"] = 'http://'.$phost."/".$data["nick"];
1373 $data["notify"] = 'smtp '.random_string();
1374 $data["poll"] = 'email '.random_string();
1376 $x = email_msg_meta($mbox, $msgs[0]);
1377 if (stristr($x[0]->from, $uri)) {
1378 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1379 } elseif (stristr($x[0]->to, $uri)) {
1380 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1383 foreach ($adr as $feadr) {
1384 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1385 &&(strcasecmp($feadr->host, $phost) == 0)
1386 && (strlen($feadr->personal))
1388 $personal = imap_mime_header_decode($feadr->personal);
1390 foreach ($personal as $perspart) {
1391 if ($perspart->charset != "default") {
1392 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1394 $data["name"] .= $perspart->text;
1398 $data["name"] = notags($data["name"]);
1408 * @brief Mix two paths together to possibly fix missing parts
1410 * @param string $avatar Path to the avatar
1411 * @param string $base Another path that is hopefully complete
1413 * @return string fixed avatar path
1415 public static function fixAvatar($avatar, $base) {
1416 $base_parts = parse_url($base);
1418 // Remove all parts that could create a problem
1419 unset($base_parts['path']);
1420 unset($base_parts['query']);
1421 unset($base_parts['fragment']);
1423 $avatar_parts = parse_url($avatar);
1426 $parts = array_merge($base_parts, $avatar_parts);
1428 // And put them together again
1429 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1430 $host = isset($parts['host']) ? $parts['host'] : '';
1431 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1432 $path = isset($parts['path']) ? $parts['path'] : '';
1433 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1434 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1436 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1438 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);