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 Probes for XRD data
64 * @param string $host The host part of an url
67 * 'lrdd' => Link to LRDD endpoint
68 * 'lrdd-xml' => Link to LRDD endpoint in XML format
69 * 'lrdd-json' => Link to LRDD endpoint in JSON format
71 private function xrd($host) {
73 // Reset the static variable
76 $ssl_url = "https://".$host."/.well-known/host-meta";
77 $url = "http://".$host."/.well-known/host-meta";
79 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
82 logger("Probing for ".$host, LOGGER_DEBUG);
84 $ret = z_fetch_url($ssl_url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
85 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
86 logger("Probing timeout for ".$ssl_url, LOGGER_DEBUG);
91 $xrd = parse_xml_string($xml, false);
93 if (!is_object($xrd)) {
94 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
95 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
96 logger("Probing timeout for ".$url, LOGGER_DEBUG);
100 $xrd = parse_xml_string($xml, false);
102 if (!is_object($xrd)) {
103 logger("No xrd object found for ".$host, LOGGER_DEBUG);
107 $links = xml::element_to_array($xrd);
108 if (!isset($links["xrd"]["link"])) {
109 logger("No xrd data found for ".$host, LOGGER_DEBUG);
115 foreach ($links["xrd"]["link"] as $value => $link) {
116 if (isset($link["@attributes"])) {
117 $attributes = $link["@attributes"];
118 } elseif ($value == "@attributes") {
124 if (($attributes["rel"] == "lrdd")
125 AND ($attributes["type"] == "application/xrd+xml")
127 $xrd_data["lrdd-xml"] = $attributes["template"];
128 } elseif (($attributes["rel"] == "lrdd")
129 AND ($attributes["type"] == "application/json")
131 $xrd_data["lrdd-json"] = $attributes["template"];
132 } elseif ($attributes["rel"] == "lrdd") {
133 $xrd_data["lrdd"] = $attributes["template"];
137 self::$baseurl = "http://".$host;
139 logger("Probing successful for ".$host, LOGGER_DEBUG);
145 * @brief Perform Webfinger lookup and return DFRN data
147 * Given an email style address, perform webfinger lookup and
148 * return the resulting DFRN profile URL, or if no DFRN profile URL
149 * is located, returns an OStatus subscription template (prefixed
150 * with the string 'stat:' to identify it as on OStatus template).
151 * If this isn't an email style address just return $webbie.
152 * Return an empty string if email-style addresses but webfinger fails,
153 * or if the resultant personal XRD doesn't contain a supported
154 * subscription/friend-request attribute.
156 * amended 7/9/2011 to return an hcard which could save potentially loading
157 * a lengthy content page to scrape dfrn attributes
159 * @param string $webbie Address that should be probed
160 * @param string $hcard_url Link to the hcard - is returned by reference
162 * @return string profile link
165 public static function webfingerDfrn($webbie, &$hcard_url) {
169 $links = self::lrdd($webbie);
170 logger('webfingerDfrn: '.$webbie.':'.print_r($links, true), LOGGER_DATA);
172 foreach ($links as $link) {
173 if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
174 $profile_link = $link['@attributes']['href'];
176 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) AND ($profile_link == "")) {
177 $profile_link = 'stat:'.$link['@attributes']['template'];
179 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
180 $hcard_url = $link['@attributes']['href'];
184 return $profile_link;
188 * @brief Check an URI for LRDD data
190 * this is a replacement for the "lrdd" function in include/network.php.
191 * It isn't used in this class and has some redundancies in the code.
192 * When time comes we can check the existing calls for "lrdd" if we can rework them.
194 * @param string $uri Address that should be probed
196 * @return array uri data
198 public static function lrdd($uri) {
200 $lrdd = self::xrd($uri);
204 $parts = @parse_url($uri);
209 $host = $parts["host"];
210 if (isset($parts["port"])) {
211 $host .= ':'.$parts["port"];
214 $path_parts = explode("/", trim($parts["path"], "/"));
216 $nick = array_pop($path_parts);
219 $lrdd = self::xrd($host);
220 $host .= "/".array_shift($path_parts);
221 } while (!$lrdd AND (sizeof($path_parts) > 0));
225 logger("No lrdd data found for ".$uri, LOGGER_DEBUG);
229 foreach ($lrdd as $key => $link) {
234 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
238 $path = str_replace('{uri}', urlencode($uri), $link);
239 $webfinger = self::webfinger($path);
241 if (!$webfinger AND (strstr($uri, "@"))) {
242 $path = str_replace('{uri}', urlencode("acct:".$uri), $link);
243 $webfinger = self::webfinger($path);
246 // Special treatment for Mastodon
247 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
248 // But the webfinger for this format fails.
249 if (!$webfinger AND isset($nick)) {
250 // Mastodon uses a "@" as prefix for usernames in their url format
251 $nick = ltrim($nick, '@');
253 $addr = $nick."@".$host;
255 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
256 $webfinger = self::webfinger($path);
260 if (!is_array($webfinger["links"])) {
261 logger("No webfinger links found for ".$uri, LOGGER_DEBUG);
267 foreach ($webfinger["links"] as $link) {
268 $data[] = array("@attributes" => $link);
271 if (is_array($webfinger["aliases"])) {
272 foreach ($webfinger["aliases"] as $alias) {
273 $data[] = array("@attributes" =>
274 array("rel" => "alias",
283 * @brief Fetch information (protocol endpoints and user information) about a given uri
285 * @param string $uri Address that should be probed
286 * @param string $network Test for this specific network
287 * @param integer $uid User ID for the probe (only used for mails)
288 * @param boolean $cache Use cached values?
290 * @return array uri data
292 public static function uri($uri, $network = "", $uid = 0, $cache = true) {
295 $result = Cache::get("probe_url:".$network.":".$uri);
296 if (!is_null($result)) {
305 $data = self::detect($uri, $network, $uid);
307 if (!isset($data["url"])) {
311 if ($data["photo"] != "") {
312 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
314 $data["photo"] = App::get_baseurl().'/images/person-175.jpg';
317 if (!isset($data["name"]) OR ($data["name"] == "")) {
318 if (isset($data["nick"])) {
319 $data["name"] = $data["nick"];
322 if ($data["name"] == "") {
323 $data["name"] = $data["url"];
327 if (!isset($data["nick"]) OR ($data["nick"] == "")) {
328 $data["nick"] = strtolower($data["name"]);
330 if (strpos($data['nick'], ' ')) {
331 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
335 if (self::$baseurl != "") {
336 $data["baseurl"] = self::$baseurl;
339 if (!isset($data["network"])) {
340 $data["network"] = NETWORK_PHANTOM;
343 $data = self::rearrangeData($data);
345 // Only store into the cache if the value seems to be valid
346 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
347 Cache::set("probe_url:".$network.":".$uri, $data, CACHE_DAY);
349 /// @todo temporary fix - we need a real contact update function that updates only changing fields
350 /// The biggest problem is the avatar picture that could have a reduced image size.
351 /// It should only be updated if the existing picture isn't existing anymore.
352 /// We only update the contact when it is no probing for a specific network.
353 if (($data['network'] != NETWORK_FEED)
361 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `url` = '%s', `addr` = '%s',
362 `notify` = '%s', `poll` = '%s', `alias` = '%s', `success_update` = '%s'
363 WHERE `nurl` = '%s' AND NOT `self` AND `uid` = 0",
364 dbesc($data["name"]),
365 dbesc($data["nick"]),
367 dbesc($data["addr"]),
368 dbesc($data["notify"]),
369 dbesc($data["poll"]),
370 dbesc($data["alias"]),
371 dbesc(datetime_convert()),
372 dbesc(normalise_link($data['url']))
381 * @brief Fetch information (protocol endpoints and user information) about a given uri
383 * This function is only called by the "uri" function that adds caching and rearranging of data.
385 * @param string $uri Address that should be probed
386 * @param string $network Test for this specific network
387 * @param integer $uid User ID for the probe (only used for mails)
389 * @return array uri data
391 private function detect($uri, $network, $uid) {
392 $parts = parse_url($uri);
394 if (isset($parts["scheme"]) AND isset($parts["host"]) AND isset($parts["path"])) {
395 $host = $parts["host"];
396 if (isset($parts["port"])) {
397 $host .= ':'.$parts["port"];
400 if ($host == 'twitter.com') {
401 return array("network" => NETWORK_TWITTER);
403 $lrdd = self::xrd($host);
405 $path_parts = explode("/", trim($parts["path"], "/"));
407 while (!$lrdd AND (sizeof($path_parts) > 1)) {
408 $host .= "/".array_shift($path_parts);
409 $lrdd = self::xrd($host);
412 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
413 return self::feed($uri);
415 $nick = array_pop($path_parts);
417 // Mastodon uses a "@" as prefix for usernames in their url format
418 $nick = ltrim($nick, '@');
420 $addr = $nick."@".$host;
422 } elseif (strstr($uri, '@')) {
423 // If the URI starts with "mailto:" then jump directly to the mail detection
424 if (strpos($uri, 'mailto:') !== false) {
425 $uri = str_replace('mailto:', '', $uri);
426 return self::mail($uri, $uid);
429 if ($network == NETWORK_MAIL) {
430 return self::mail($uri, $uid);
432 // Remove "acct:" from the URI
433 $uri = str_replace('acct:', '', $uri);
435 $host = substr($uri, strpos($uri, '@') + 1);
436 $nick = substr($uri, 0, strpos($uri, '@'));
438 if (strpos($uri, '@twitter.com')) {
439 return array("network" => NETWORK_TWITTER);
441 $lrdd = self::xrd($host);
444 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
445 return self::mail($uri, $uid);
450 logger("Uri ".$uri." was not detectable", LOGGER_DEBUG);
456 /// @todo Do we need the prefix "acct:" or "acct://"?
458 foreach ($lrdd as $key => $link) {
462 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
465 // At first try it with the given uri
466 $path = str_replace('{uri}', urlencode($uri), $link);
467 $webfinger = self::webfinger($path);
469 // We cannot be sure that the detected address was correct, so we don't use the values
470 if ($webfinger AND ($uri != $addr)) {
475 // Try webfinger with the address (user@domain.tld)
477 $path = str_replace('{uri}', urlencode($addr), $link);
478 $webfinger = self::webfinger($path);
481 // Mastodon needs to have it with "acct:"
483 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
484 $webfinger = self::webfinger($path);
488 return self::feed($uri);
493 logger("Probing ".$uri, LOGGER_DEBUG);
495 if (in_array($network, array("", NETWORK_DFRN))) {
496 $result = self::dfrn($webfinger);
498 if ((!$result AND ($network == "")) OR ($network == NETWORK_DIASPORA)) {
499 $result = self::diaspora($webfinger);
501 if ((!$result AND ($network == "")) OR ($network == NETWORK_OSTATUS)) {
502 $result = self::ostatus($webfinger);
504 if ((!$result AND ($network == "")) OR ($network == NETWORK_PUMPIO)) {
505 $result = self::pumpio($webfinger);
507 if ((!$result AND ($network == "")) OR ($network == NETWORK_FEED)) {
508 $result = self::feed($uri);
510 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
511 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
512 if ((!isset($result["nick"]) OR ($result["nick"] == "") OR (strstr($result["nick"], " "))) AND ($nick != "")) {
513 $result["nick"] = $nick;
516 if ((!isset($result["addr"]) OR ($result["addr"] == "")) AND ($addr != "")) {
517 $result["addr"] = $addr;
521 logger($uri." is ".$result["network"], LOGGER_DEBUG);
523 if (!isset($result["baseurl"]) OR ($result["baseurl"] == "")) {
524 $pos = strpos($result["url"], $host);
526 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
534 * @brief Perform a webfinger request.
536 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
538 * @param string $url Address that should be probed
540 * @return array webfinger data
542 private function webfinger($url) {
544 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
547 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
548 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
551 $data = $ret['body'];
553 $xrd = parse_xml_string($data, false);
555 if (!is_object($xrd)) {
556 // If it is not XML, maybe it is JSON
557 $webfinger = json_decode($data, true);
559 if (!isset($webfinger["links"])) {
560 logger("No json webfinger links for ".$url, LOGGER_DEBUG);
567 $xrd_arr = xml::element_to_array($xrd);
568 if (!isset($xrd_arr["xrd"]["link"])) {
569 logger("No XML webfinger links for ".$url, LOGGER_DEBUG);
573 $webfinger = array();
575 if (isset($xrd_arr["xrd"]["subject"])) {
576 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
579 if (isset($xrd_arr["xrd"]["alias"])) {
580 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
583 $webfinger["links"] = array();
585 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
586 if (isset($data["@attributes"])) {
587 $attributes = $data["@attributes"];
588 } elseif ($value == "@attributes") {
594 $webfinger["links"][] = $attributes;
600 * @brief Poll the Friendica specific noscrape page.
602 * "noscrape" is a faster alternative to fetch the data from the hcard.
603 * This functionality was originally created for the directory.
605 * @param string $noscrape_url Link to the noscrape page
606 * @param array $data The already fetched data
608 * @return array noscrape data
610 private function pollNoscrape($noscrape_url, $data) {
611 $ret = z_fetch_url($noscrape_url);
612 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
615 $content = $ret['body'];
617 logger("Empty body for ".$noscrape_url, LOGGER_DEBUG);
621 $json = json_decode($content, true);
622 if (!is_array($json)) {
623 logger("No json data for ".$noscrape_url, LOGGER_DEBUG);
627 if (isset($json["fn"])) {
628 $data["name"] = $json["fn"];
631 if (isset($json["addr"])) {
632 $data["addr"] = $json["addr"];
635 if (isset($json["nick"])) {
636 $data["nick"] = $json["nick"];
639 if (isset($json["comm"])) {
640 $data["community"] = $json["comm"];
643 if (isset($json["tags"])) {
644 $keywords = implode(" ", $json["tags"]);
645 if ($keywords != "") {
646 $data["keywords"] = $keywords;
650 $location = formatted_location($json);
652 $data["location"] = $location;
655 if (isset($json["about"])) {
656 $data["about"] = $json["about"];
659 if (isset($json["key"])) {
660 $data["pubkey"] = $json["key"];
663 if (isset($json["photo"])) {
664 $data["photo"] = $json["photo"];
667 if (isset($json["dfrn-request"])) {
668 $data["request"] = $json["dfrn-request"];
671 if (isset($json["dfrn-confirm"])) {
672 $data["confirm"] = $json["dfrn-confirm"];
675 if (isset($json["dfrn-notify"])) {
676 $data["notify"] = $json["dfrn-notify"];
679 if (isset($json["dfrn-poll"])) {
680 $data["poll"] = $json["dfrn-poll"];
687 * @brief Check for valid DFRN data
689 * @param array $data DFRN data
691 * @return int Number of errors
693 public static function validDfrn($data) {
695 if (!isset($data['key'])) {
698 if (!isset($data['dfrn-request'])) {
701 if (!isset($data['dfrn-confirm'])) {
704 if (!isset($data['dfrn-notify'])) {
707 if (!isset($data['dfrn-poll'])) {
714 * @brief Fetch data from a DFRN profile page and via "noscrape"
716 * @param string $profile_link Link to the profile page
718 * @return array profile data
720 public static function profile($profile_link) {
724 logger("Check profile ".$profile_link, LOGGER_DEBUG);
726 // Fetch data via noscrape - this is faster
727 $noscrape_url = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile_link);
728 $data = self::pollNoscrape($noscrape_url, $data);
730 if (!isset($data["notify"])
731 OR !isset($data["confirm"])
732 OR !isset($data["request"])
733 OR !isset($data["poll"])
734 OR !isset($data["poco"])
735 OR !isset($data["name"])
736 OR !isset($data["photo"])
738 $data = self::pollHcard($profile_link, $data, true);
741 $prof_data = array();
742 $prof_data["addr"] = $data["addr"];
743 $prof_data["nick"] = $data["nick"];
744 $prof_data["dfrn-request"] = $data["request"];
745 $prof_data["dfrn-confirm"] = $data["confirm"];
746 $prof_data["dfrn-notify"] = $data["notify"];
747 $prof_data["dfrn-poll"] = $data["poll"];
748 $prof_data["dfrn-poco"] = $data["poco"];
749 $prof_data["photo"] = $data["photo"];
750 $prof_data["fn"] = $data["name"];
751 $prof_data["key"] = $data["pubkey"];
753 logger("Result for profile ".$profile_link.": ".print_r($prof_data, true), LOGGER_DEBUG);
759 * @brief Check for DFRN contact
761 * @param array $webfinger Webfinger data
763 * @return array DFRN data
765 private function dfrn($webfinger) {
769 foreach ($webfinger["links"] as $link) {
770 if (($link["rel"] == NAMESPACE_DFRN) AND ($link["href"] != "")) {
771 $data["network"] = NETWORK_DFRN;
772 } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
773 $data["poll"] = $link["href"];
774 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND ($link["type"] == "text/html") AND ($link["href"] != "")) {
775 $data["url"] = $link["href"];
776 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != "")) {
777 $hcard_url = $link["href"];
778 } elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != "")) {
779 $data["poco"] = $link["href"];
780 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") AND ($link["href"] != "")) {
781 $data["photo"] = $link["href"];
782 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != "")) {
783 $data["baseurl"] = trim($link["href"], '/');
784 } elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != "")) {
785 $data["guid"] = $link["href"];
786 } elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
787 $data["pubkey"] = base64_decode($link["href"]);
789 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
790 if (strstr($data["pubkey"], 'RSA ')) {
791 $data["pubkey"] = rsatopem($data["pubkey"]);
796 if (!isset($data["network"]) OR ($hcard_url == "")) {
800 // Fetch data via noscrape - this is faster
801 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
802 $data = self::pollNoscrape($noscrape_url, $data);
804 if (isset($data["notify"])
805 AND isset($data["confirm"])
806 AND isset($data["request"])
807 AND isset($data["poll"])
808 AND isset($data["name"])
809 AND isset($data["photo"])
814 $data = self::pollHcard($hcard_url, $data, true);
820 * @brief Poll the hcard page (Diaspora and Friendica specific)
822 * @param string $hcard_url Link to the hcard page
823 * @param array $data The already fetched data
824 * @param boolean $dfrn Poll DFRN specific data
826 * @return array hcard data
828 private function pollHcard($hcard_url, $data, $dfrn = false) {
829 $ret = z_fetch_url($hcard_url);
830 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
833 $content = $ret['body'];
838 $doc = new DOMDocument();
839 if (!@$doc->loadHTML($content)) {
843 $xpath = new DomXPath($doc);
845 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
846 if (!is_object($vcards)) {
850 if ($vcards->length > 0) {
851 $vcard = $vcards->item(0);
853 // We have to discard the guid from the hcard in favour of the guid from lrdd
854 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
855 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
856 if (($search->length > 0) AND ($data["guid"] == "")) {
857 $data["guid"] = $search->item(0)->nodeValue;
860 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
861 if ($search->length > 0) {
862 $data["nick"] = $search->item(0)->nodeValue;
865 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
866 if ($search->length > 0) {
867 $data["name"] = $search->item(0)->nodeValue;
870 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
871 if ($search->length > 0) {
872 $data["searchable"] = $search->item(0)->nodeValue;
875 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
876 if ($search->length > 0) {
877 $data["pubkey"] = $search->item(0)->nodeValue;
878 if (strstr($data["pubkey"], 'RSA ')) {
879 $data["pubkey"] = rsatopem($data["pubkey"]);
883 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
884 if ($search->length > 0) {
885 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
890 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
891 foreach ($photos as $photo) {
893 foreach ($photo->attributes as $attribute) {
894 $attr[$attribute->name] = trim($attribute->value);
897 if (isset($attr["src"]) AND isset($attr["width"])) {
898 $avatar[$attr["width"]] = $attr["src"];
901 // We don't have a width. So we just take everything that we got.
902 // This is a Hubzilla workaround which doesn't send a width.
903 if ((sizeof($avatar) == 0) AND isset($attr["src"])) {
904 $avatar[] = $attr["src"];
908 if (sizeof($avatar)) {
910 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
914 // Poll DFRN specific data
915 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
916 if ($search->length > 0) {
917 foreach ($search as $link) {
918 //$data["request"] = $search->item(0)->nodeValue;
920 foreach ($link->attributes as $attribute) {
921 $attr[$attribute->name] = trim($attribute->value);
924 $data[substr($attr["rel"], 5)] = $attr["href"];
928 // Older Friendica versions had used the "uid" field differently than newer versions
929 if ($data["nick"] == $data["guid"]) {
930 unset($data["guid"]);
939 * @brief Check for Diaspora contact
941 * @param array $webfinger Webfinger data
943 * @return array Diaspora data
945 private function diaspora($webfinger) {
949 foreach ($webfinger["links"] as $link) {
950 if (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != "")) {
951 $hcard_url = $link["href"];
952 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != "")) {
953 $data["baseurl"] = trim($link["href"], '/');
954 } elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != "")) {
955 $data["guid"] = $link["href"];
956 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND ($link["type"] == "text/html") AND ($link["href"] != "")) {
957 $data["url"] = $link["href"];
958 } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
959 $data["poll"] = $link["href"];
960 } elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != "")) {
961 $data["poco"] = $link["href"];
962 } elseif (($link["rel"] == "salmon") AND ($link["href"] != "")) {
963 $data["notify"] = $link["href"];
964 } elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
965 $data["pubkey"] = base64_decode($link["href"]);
967 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
968 if (strstr($data["pubkey"], 'RSA ')) {
969 $data["pubkey"] = rsatopem($data["pubkey"]);
974 if (!isset($data["url"]) OR ($hcard_url == "")) {
978 if (is_array($webfinger["aliases"])) {
979 foreach ($webfinger["aliases"] as $alias) {
980 if (normalise_link($alias) != normalise_link($data["url"]) AND ! strstr($alias, "@")) {
981 $data["alias"] = $alias;
986 // Fetch further information from the hcard
987 $data = self::pollHcard($hcard_url, $data);
993 if (isset($data["url"])
994 AND isset($data["guid"])
995 AND isset($data["baseurl"])
996 AND isset($data["pubkey"])
997 AND ($hcard_url != "")
999 $data["network"] = NETWORK_DIASPORA;
1001 // The Diaspora handle must always be lowercase
1002 $data["addr"] = strtolower($data["addr"]);
1004 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1005 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1006 $data["batch"] = $data["baseurl"] . "/receive/public";
1015 * @brief Check for OStatus contact
1017 * @param array $webfinger Webfinger data
1019 * @return array OStatus data
1021 private function ostatus($webfinger) {
1023 if (is_array($webfinger["aliases"])) {
1024 foreach ($webfinger["aliases"] as $alias) {
1025 if (strstr($alias, "@")) {
1026 $data["addr"] = str_replace('acct:', '', $alias);
1031 if (is_string($webfinger["subject"]) AND strstr($webfinger["subject"], "@")) {
1032 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1035 foreach ($webfinger["links"] as $link) {
1036 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1037 AND ($link["type"] == "text/html")
1038 AND ($link["href"] != "")
1040 $data["url"] = $link["href"];
1041 } elseif (($link["rel"] == "salmon") AND ($link["href"] != "")) {
1042 $data["notify"] = $link["href"];
1043 } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
1044 $data["poll"] = $link["href"];
1045 } elseif (($link["rel"] == "magic-public-key") AND ($link["href"] != "")) {
1046 $pubkey = $link["href"];
1048 if (substr($pubkey, 0, 5) === 'data:') {
1049 if (strstr($pubkey, ',')) {
1050 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1052 $pubkey = substr($pubkey, 5);
1054 } elseif (normalise_link($pubkey) == 'http://') {
1055 $ret = z_fetch_url($pubkey);
1056 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1059 $pubkey = $ret['body'];
1062 $key = explode(".", $pubkey);
1064 if (sizeof($key) >= 3) {
1065 $m = base64url_decode($key[1]);
1066 $e = base64url_decode($key[2]);
1067 $data["pubkey"] = metopem($m, $e);
1072 if (isset($data["notify"]) AND isset($data["pubkey"])
1073 AND isset($data["poll"])
1074 AND isset($data["url"])
1076 $data["network"] = NETWORK_OSTATUS;
1080 // Fetch all additional data from the feed
1081 $ret = z_fetch_url($data["poll"]);
1082 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1085 $feed = $ret['body'];
1086 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1090 if ($feed_data["header"]["author-name"] != "") {
1091 $data["name"] = $feed_data["header"]["author-name"];
1093 if ($feed_data["header"]["author-nick"] != "") {
1094 $data["nick"] = $feed_data["header"]["author-nick"];
1096 if ($feed_data["header"]["author-avatar"] != "") {
1097 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1099 if ($feed_data["header"]["author-id"] != "") {
1100 $data["alias"] = $feed_data["header"]["author-id"];
1102 if ($feed_data["header"]["author-location"] != "") {
1103 $data["location"] = $feed_data["header"]["author-location"];
1105 if ($feed_data["header"]["author-about"] != "") {
1106 $data["about"] = $feed_data["header"]["author-about"];
1108 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1109 // So we take the value that we just fetched, although the other one worked as well
1110 if ($feed_data["header"]["author-link"] != "") {
1111 $data["url"] = $feed_data["header"]["author-link"];
1113 /// @todo Fetch location and "about" from the feed as well
1118 * @brief Fetch data from a pump.io profile page
1120 * @param string $profile_link Link to the profile page
1122 * @return array profile data
1124 private function pumpioProfileData($profile_link) {
1126 $doc = new DOMDocument();
1127 if (!@$doc->loadHTMLFile($profile_link)) {
1131 $xpath = new DomXPath($doc);
1135 // This is ugly - but pump.io doesn't seem to know a better way for it
1136 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1137 $pos = strpos($data["name"], chr(10));
1139 $data["name"] = trim(substr($data["name"], 0, $pos));
1142 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1144 foreach ($avatar->attributes as $attribute) {
1145 if ($attribute->name == "src") {
1146 $data["photo"] = trim($attribute->value);
1151 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
1152 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
1158 * @brief Check for pump.io contact
1160 * @param array $webfinger Webfinger data
1162 * @return array pump.io data
1164 private function pumpio($webfinger) {
1167 foreach ($webfinger["links"] as $link) {
1168 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1169 AND ($link["type"] == "text/html")
1170 AND ($link["href"] != "")
1172 $data["url"] = $link["href"];
1173 } elseif (($link["rel"] == "activity-inbox") AND ($link["href"] != "")) {
1174 $data["notify"] = $link["href"];
1175 } elseif (($link["rel"] == "activity-outbox") AND ($link["href"] != "")) {
1176 $data["poll"] = $link["href"];
1177 } elseif (($link["rel"] == "dialback") AND ($link["href"] != "")) {
1178 $data["dialback"] = $link["href"];
1181 if (isset($data["poll"]) AND isset($data["notify"])
1182 AND isset($data["dialback"])
1183 AND isset($data["url"])
1185 // by now we use these fields only for the network type detection
1186 // So we unset all data that isn't used at the moment
1187 unset($data["dialback"]);
1189 $data["network"] = NETWORK_PUMPIO;
1194 $profile_data = self::pumpioProfileData($data["url"]);
1196 if (!$profile_data) {
1200 $data = array_merge($data, $profile_data);
1206 * @brief Check page for feed link
1208 * @param string $url Page link
1210 * @return string feed link
1212 private function getFeedLink($url) {
1213 $doc = new DOMDocument();
1215 if (!@$doc->loadHTMLFile($url)) {
1219 $xpath = new DomXPath($doc);
1221 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1222 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1223 if (!is_object($feeds)) {
1227 if ($feeds->length == 0) {
1233 foreach ($feeds as $feed) {
1235 foreach ($feed->attributes as $attribute) {
1236 $attr[$attribute->name] = trim($attribute->value);
1239 if ($feed_url == "") {
1240 $feed_url = $attr["href"];
1248 * @brief Check for feed contact
1250 * @param string $url Profile link
1251 * @param boolean $probe Do a probe if the page contains a feed link
1253 * @return array feed data
1255 private function feed($url, $probe = true) {
1256 $ret = z_fetch_url($url);
1257 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1260 $feed = $ret['body'];
1261 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1268 $feed_url = self::getFeedLink($url);
1274 return self::feed($feed_url, false);
1277 if ($feed_data["header"]["author-name"] != "") {
1278 $data["name"] = $feed_data["header"]["author-name"];
1281 if ($feed_data["header"]["author-nick"] != "") {
1282 $data["nick"] = $feed_data["header"]["author-nick"];
1285 if ($feed_data["header"]["author-avatar"] != "") {
1286 $data["photo"] = $feed_data["header"]["author-avatar"];
1289 if ($feed_data["header"]["author-id"] != "") {
1290 $data["alias"] = $feed_data["header"]["author-id"];
1293 $data["url"] = $url;
1294 $data["poll"] = $url;
1296 if ($feed_data["header"]["author-link"] != "") {
1297 $data["baseurl"] = $feed_data["header"]["author-link"];
1299 $data["baseurl"] = $data["url"];
1302 $data["network"] = NETWORK_FEED;
1308 * @brief Check for mail contact
1310 * @param string $uri Profile link
1311 * @param integer $uid User ID
1313 * @return array mail data
1315 private function mail($uri, $uid) {
1317 if (!validate_email($uri)) {
1321 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1323 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1325 if (dbm::is_result($x) && dbm::is_result($r)) {
1326 $mailbox = construct_mailbox_name($r[0]);
1328 openssl_private_decrypt(hex2bin($r[0]['pass']), $password, $x[0]['prvkey']);
1329 $mbox = email_connect($mailbox, $r[0]['user'], $password);
1335 $msgs = email_poll($mbox, $uri);
1336 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1338 if (!count($msgs)) {
1342 $phost = substr($uri, strpos($uri, '@') + 1);
1345 $data["addr"] = $uri;
1346 $data["network"] = NETWORK_MAIL;
1347 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1348 $data["nick"] = $data["name"];
1349 $data["photo"] = avatar_img($uri);
1350 $data["url"] = 'http://'.$phost."/".$data["nick"];
1351 $data["notify"] = 'smtp '.random_string();
1352 $data["poll"] = 'email '.random_string();
1354 $x = email_msg_meta($mbox, $msgs[0]);
1355 if (stristr($x[0]->from, $uri)) {
1356 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1357 } elseif (stristr($x[0]->to, $uri)) {
1358 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1361 foreach ($adr as $feadr) {
1362 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1363 &&(strcasecmp($feadr->host, $phost) == 0)
1364 && (strlen($feadr->personal))
1366 $personal = imap_mime_header_decode($feadr->personal);
1368 foreach ($personal as $perspart) {
1369 if ($perspart->charset != "default") {
1370 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1372 $data["name"] .= $perspart->text;
1376 $data["name"] = notags($data["name"]);
1386 * @brief Mix two paths together to possibly fix missing parts
1388 * @param string $avatar Path to the avatar
1389 * @param string $base Another path that is hopefully complete
1391 * @return string fixed avatar path
1393 public static function fixAvatar($avatar, $base) {
1394 $base_parts = parse_url($base);
1396 // Remove all parts that could create a problem
1397 unset($base_parts['path']);
1398 unset($base_parts['query']);
1399 unset($base_parts['fragment']);
1401 $avatar_parts = parse_url($avatar);
1404 $parts = array_merge($base_parts, $avatar_parts);
1406 // And put them together again
1407 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1408 $host = isset($parts['host']) ? $parts['host'] : '';
1409 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1410 $path = isset($parts['path']) ? $parts['path'] : '';
1411 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1412 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1414 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1416 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);