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 $ret = z_fetch_url($ssl_url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
83 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
88 $xrd = parse_xml_string($xml, false);
90 if (!is_object($xrd)) {
91 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
92 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
96 $xrd = parse_xml_string($xml, false);
98 if (!is_object($xrd)) {
102 $links = xml::element_to_array($xrd);
103 if (!isset($links["xrd"]["link"])) {
109 foreach ($links["xrd"]["link"] as $value => $link) {
110 if (isset($link["@attributes"])) {
111 $attributes = $link["@attributes"];
112 } elseif ($value == "@attributes") {
118 if (($attributes["rel"] == "lrdd")
119 AND ($attributes["type"] == "application/xrd+xml")
121 $xrd_data["lrdd-xml"] = $attributes["template"];
122 } elseif (($attributes["rel"] == "lrdd")
123 AND ($attributes["type"] == "application/json")
125 $xrd_data["lrdd-json"] = $attributes["template"];
126 } elseif ($attributes["rel"] == "lrdd") {
127 $xrd_data["lrdd"] = $attributes["template"];
131 self::$baseurl = "http://".$host;
137 * @brief Perform Webfinger lookup and return DFRN data
139 * Given an email style address, perform webfinger lookup and
140 * return the resulting DFRN profile URL, or if no DFRN profile URL
141 * is located, returns an OStatus subscription template (prefixed
142 * with the string 'stat:' to identify it as on OStatus template).
143 * If this isn't an email style address just return $webbie.
144 * Return an empty string if email-style addresses but webfinger fails,
145 * or if the resultant personal XRD doesn't contain a supported
146 * subscription/friend-request attribute.
148 * amended 7/9/2011 to return an hcard which could save potentially loading
149 * a lengthy content page to scrape dfrn attributes
151 * @param string $webbie Address that should be probed
152 * @param string $hcard_url Link to the hcard - is returned by reference
154 * @return string profile link
157 public static function webfingerDfrn($webbie, &$hcard_url) {
161 $links = self::lrdd($webbie);
162 logger('webfingerDfrn: '.$webbie.':'.print_r($links, true), LOGGER_DATA);
164 foreach ($links as $link) {
165 if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
166 $profile_link = $link['@attributes']['href'];
168 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) AND ($profile_link == "")) {
169 $profile_link = 'stat:'.$link['@attributes']['template'];
171 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
172 $hcard_url = $link['@attributes']['href'];
176 return $profile_link;
180 * @brief Check an URI for LRDD data
182 * this is a replacement for the "lrdd" function in include/network.php.
183 * It isn't used in this class and has some redundancies in the code.
184 * When time comes we can check the existing calls for "lrdd" if we can rework them.
186 * @param string $uri Address that should be probed
188 * @return array uri data
190 public static function lrdd($uri) {
192 $lrdd = self::xrd($uri);
196 $parts = @parse_url($uri);
201 $host = $parts["host"];
202 if (isset($parts["port"])) {
203 $host .= ':'.$parts["port"];
206 $path_parts = explode("/", trim($parts["path"], "/"));
208 $nick = array_pop($path_parts);
211 $lrdd = self::xrd($host);
212 $host .= "/".array_shift($path_parts);
213 } while (!$lrdd AND (sizeof($path_parts) > 0));
220 foreach ($lrdd as $key => $link) {
225 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
229 $path = str_replace('{uri}', urlencode($uri), $link);
230 $webfinger = self::webfinger($path);
232 if (!$webfinger AND (strstr($uri, "@"))) {
233 $path = str_replace('{uri}', urlencode("acct:".$uri), $link);
234 $webfinger = self::webfinger($path);
237 // Special treatment for Mastodon
238 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
239 // But the webfinger for this format fails.
240 if (!$webfinger AND isset($nick)) {
241 // Mastodon uses a "@" as prefix for usernames in their url format
242 $nick = ltrim($nick, '@');
244 $addr = $nick."@".$host;
246 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
247 $webfinger = self::webfinger($path);
251 if (!is_array($webfinger["links"])) {
257 foreach ($webfinger["links"] as $link) {
258 $data[] = array("@attributes" => $link);
261 if (is_array($webfinger["aliases"])) {
262 foreach ($webfinger["aliases"] as $alias) {
263 $data[] = array("@attributes" =>
264 array("rel" => "alias",
273 * @brief Fetch information (protocol endpoints and user information) about a given uri
275 * @param string $uri Address that should be probed
276 * @param string $network Test for this specific network
277 * @param integer $uid User ID for the probe (only used for mails)
278 * @param boolean $cache Use cached values?
280 * @return array uri data
282 public static function uri($uri, $network = "", $uid = 0, $cache = true) {
285 $result = Cache::get("probe_url:".$network.":".$uri);
286 if (!is_null($result)) {
295 $data = self::detect($uri, $network, $uid);
297 if (!isset($data["url"])) {
301 if ($data["photo"] != "") {
302 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
304 $data["photo"] = App::get_baseurl().'/images/person-175.jpg';
307 if (!isset($data["name"]) OR ($data["name"] == "")) {
308 if (isset($data["nick"])) {
309 $data["name"] = $data["nick"];
312 if ($data["name"] == "") {
313 $data["name"] = $data["url"];
317 if (!isset($data["nick"]) OR ($data["nick"] == "")) {
318 $data["nick"] = strtolower($data["name"]);
320 if (strpos($data['nick'], ' ')) {
321 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
325 if (self::$baseurl != "") {
326 $data["baseurl"] = self::$baseurl;
329 if (!isset($data["network"])) {
330 $data["network"] = NETWORK_PHANTOM;
333 $data = self::rearrangeData($data);
335 // Only store into the cache if the value seems to be valid
336 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
337 Cache::set("probe_url:".$network.":".$uri, $data, CACHE_DAY);
339 /// @todo temporary fix - we need a real contact update function that updates only changing fields
340 /// The biggest problem is the avatar picture that could have a reduced image size.
341 /// It should only be updated if the existing picture isn't existing anymore.
342 /// We only update the contact when it is no probing for a specific network.
343 if (($data['network'] != NETWORK_FEED)
351 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `url` = '%s', `addr` = '%s',
352 `notify` = '%s', `poll` = '%s', `alias` = '%s', `success_update` = '%s'
353 WHERE `nurl` = '%s' AND NOT `self` AND `uid` = 0",
354 dbesc($data["name"]),
355 dbesc($data["nick"]),
357 dbesc($data["addr"]),
358 dbesc($data["notify"]),
359 dbesc($data["poll"]),
360 dbesc($data["alias"]),
361 dbesc(datetime_convert()),
362 dbesc(normalise_link($data['url']))
371 * @brief Fetch information (protocol endpoints and user information) about a given uri
373 * This function is only called by the "uri" function that adds caching and rearranging of data.
375 * @param string $uri Address that should be probed
376 * @param string $network Test for this specific network
377 * @param integer $uid User ID for the probe (only used for mails)
379 * @return array uri data
381 private function detect($uri, $network, $uid) {
382 $parts = parse_url($uri);
384 if (isset($parts["scheme"]) AND isset($parts["host"]) AND isset($parts["path"])) {
385 $host = $parts["host"];
386 if (isset($parts["port"])) {
387 $host .= ':'.$parts["port"];
390 if ($host == 'twitter.com') {
391 return array("network" => NETWORK_TWITTER);
393 $lrdd = self::xrd($host);
395 $path_parts = explode("/", trim($parts["path"], "/"));
397 while (!$lrdd AND (sizeof($path_parts) > 1)) {
398 $host .= "/".array_shift($path_parts);
399 $lrdd = self::xrd($host);
402 return self::feed($uri);
404 $nick = array_pop($path_parts);
406 // Mastodon uses a "@" as prefix for usernames in their url format
407 $nick = ltrim($nick, '@');
409 $addr = $nick."@".$host;
411 } elseif (strstr($uri, '@')) {
412 // If the URI starts with "mailto:" then jump directly to the mail detection
413 if (strpos($uri, 'mailto:') !== false) {
414 $uri = str_replace('mailto:', '', $uri);
415 return self::mail($uri, $uid);
418 if ($network == NETWORK_MAIL) {
419 return self::mail($uri, $uid);
421 // Remove "acct:" from the URI
422 $uri = str_replace('acct:', '', $uri);
424 $host = substr($uri, strpos($uri, '@') + 1);
425 $nick = substr($uri, 0, strpos($uri, '@'));
427 if (strpos($uri, '@twitter.com')) {
428 return array("network" => NETWORK_TWITTER);
430 $lrdd = self::xrd($host);
433 return self::mail($uri, $uid);
443 /// @todo Do we need the prefix "acct:" or "acct://"?
445 foreach ($lrdd as $key => $link) {
449 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
452 // At first try it with the given uri
453 $path = str_replace('{uri}', urlencode($uri), $link);
454 $webfinger = self::webfinger($path);
456 // We cannot be sure that the detected address was correct, so we don't use the values
457 if ($webfinger AND ($uri != $addr)) {
462 // Try webfinger with the address (user@domain.tld)
464 $path = str_replace('{uri}', urlencode($addr), $link);
465 $webfinger = self::webfinger($path);
468 // Mastodon needs to have it with "acct:"
470 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
471 $webfinger = self::webfinger($path);
475 return self::feed($uri);
480 logger("Probing ".$uri, LOGGER_DEBUG);
482 if (in_array($network, array("", NETWORK_DFRN))) {
483 $result = self::dfrn($webfinger);
485 if ((!$result AND ($network == "")) OR ($network == NETWORK_DIASPORA)) {
486 $result = self::diaspora($webfinger);
488 if ((!$result AND ($network == "")) OR ($network == NETWORK_OSTATUS)) {
489 $result = self::ostatus($webfinger);
491 if ((!$result AND ($network == "")) OR ($network == NETWORK_PUMPIO)) {
492 $result = self::pumpio($webfinger);
494 if ((!$result AND ($network == "")) OR ($network == NETWORK_FEED)) {
495 $result = self::feed($uri);
497 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
498 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
499 if ((!isset($result["nick"]) OR ($result["nick"] == "") OR (strstr($result["nick"], " "))) AND ($nick != "")) {
500 $result["nick"] = $nick;
503 if ((!isset($result["addr"]) OR ($result["addr"] == "")) AND ($addr != "")) {
504 $result["addr"] = $addr;
508 logger($uri." is ".$result["network"], LOGGER_DEBUG);
510 if (!isset($result["baseurl"]) OR ($result["baseurl"] == "")) {
511 $pos = strpos($result["url"], $host);
513 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
521 * @brief Perform a webfinger request.
523 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
525 * @param string $url Address that should be probed
527 * @return array webfinger data
529 private function webfinger($url) {
531 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
534 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
535 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
538 $data = $ret['body'];
540 $xrd = parse_xml_string($data, false);
542 if (!is_object($xrd)) {
543 // If it is not XML, maybe it is JSON
544 $webfinger = json_decode($data, true);
546 if (!isset($webfinger["links"])) {
553 $xrd_arr = xml::element_to_array($xrd);
554 if (!isset($xrd_arr["xrd"]["link"])) {
558 $webfinger = array();
560 if (isset($xrd_arr["xrd"]["subject"])) {
561 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
564 if (isset($xrd_arr["xrd"]["alias"])) {
565 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
568 $webfinger["links"] = array();
570 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
571 if (isset($data["@attributes"])) {
572 $attributes = $data["@attributes"];
573 } elseif ($value == "@attributes") {
579 $webfinger["links"][] = $attributes;
585 * @brief Poll the Friendica specific noscrape page.
587 * "noscrape" is a faster alternative to fetch the data from the hcard.
588 * This functionality was originally created for the directory.
590 * @param string $noscrape_url Link to the noscrape page
591 * @param array $data The already fetched data
593 * @return array noscrape data
595 private function pollNoscrape($noscrape_url, $data) {
596 $ret = z_fetch_url($noscrape_url);
597 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
600 $content = $ret['body'];
605 $json = json_decode($content, true);
606 if (!is_array($json)) {
610 if (isset($json["fn"])) {
611 $data["name"] = $json["fn"];
614 if (isset($json["addr"])) {
615 $data["addr"] = $json["addr"];
618 if (isset($json["nick"])) {
619 $data["nick"] = $json["nick"];
622 if (isset($json["comm"])) {
623 $data["community"] = $json["comm"];
626 if (isset($json["tags"])) {
627 $keywords = implode(" ", $json["tags"]);
628 if ($keywords != "") {
629 $data["keywords"] = $keywords;
633 $location = formatted_location($json);
635 $data["location"] = $location;
638 if (isset($json["about"])) {
639 $data["about"] = $json["about"];
642 if (isset($json["key"])) {
643 $data["pubkey"] = $json["key"];
646 if (isset($json["photo"])) {
647 $data["photo"] = $json["photo"];
650 if (isset($json["dfrn-request"])) {
651 $data["request"] = $json["dfrn-request"];
654 if (isset($json["dfrn-confirm"])) {
655 $data["confirm"] = $json["dfrn-confirm"];
658 if (isset($json["dfrn-notify"])) {
659 $data["notify"] = $json["dfrn-notify"];
662 if (isset($json["dfrn-poll"])) {
663 $data["poll"] = $json["dfrn-poll"];
670 * @brief Check for valid DFRN data
672 * @param array $data DFRN data
674 * @return int Number of errors
676 public static function validDfrn($data) {
678 if (!isset($data['key'])) {
681 if (!isset($data['dfrn-request'])) {
684 if (!isset($data['dfrn-confirm'])) {
687 if (!isset($data['dfrn-notify'])) {
690 if (!isset($data['dfrn-poll'])) {
697 * @brief Fetch data from a DFRN profile page and via "noscrape"
699 * @param string $profile_link Link to the profile page
701 * @return array profile data
703 public static function profile($profile_link) {
707 logger("Check profile ".$profile_link, LOGGER_DEBUG);
709 // Fetch data via noscrape - this is faster
710 $noscrape_url = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile_link);
711 $data = self::pollNoscrape($noscrape_url, $data);
713 if (!isset($data["notify"])
714 OR !isset($data["confirm"])
715 OR !isset($data["request"])
716 OR !isset($data["poll"])
717 OR !isset($data["poco"])
718 OR !isset($data["name"])
719 OR !isset($data["photo"])
721 $data = self::pollHcard($profile_link, $data, true);
724 $prof_data = array();
725 $prof_data["addr"] = $data["addr"];
726 $prof_data["nick"] = $data["nick"];
727 $prof_data["dfrn-request"] = $data["request"];
728 $prof_data["dfrn-confirm"] = $data["confirm"];
729 $prof_data["dfrn-notify"] = $data["notify"];
730 $prof_data["dfrn-poll"] = $data["poll"];
731 $prof_data["dfrn-poco"] = $data["poco"];
732 $prof_data["photo"] = $data["photo"];
733 $prof_data["fn"] = $data["name"];
734 $prof_data["key"] = $data["pubkey"];
736 logger("Result for profile ".$profile_link.": ".print_r($prof_data, true), LOGGER_DEBUG);
742 * @brief Check for DFRN contact
744 * @param array $webfinger Webfinger data
746 * @return array DFRN data
748 private function dfrn($webfinger) {
752 foreach ($webfinger["links"] as $link) {
753 if (($link["rel"] == NAMESPACE_DFRN) AND ($link["href"] != "")) {
754 $data["network"] = NETWORK_DFRN;
755 } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
756 $data["poll"] = $link["href"];
757 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND ($link["type"] == "text/html") AND ($link["href"] != "")) {
758 $data["url"] = $link["href"];
759 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != "")) {
760 $hcard_url = $link["href"];
761 } elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != "")) {
762 $data["poco"] = $link["href"];
763 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") AND ($link["href"] != "")) {
764 $data["photo"] = $link["href"];
765 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != "")) {
766 $data["baseurl"] = trim($link["href"], '/');
767 } elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != "")) {
768 $data["guid"] = $link["href"];
769 } elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
770 $data["pubkey"] = base64_decode($link["href"]);
772 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
773 if (strstr($data["pubkey"], 'RSA ')) {
774 $data["pubkey"] = rsatopem($data["pubkey"]);
779 if (!isset($data["network"]) OR ($hcard_url == "")) {
783 // Fetch data via noscrape - this is faster
784 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
785 $data = self::pollNoscrape($noscrape_url, $data);
787 if (isset($data["notify"])
788 AND isset($data["confirm"])
789 AND isset($data["request"])
790 AND isset($data["poll"])
791 AND isset($data["name"])
792 AND isset($data["photo"])
797 $data = self::pollHcard($hcard_url, $data, true);
803 * @brief Poll the hcard page (Diaspora and Friendica specific)
805 * @param string $hcard_url Link to the hcard page
806 * @param array $data The already fetched data
807 * @param boolean $dfrn Poll DFRN specific data
809 * @return array hcard data
811 private function pollHcard($hcard_url, $data, $dfrn = false) {
812 $ret = z_fetch_url($hcard_url);
813 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
816 $content = $ret['body'];
821 $doc = new DOMDocument();
822 if (!@$doc->loadHTML($content)) {
826 $xpath = new DomXPath($doc);
828 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
829 if (!is_object($vcards)) {
833 if ($vcards->length > 0) {
834 $vcard = $vcards->item(0);
836 // We have to discard the guid from the hcard in favour of the guid from lrdd
837 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
838 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
839 if (($search->length > 0) AND ($data["guid"] == "")) {
840 $data["guid"] = $search->item(0)->nodeValue;
843 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
844 if ($search->length > 0) {
845 $data["nick"] = $search->item(0)->nodeValue;
848 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
849 if ($search->length > 0) {
850 $data["name"] = $search->item(0)->nodeValue;
853 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
854 if ($search->length > 0) {
855 $data["searchable"] = $search->item(0)->nodeValue;
858 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
859 if ($search->length > 0) {
860 $data["pubkey"] = $search->item(0)->nodeValue;
861 if (strstr($data["pubkey"], 'RSA ')) {
862 $data["pubkey"] = rsatopem($data["pubkey"]);
866 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
867 if ($search->length > 0) {
868 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
873 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
874 foreach ($photos as $photo) {
876 foreach ($photo->attributes as $attribute) {
877 $attr[$attribute->name] = trim($attribute->value);
880 if (isset($attr["src"]) AND isset($attr["width"])) {
881 $avatar[$attr["width"]] = $attr["src"];
884 // We don't have a width. So we just take everything that we got.
885 // This is a Hubzilla workaround which doesn't send a width.
886 if ((sizeof($avatar) == 0) AND isset($attr["src"])) {
887 $avatar[] = $attr["src"];
891 if (sizeof($avatar)) {
893 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
897 // Poll DFRN specific data
898 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
899 if ($search->length > 0) {
900 foreach ($search as $link) {
901 //$data["request"] = $search->item(0)->nodeValue;
903 foreach ($link->attributes as $attribute) {
904 $attr[$attribute->name] = trim($attribute->value);
907 $data[substr($attr["rel"], 5)] = $attr["href"];
911 // Older Friendica versions had used the "uid" field differently than newer versions
912 if ($data["nick"] == $data["guid"]) {
913 unset($data["guid"]);
922 * @brief Check for Diaspora contact
924 * @param array $webfinger Webfinger data
926 * @return array Diaspora data
928 private function diaspora($webfinger) {
932 foreach ($webfinger["links"] as $link) {
933 if (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != "")) {
934 $hcard_url = $link["href"];
935 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != "")) {
936 $data["baseurl"] = trim($link["href"], '/');
937 } elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != "")) {
938 $data["guid"] = $link["href"];
939 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND ($link["type"] == "text/html") AND ($link["href"] != "")) {
940 $data["url"] = $link["href"];
941 } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
942 $data["poll"] = $link["href"];
943 } elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != "")) {
944 $data["poco"] = $link["href"];
945 } elseif (($link["rel"] == "salmon") AND ($link["href"] != "")) {
946 $data["notify"] = $link["href"];
947 } elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
948 $data["pubkey"] = base64_decode($link["href"]);
950 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
951 if (strstr($data["pubkey"], 'RSA ')) {
952 $data["pubkey"] = rsatopem($data["pubkey"]);
957 if (!isset($data["url"]) OR ($hcard_url == "")) {
961 if (is_array($webfinger["aliases"])) {
962 foreach ($webfinger["aliases"] as $alias) {
963 if (normalise_link($alias) != normalise_link($data["url"]) AND ! strstr($alias, "@")) {
964 $data["alias"] = $alias;
969 // Fetch further information from the hcard
970 $data = self::pollHcard($hcard_url, $data);
976 if (isset($data["url"])
977 AND isset($data["guid"])
978 AND isset($data["baseurl"])
979 AND isset($data["pubkey"])
980 AND ($hcard_url != "")
982 $data["network"] = NETWORK_DIASPORA;
984 // The Diaspora handle must always be lowercase
985 $data["addr"] = strtolower($data["addr"]);
987 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
988 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
989 $data["batch"] = $data["baseurl"] . "/receive/public";
998 * @brief Check for OStatus contact
1000 * @param array $webfinger Webfinger data
1002 * @return array OStatus data
1004 private function ostatus($webfinger) {
1006 if (is_array($webfinger["aliases"])) {
1007 foreach ($webfinger["aliases"] as $alias) {
1008 if (strstr($alias, "@")) {
1009 $data["addr"] = str_replace('acct:', '', $alias);
1014 if (is_string($webfinger["subject"]) AND strstr($webfinger["subject"], "@")) {
1015 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1018 foreach ($webfinger["links"] as $link) {
1019 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1020 AND ($link["type"] == "text/html")
1021 AND ($link["href"] != "")
1023 $data["url"] = $link["href"];
1024 } elseif (($link["rel"] == "salmon") AND ($link["href"] != "")) {
1025 $data["notify"] = $link["href"];
1026 } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
1027 $data["poll"] = $link["href"];
1028 } elseif (($link["rel"] == "magic-public-key") AND ($link["href"] != "")) {
1029 $pubkey = $link["href"];
1031 if (substr($pubkey, 0, 5) === 'data:') {
1032 if (strstr($pubkey, ',')) {
1033 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1035 $pubkey = substr($pubkey, 5);
1037 } elseif (normalise_link($pubkey) == 'http://') {
1038 $ret = z_fetch_url($pubkey);
1039 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1042 $pubkey = $ret['body'];
1045 $key = explode(".", $pubkey);
1047 if (sizeof($key) >= 3) {
1048 $m = base64url_decode($key[1]);
1049 $e = base64url_decode($key[2]);
1050 $data["pubkey"] = metopem($m, $e);
1055 if (isset($data["notify"]) AND isset($data["pubkey"])
1056 AND isset($data["poll"])
1057 AND isset($data["url"])
1059 $data["network"] = NETWORK_OSTATUS;
1063 // Fetch all additional data from the feed
1064 $ret = z_fetch_url($data["poll"]);
1065 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1068 $feed = $ret['body'];
1069 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1073 if ($feed_data["header"]["author-name"] != "") {
1074 $data["name"] = $feed_data["header"]["author-name"];
1076 if ($feed_data["header"]["author-nick"] != "") {
1077 $data["nick"] = $feed_data["header"]["author-nick"];
1079 if ($feed_data["header"]["author-avatar"] != "") {
1080 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1082 if ($feed_data["header"]["author-id"] != "") {
1083 $data["alias"] = $feed_data["header"]["author-id"];
1085 if ($feed_data["header"]["author-location"] != "") {
1086 $data["location"] = $feed_data["header"]["author-location"];
1088 if ($feed_data["header"]["author-about"] != "") {
1089 $data["about"] = $feed_data["header"]["author-about"];
1091 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1092 // So we take the value that we just fetched, although the other one worked as well
1093 if ($feed_data["header"]["author-link"] != "") {
1094 $data["url"] = $feed_data["header"]["author-link"];
1096 /// @todo Fetch location and "about" from the feed as well
1101 * @brief Fetch data from a pump.io profile page
1103 * @param string $profile_link Link to the profile page
1105 * @return array profile data
1107 private function pumpioProfileData($profile_link) {
1109 $doc = new DOMDocument();
1110 if (!@$doc->loadHTMLFile($profile_link)) {
1114 $xpath = new DomXPath($doc);
1118 // This is ugly - but pump.io doesn't seem to know a better way for it
1119 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1120 $pos = strpos($data["name"], chr(10));
1122 $data["name"] = trim(substr($data["name"], 0, $pos));
1125 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1127 foreach ($avatar->attributes as $attribute) {
1128 if ($attribute->name == "src") {
1129 $data["photo"] = trim($attribute->value);
1134 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
1135 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
1141 * @brief Check for pump.io contact
1143 * @param array $webfinger Webfinger data
1145 * @return array pump.io data
1147 private function pumpio($webfinger) {
1150 foreach ($webfinger["links"] as $link) {
1151 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1152 AND ($link["type"] == "text/html")
1153 AND ($link["href"] != "")
1155 $data["url"] = $link["href"];
1156 } elseif (($link["rel"] == "activity-inbox") AND ($link["href"] != "")) {
1157 $data["notify"] = $link["href"];
1158 } elseif (($link["rel"] == "activity-outbox") AND ($link["href"] != "")) {
1159 $data["poll"] = $link["href"];
1160 } elseif (($link["rel"] == "dialback") AND ($link["href"] != "")) {
1161 $data["dialback"] = $link["href"];
1164 if (isset($data["poll"]) AND isset($data["notify"])
1165 AND isset($data["dialback"])
1166 AND isset($data["url"])
1168 // by now we use these fields only for the network type detection
1169 // So we unset all data that isn't used at the moment
1170 unset($data["dialback"]);
1172 $data["network"] = NETWORK_PUMPIO;
1177 $profile_data = self::pumpioProfileData($data["url"]);
1179 if (!$profile_data) {
1183 $data = array_merge($data, $profile_data);
1189 * @brief Check page for feed link
1191 * @param string $url Page link
1193 * @return string feed link
1195 private function getFeedLink($url) {
1196 $doc = new DOMDocument();
1198 if (!@$doc->loadHTMLFile($url)) {
1202 $xpath = new DomXPath($doc);
1204 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1205 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1206 if (!is_object($feeds)) {
1210 if ($feeds->length == 0) {
1216 foreach ($feeds as $feed) {
1218 foreach ($feed->attributes as $attribute) {
1219 $attr[$attribute->name] = trim($attribute->value);
1222 if ($feed_url == "") {
1223 $feed_url = $attr["href"];
1231 * @brief Check for feed contact
1233 * @param string $url Profile link
1234 * @param boolean $probe Do a probe if the page contains a feed link
1236 * @return array feed data
1238 private function feed($url, $probe = true) {
1239 $ret = z_fetch_url($url);
1240 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1243 $feed = $ret['body'];
1244 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1251 $feed_url = self::getFeedLink($url);
1257 return self::feed($feed_url, false);
1260 if ($feed_data["header"]["author-name"] != "") {
1261 $data["name"] = $feed_data["header"]["author-name"];
1264 if ($feed_data["header"]["author-nick"] != "") {
1265 $data["nick"] = $feed_data["header"]["author-nick"];
1268 if ($feed_data["header"]["author-avatar"] != "") {
1269 $data["photo"] = $feed_data["header"]["author-avatar"];
1272 if ($feed_data["header"]["author-id"] != "") {
1273 $data["alias"] = $feed_data["header"]["author-id"];
1276 $data["url"] = $url;
1277 $data["poll"] = $url;
1279 if ($feed_data["header"]["author-link"] != "") {
1280 $data["baseurl"] = $feed_data["header"]["author-link"];
1282 $data["baseurl"] = $data["url"];
1285 $data["network"] = NETWORK_FEED;
1291 * @brief Check for mail contact
1293 * @param string $uri Profile link
1294 * @param integer $uid User ID
1296 * @return array mail data
1298 private function mail($uri, $uid) {
1300 if (!validate_email($uri)) {
1304 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1306 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1308 if (dbm::is_result($x) && dbm::is_result($r)) {
1309 $mailbox = construct_mailbox_name($r[0]);
1311 openssl_private_decrypt(hex2bin($r[0]['pass']), $password, $x[0]['prvkey']);
1312 $mbox = email_connect($mailbox, $r[0]['user'], $password);
1318 $msgs = email_poll($mbox, $uri);
1319 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1321 if (!count($msgs)) {
1325 $phost = substr($uri, strpos($uri, '@') + 1);
1328 $data["addr"] = $uri;
1329 $data["network"] = NETWORK_MAIL;
1330 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1331 $data["nick"] = $data["name"];
1332 $data["photo"] = avatar_img($uri);
1333 $data["url"] = 'http://'.$phost."/".$data["nick"];
1334 $data["notify"] = 'smtp '.random_string();
1335 $data["poll"] = 'email '.random_string();
1337 $x = email_msg_meta($mbox, $msgs[0]);
1338 if (stristr($x[0]->from, $uri)) {
1339 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1340 } elseif (stristr($x[0]->to, $uri)) {
1341 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1344 foreach ($adr as $feadr) {
1345 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1346 &&(strcasecmp($feadr->host, $phost) == 0)
1347 && (strlen($feadr->personal))
1349 $personal = imap_mime_header_decode($feadr->personal);
1351 foreach ($personal as $perspart) {
1352 if ($perspart->charset != "default") {
1353 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1355 $data["name"] .= $perspart->text;
1359 $data["name"] = notags($data["name"]);
1369 * @brief Mix two paths together to possibly fix missing parts
1371 * @param string $avatar Path to the avatar
1372 * @param string $base Another path that is hopefully complete
1374 * @return string fixed avatar path
1376 public static function fixAvatar($avatar, $base) {
1377 $base_parts = parse_url($base);
1379 // Remove all parts that could create a problem
1380 unset($base_parts['path']);
1381 unset($base_parts['query']);
1382 unset($base_parts['fragment']);
1384 $avatar_parts = parse_url($avatar);
1387 $parts = array_merge($base_parts, $avatar_parts);
1389 // And put them together again
1390 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1391 $host = isset($parts['host']) ? $parts['host'] : '';
1392 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1393 $path = isset($parts['path']) ? $parts['path'] : '';
1394 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1395 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1397 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1399 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);