3 namespace Friendica\Network;
6 * @file src/Network/Probe.php
7 * @brief Functions for probing URL
12 use Friendica\Core\Config;
14 require_once 'include/feed.php';
15 require_once 'include/email.php';
16 require_once 'include/network.php';
19 * @brief This class contain functions for probing URL
24 private static $baseurl;
27 * @brief Rearrange the array so that it always has the same order
29 * @param array $data Unordered data
31 * @return array Ordered data
33 private function rearrangeData($data) {
34 $fields = array("name", "nick", "guid", "url", "addr", "alias",
35 "photo", "community", "keywords", "location", "about",
36 "batch", "notify", "poll", "request", "confirm", "poco",
37 "priority", "network", "pubkey", "baseurl");
40 foreach ($fields as $field) {
41 if (isset($data[$field])) {
42 $newdata[$field] = $data[$field];
44 $newdata[$field] = "";
48 // We don't use the "priority" field anymore and replace it with a dummy.
49 $newdata["priority"] = 0;
55 * @brief Probes for XRD data
57 * @param string $host The host part of an url
60 * 'lrdd' => Link to LRDD endpoint
61 * 'lrdd-xml' => Link to LRDD endpoint in XML format
62 * 'lrdd-json' => Link to LRDD endpoint in JSON format
64 private function xrd($host) {
66 // Reset the static variable
69 $ssl_url = "https://".$host."/.well-known/host-meta";
70 $url = "http://".$host."/.well-known/host-meta";
72 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
75 $ret = z_fetch_url($ssl_url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
76 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
81 $xrd = parse_xml_string($xml, false);
83 if (!is_object($xrd)) {
84 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
85 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
89 $xrd = parse_xml_string($xml, false);
91 if (!is_object($xrd)) {
95 $links = \xml::element_to_array($xrd);
96 if (!isset($links["xrd"]["link"])) {
102 foreach ($links["xrd"]["link"] as $value => $link) {
103 if (isset($link["@attributes"])) {
104 $attributes = $link["@attributes"];
105 } elseif ($value == "@attributes") {
111 if (($attributes["rel"] == "lrdd")
112 AND ($attributes["type"] == "application/xrd+xml")
114 $xrd_data["lrdd-xml"] = $attributes["template"];
115 } elseif (($attributes["rel"] == "lrdd")
116 AND ($attributes["type"] == "application/json")
118 $xrd_data["lrdd-json"] = $attributes["template"];
119 } elseif ($attributes["rel"] == "lrdd") {
120 $xrd_data["lrdd"] = $attributes["template"];
124 self::$baseurl = "http://".$host;
130 * @brief Perform Webfinger lookup and return DFRN data
132 * Given an email style address, perform webfinger lookup and
133 * return the resulting DFRN profile URL, or if no DFRN profile URL
134 * is located, returns an OStatus subscription template (prefixed
135 * with the string 'stat:' to identify it as on OStatus template).
136 * If this isn't an email style address just return $webbie.
137 * Return an empty string if email-style addresses but webfinger fails,
138 * or if the resultant personal XRD doesn't contain a supported
139 * subscription/friend-request attribute.
141 * amended 7/9/2011 to return an hcard which could save potentially loading
142 * a lengthy content page to scrape dfrn attributes
144 * @param string $webbie Address that should be probed
145 * @param string $hcard_url Link to the hcard - is returned by reference
147 * @return string profile link
150 public static function webfingerDfrn($webbie, &$hcard_url) {
154 $links = self::lrdd($webbie);
155 logger('webfingerDfrn: '.$webbie.':'.print_r($links, true), LOGGER_DATA);
157 foreach ($links as $link) {
158 if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
159 $profile_link = $link['@attributes']['href'];
161 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) AND ($profile_link == "")) {
162 $profile_link = 'stat:'.$link['@attributes']['template'];
164 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
165 $hcard_url = $link['@attributes']['href'];
169 return $profile_link;
173 * @brief Check an URI for LRDD data
175 * this is a replacement for the "lrdd" function in include/network.php.
176 * It isn't used in this class and has some redundancies in the code.
177 * When time comes we can check the existing calls for "lrdd" if we can rework them.
179 * @param string $uri Address that should be probed
181 * @return array uri data
183 public static function lrdd($uri) {
185 $lrdd = self::xrd($uri);
189 $parts = @parse_url($uri);
194 $host = $parts["host"];
195 if (isset($parts["port"])) {
196 $host .= ':'.$parts["port"];
199 $path_parts = explode("/", trim($parts["path"], "/"));
201 $nick = array_pop($path_parts);
204 $lrdd = self::xrd($host);
205 $host .= "/".array_shift($path_parts);
206 } while (!$lrdd AND (sizeof($path_parts) > 0));
213 foreach ($lrdd as $key => $link) {
218 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
222 $path = str_replace('{uri}', urlencode($uri), $link);
223 $webfinger = self::webfinger($path);
225 if (!$webfinger AND (strstr($uri, "@"))) {
226 $path = str_replace('{uri}', urlencode("acct:".$uri), $link);
227 $webfinger = self::webfinger($path);
230 // Special treatment for Mastodon
231 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
232 // But the webfinger for this format fails.
233 if (!$webfinger AND isset($nick)) {
234 // Mastodon uses a "@" as prefix for usernames in their url format
235 $nick = ltrim($nick, '@');
237 $addr = $nick."@".$host;
239 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
240 $webfinger = self::webfinger($path);
244 if (!is_array($webfinger["links"])) {
250 foreach ($webfinger["links"] as $link) {
251 $data[] = array("@attributes" => $link);
254 if (is_array($webfinger["aliases"])) {
255 foreach ($webfinger["aliases"] as $alias) {
256 $data[] = array("@attributes" =>
257 array("rel" => "alias",
266 * @brief Fetch information (protocol endpoints and user information) about a given uri
268 * @param string $uri Address that should be probed
269 * @param string $network Test for this specific network
270 * @param integer $uid User ID for the probe (only used for mails)
271 * @param boolean $cache Use cached values?
273 * @return array uri data
275 public static function uri($uri, $network = "", $uid = 0, $cache = true) {
278 $result = \Cache::get("probe_url:".$network.":".$uri);
279 if (!is_null($result)) {
288 $data = self::detect($uri, $network, $uid);
290 if (!isset($data["url"])) {
294 if ($data["photo"] != "") {
295 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
297 $data["photo"] = App::get_baseurl().'/images/person-175.jpg';
300 if (!isset($data["name"]) OR ($data["name"] == "")) {
301 if (isset($data["nick"])) {
302 $data["name"] = $data["nick"];
305 if ($data["name"] == "") {
306 $data["name"] = $data["url"];
310 if (!isset($data["nick"]) OR ($data["nick"] == "")) {
311 $data["nick"] = strtolower($data["name"]);
313 if (strpos($data['nick'], ' ')) {
314 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
318 if (self::$baseurl != "") {
319 $data["baseurl"] = self::$baseurl;
322 if (!isset($data["network"])) {
323 $data["network"] = NETWORK_PHANTOM;
326 $data = self::rearrangeData($data);
328 // Only store into the cache if the value seems to be valid
329 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
330 \Cache::set("probe_url:".$network.":".$uri, $data, CACHE_DAY);
332 /// @todo temporary fix - we need a real contact update function that updates only changing fields
333 /// The biggest problem is the avatar picture that could have a reduced image size.
334 /// It should only be updated if the existing picture isn't existing anymore.
335 /// We only update the contact when it is no probing for a specific network.
336 if (($data['network'] != NETWORK_FEED)
344 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `url` = '%s', `addr` = '%s',
345 `notify` = '%s', `poll` = '%s', `alias` = '%s', `success_update` = '%s'
346 WHERE `nurl` = '%s' AND NOT `self` AND `uid` = 0",
347 dbesc($data["name"]),
348 dbesc($data["nick"]),
350 dbesc($data["addr"]),
351 dbesc($data["notify"]),
352 dbesc($data["poll"]),
353 dbesc($data["alias"]),
354 dbesc(datetime_convert()),
355 dbesc(normalise_link($data['url']))
364 * @brief Fetch information (protocol endpoints and user information) about a given uri
366 * This function is only called by the "uri" function that adds caching and rearranging of data.
368 * @param string $uri Address that should be probed
369 * @param string $network Test for this specific network
370 * @param integer $uid User ID for the probe (only used for mails)
372 * @return array uri data
374 private function detect($uri, $network, $uid) {
375 $parts = parse_url($uri);
377 if (isset($parts["scheme"]) AND isset($parts["host"]) AND isset($parts["path"])) {
378 $host = $parts["host"];
379 if (isset($parts["port"])) {
380 $host .= ':'.$parts["port"];
383 if ($host == 'twitter.com') {
384 return array("network" => NETWORK_TWITTER);
386 $lrdd = self::xrd($host);
388 $path_parts = explode("/", trim($parts["path"], "/"));
390 while (!$lrdd AND (sizeof($path_parts) > 1)) {
391 $host .= "/".array_shift($path_parts);
392 $lrdd = self::xrd($host);
395 return self::feed($uri);
397 $nick = array_pop($path_parts);
399 // Mastodon uses a "@" as prefix for usernames in their url format
400 $nick = ltrim($nick, '@');
402 $addr = $nick."@".$host;
404 } elseif (strstr($uri, '@')) {
405 // If the URI starts with "mailto:" then jump directly to the mail detection
406 if (strpos($uri, 'mailto:') !== false) {
407 $uri = str_replace('mailto:', '', $uri);
408 return self::mail($uri, $uid);
411 if ($network == NETWORK_MAIL) {
412 return self::mail($uri, $uid);
414 // Remove "acct:" from the URI
415 $uri = str_replace('acct:', '', $uri);
417 $host = substr($uri, strpos($uri, '@') + 1);
418 $nick = substr($uri, 0, strpos($uri, '@'));
420 if (strpos($uri, '@twitter.com')) {
421 return array("network" => NETWORK_TWITTER);
423 $lrdd = self::xrd($host);
426 return self::mail($uri, $uid);
436 /// @todo Do we need the prefix "acct:" or "acct://"?
438 foreach ($lrdd as $key => $link) {
442 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
445 // At first try it with the given uri
446 $path = str_replace('{uri}', urlencode($uri), $link);
447 $webfinger = self::webfinger($path);
449 // We cannot be sure that the detected address was correct, so we don't use the values
450 if ($webfinger AND ($uri != $addr)) {
455 // Try webfinger with the address (user@domain.tld)
457 $path = str_replace('{uri}', urlencode($addr), $link);
458 $webfinger = self::webfinger($path);
461 // Mastodon needs to have it with "acct:"
463 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
464 $webfinger = self::webfinger($path);
468 return self::feed($uri);
473 logger("Probing ".$uri, LOGGER_DEBUG);
475 if (in_array($network, array("", NETWORK_DFRN))) {
476 $result = self::dfrn($webfinger);
478 if ((!$result AND ($network == "")) OR ($network == NETWORK_DIASPORA)) {
479 $result = self::diaspora($webfinger);
481 if ((!$result AND ($network == "")) OR ($network == NETWORK_OSTATUS)) {
482 $result = self::ostatus($webfinger);
484 if ((!$result AND ($network == "")) OR ($network == NETWORK_PUMPIO)) {
485 $result = self::pumpio($webfinger);
487 if ((!$result AND ($network == "")) OR ($network == NETWORK_FEED)) {
488 $result = self::feed($uri);
490 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
491 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
492 if ((!isset($result["nick"]) OR ($result["nick"] == "") OR (strstr($result["nick"], " "))) AND ($nick != "")) {
493 $result["nick"] = $nick;
496 if ((!isset($result["addr"]) OR ($result["addr"] == "")) AND ($addr != "")) {
497 $result["addr"] = $addr;
501 logger($uri." is ".$result["network"], LOGGER_DEBUG);
503 if (!isset($result["baseurl"]) OR ($result["baseurl"] == "")) {
504 $pos = strpos($result["url"], $host);
506 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
514 * @brief Perform a webfinger request.
516 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
518 * @param string $url Address that should be probed
520 * @return array webfinger data
522 private function webfinger($url) {
524 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
527 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
528 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
531 $data = $ret['body'];
533 $xrd = parse_xml_string($data, false);
535 if (!is_object($xrd)) {
536 // If it is not XML, maybe it is JSON
537 $webfinger = json_decode($data, true);
539 if (!isset($webfinger["links"])) {
546 $xrd_arr = \xml::element_to_array($xrd);
547 if (!isset($xrd_arr["xrd"]["link"])) {
551 $webfinger = array();
553 if (isset($xrd_arr["xrd"]["subject"])) {
554 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
557 if (isset($xrd_arr["xrd"]["alias"])) {
558 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
561 $webfinger["links"] = array();
563 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
564 if (isset($data["@attributes"])) {
565 $attributes = $data["@attributes"];
566 } elseif ($value == "@attributes") {
572 $webfinger["links"][] = $attributes;
578 * @brief Poll the Friendica specific noscrape page.
580 * "noscrape" is a faster alternative to fetch the data from the hcard.
581 * This functionality was originally created for the directory.
583 * @param string $noscrape_url Link to the noscrape page
584 * @param array $data The already fetched data
586 * @return array noscrape data
588 private function pollNoscrape($noscrape_url, $data) {
589 $ret = z_fetch_url($noscrape_url);
590 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
593 $content = $ret['body'];
598 $json = json_decode($content, true);
599 if (!is_array($json)) {
603 if (isset($json["fn"])) {
604 $data["name"] = $json["fn"];
607 if (isset($json["addr"])) {
608 $data["addr"] = $json["addr"];
611 if (isset($json["nick"])) {
612 $data["nick"] = $json["nick"];
615 if (isset($json["comm"])) {
616 $data["community"] = $json["comm"];
619 if (isset($json["tags"])) {
620 $keywords = implode(" ", $json["tags"]);
621 if ($keywords != "") {
622 $data["keywords"] = $keywords;
626 $location = formatted_location($json);
628 $data["location"] = $location;
631 if (isset($json["about"])) {
632 $data["about"] = $json["about"];
635 if (isset($json["key"])) {
636 $data["pubkey"] = $json["key"];
639 if (isset($json["photo"])) {
640 $data["photo"] = $json["photo"];
643 if (isset($json["dfrn-request"])) {
644 $data["request"] = $json["dfrn-request"];
647 if (isset($json["dfrn-confirm"])) {
648 $data["confirm"] = $json["dfrn-confirm"];
651 if (isset($json["dfrn-notify"])) {
652 $data["notify"] = $json["dfrn-notify"];
655 if (isset($json["dfrn-poll"])) {
656 $data["poll"] = $json["dfrn-poll"];
663 * @brief Check for valid DFRN data
665 * @param array $data DFRN data
667 * @return int Number of errors
669 public static function validDfrn($data) {
671 if (!isset($data['key'])) {
674 if (!isset($data['dfrn-request'])) {
677 if (!isset($data['dfrn-confirm'])) {
680 if (!isset($data['dfrn-notify'])) {
683 if (!isset($data['dfrn-poll'])) {
690 * @brief Fetch data from a DFRN profile page and via "noscrape"
692 * @param string $profile_link Link to the profile page
694 * @return array profile data
696 public static function profile($profile_link) {
700 logger("Check profile ".$profile_link, LOGGER_DEBUG);
702 // Fetch data via noscrape - this is faster
703 $noscrape_url = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile_link);
704 $data = self::pollNoscrape($noscrape_url, $data);
706 if (!isset($data["notify"])
707 OR !isset($data["confirm"])
708 OR !isset($data["request"])
709 OR !isset($data["poll"])
710 OR !isset($data["poco"])
711 OR !isset($data["name"])
712 OR !isset($data["photo"])
714 $data = self::pollHcard($profile_link, $data, true);
717 $prof_data = array();
718 $prof_data["addr"] = $data["addr"];
719 $prof_data["nick"] = $data["nick"];
720 $prof_data["dfrn-request"] = $data["request"];
721 $prof_data["dfrn-confirm"] = $data["confirm"];
722 $prof_data["dfrn-notify"] = $data["notify"];
723 $prof_data["dfrn-poll"] = $data["poll"];
724 $prof_data["dfrn-poco"] = $data["poco"];
725 $prof_data["photo"] = $data["photo"];
726 $prof_data["fn"] = $data["name"];
727 $prof_data["key"] = $data["pubkey"];
729 logger("Result for profile ".$profile_link.": ".print_r($prof_data, true), LOGGER_DEBUG);
735 * @brief Check for DFRN contact
737 * @param array $webfinger Webfinger data
739 * @return array DFRN data
741 private function dfrn($webfinger) {
745 foreach ($webfinger["links"] as $link) {
746 if (($link["rel"] == NAMESPACE_DFRN) AND ($link["href"] != "")) {
747 $data["network"] = NETWORK_DFRN;
748 } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
749 $data["poll"] = $link["href"];
750 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND ($link["type"] == "text/html") AND ($link["href"] != "")) {
751 $data["url"] = $link["href"];
752 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != "")) {
753 $hcard_url = $link["href"];
754 } elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != "")) {
755 $data["poco"] = $link["href"];
756 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") AND ($link["href"] != "")) {
757 $data["photo"] = $link["href"];
758 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != "")) {
759 $data["baseurl"] = trim($link["href"], '/');
760 } elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != "")) {
761 $data["guid"] = $link["href"];
762 } elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
763 $data["pubkey"] = base64_decode($link["href"]);
765 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
766 if (strstr($data["pubkey"], 'RSA ')) {
767 $data["pubkey"] = rsatopem($data["pubkey"]);
772 if (!isset($data["network"]) OR ($hcard_url == "")) {
776 // Fetch data via noscrape - this is faster
777 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
778 $data = self::pollNoscrape($noscrape_url, $data);
780 if (isset($data["notify"])
781 AND isset($data["confirm"])
782 AND isset($data["request"])
783 AND isset($data["poll"])
784 AND isset($data["name"])
785 AND isset($data["photo"])
790 $data = self::pollHcard($hcard_url, $data, true);
796 * @brief Poll the hcard page (Diaspora and Friendica specific)
798 * @param string $hcard_url Link to the hcard page
799 * @param array $data The already fetched data
800 * @param boolean $dfrn Poll DFRN specific data
802 * @return array hcard data
804 private function pollHcard($hcard_url, $data, $dfrn = false) {
805 $ret = z_fetch_url($hcard_url);
806 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
809 $content = $ret['body'];
814 $doc = new \DOMDocument();
815 if (!@$doc->loadHTML($content)) {
819 $xpath = new \DomXPath($doc);
821 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
822 if (!is_object($vcards)) {
826 if ($vcards->length > 0) {
827 $vcard = $vcards->item(0);
829 // We have to discard the guid from the hcard in favour of the guid from lrdd
830 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
831 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
832 if (($search->length > 0) AND ($data["guid"] == "")) {
833 $data["guid"] = $search->item(0)->nodeValue;
836 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
837 if ($search->length > 0) {
838 $data["nick"] = $search->item(0)->nodeValue;
841 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
842 if ($search->length > 0) {
843 $data["name"] = $search->item(0)->nodeValue;
846 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
847 if ($search->length > 0) {
848 $data["searchable"] = $search->item(0)->nodeValue;
851 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
852 if ($search->length > 0) {
853 $data["pubkey"] = $search->item(0)->nodeValue;
854 if (strstr($data["pubkey"], 'RSA ')) {
855 $data["pubkey"] = rsatopem($data["pubkey"]);
859 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
860 if ($search->length > 0) {
861 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
866 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
867 foreach ($photos as $photo) {
869 foreach ($photo->attributes as $attribute) {
870 $attr[$attribute->name] = trim($attribute->value);
873 if (isset($attr["src"]) AND isset($attr["width"])) {
874 $avatar[$attr["width"]] = $attr["src"];
877 // We don't have a width. So we just take everything that we got.
878 // This is a Hubzilla workaround which doesn't send a width.
879 if ((sizeof($avatar) == 0) AND isset($attr["src"])) {
880 $avatar[] = $attr["src"];
884 if (sizeof($avatar)) {
886 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
890 // Poll DFRN specific data
891 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
892 if ($search->length > 0) {
893 foreach ($search as $link) {
894 //$data["request"] = $search->item(0)->nodeValue;
896 foreach ($link->attributes as $attribute) {
897 $attr[$attribute->name] = trim($attribute->value);
900 $data[substr($attr["rel"], 5)] = $attr["href"];
904 // Older Friendica versions had used the "uid" field differently than newer versions
905 if ($data["nick"] == $data["guid"]) {
906 unset($data["guid"]);
915 * @brief Check for Diaspora contact
917 * @param array $webfinger Webfinger data
919 * @return array Diaspora data
921 private function diaspora($webfinger) {
925 foreach ($webfinger["links"] as $link) {
926 if (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != "")) {
927 $hcard_url = $link["href"];
928 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != "")) {
929 $data["baseurl"] = trim($link["href"], '/');
930 } elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != "")) {
931 $data["guid"] = $link["href"];
932 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND ($link["type"] == "text/html") AND ($link["href"] != "")) {
933 $data["url"] = $link["href"];
934 } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
935 $data["poll"] = $link["href"];
936 } elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != "")) {
937 $data["poco"] = $link["href"];
938 } elseif (($link["rel"] == "salmon") AND ($link["href"] != "")) {
939 $data["notify"] = $link["href"];
940 } elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
941 $data["pubkey"] = base64_decode($link["href"]);
943 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
944 if (strstr($data["pubkey"], 'RSA ')) {
945 $data["pubkey"] = rsatopem($data["pubkey"]);
950 if (!isset($data["url"]) OR ($hcard_url == "")) {
954 if (is_array($webfinger["aliases"])) {
955 foreach ($webfinger["aliases"] as $alias) {
956 if (normalise_link($alias) != normalise_link($data["url"]) AND ! strstr($alias, "@")) {
957 $data["alias"] = $alias;
962 // Fetch further information from the hcard
963 $data = self::pollHcard($hcard_url, $data);
969 if (isset($data["url"])
970 AND isset($data["guid"])
971 AND isset($data["baseurl"])
972 AND isset($data["pubkey"])
973 AND ($hcard_url != "")
975 $data["network"] = NETWORK_DIASPORA;
977 // The Diaspora handle must always be lowercase
978 $data["addr"] = strtolower($data["addr"]);
980 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
981 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
982 $data["batch"] = $data["baseurl"] . "/receive/public";
991 * @brief Check for OStatus contact
993 * @param array $webfinger Webfinger data
995 * @return array OStatus data
997 private function ostatus($webfinger) {
999 if (is_array($webfinger["aliases"])) {
1000 foreach ($webfinger["aliases"] as $alias) {
1001 if (strstr($alias, "@")) {
1002 $data["addr"] = str_replace('acct:', '', $alias);
1007 if (is_string($webfinger["subject"]) AND strstr($webfinger["subject"], "@")) {
1008 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1011 foreach ($webfinger["links"] as $link) {
1012 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1013 AND ($link["type"] == "text/html")
1014 AND ($link["href"] != "")
1016 $data["url"] = $link["href"];
1017 } elseif (($link["rel"] == "salmon") AND ($link["href"] != "")) {
1018 $data["notify"] = $link["href"];
1019 } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
1020 $data["poll"] = $link["href"];
1021 } elseif (($link["rel"] == "magic-public-key") AND ($link["href"] != "")) {
1022 $pubkey = $link["href"];
1024 if (substr($pubkey, 0, 5) === 'data:') {
1025 if (strstr($pubkey, ',')) {
1026 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1028 $pubkey = substr($pubkey, 5);
1030 } elseif (normalise_link($pubkey) == 'http://') {
1031 $ret = z_fetch_url($pubkey);
1032 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1035 $pubkey = $ret['body'];
1038 $key = explode(".", $pubkey);
1040 if (sizeof($key) >= 3) {
1041 $m = base64url_decode($key[1]);
1042 $e = base64url_decode($key[2]);
1043 $data["pubkey"] = metopem($m, $e);
1048 if (isset($data["notify"]) AND isset($data["pubkey"])
1049 AND isset($data["poll"])
1050 AND isset($data["url"])
1052 $data["network"] = NETWORK_OSTATUS;
1056 // Fetch all additional data from the feed
1057 $ret = z_fetch_url($data["poll"]);
1058 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1061 $feed = $ret['body'];
1062 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1066 if ($feed_data["header"]["author-name"] != "") {
1067 $data["name"] = $feed_data["header"]["author-name"];
1069 if ($feed_data["header"]["author-nick"] != "") {
1070 $data["nick"] = $feed_data["header"]["author-nick"];
1072 if ($feed_data["header"]["author-avatar"] != "") {
1073 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1075 if ($feed_data["header"]["author-id"] != "") {
1076 $data["alias"] = $feed_data["header"]["author-id"];
1078 if ($feed_data["header"]["author-location"] != "") {
1079 $data["location"] = $feed_data["header"]["author-location"];
1081 if ($feed_data["header"]["author-about"] != "") {
1082 $data["about"] = $feed_data["header"]["author-about"];
1084 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1085 // So we take the value that we just fetched, although the other one worked as well
1086 if ($feed_data["header"]["author-link"] != "") {
1087 $data["url"] = $feed_data["header"]["author-link"];
1089 /// @todo Fetch location and "about" from the feed as well
1094 * @brief Fetch data from a pump.io profile page
1096 * @param string $profile_link Link to the profile page
1098 * @return array profile data
1100 private function pumpioProfileData($profile_link) {
1102 $doc = new \DOMDocument();
1103 if (!@$doc->loadHTMLFile($profile_link)) {
1107 $xpath = new \DomXPath($doc);
1111 // This is ugly - but pump.io doesn't seem to know a better way for it
1112 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1113 $pos = strpos($data["name"], chr(10));
1115 $data["name"] = trim(substr($data["name"], 0, $pos));
1118 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1120 foreach ($avatar->attributes as $attribute) {
1121 if ($attribute->name == "src") {
1122 $data["photo"] = trim($attribute->value);
1127 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
1128 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
1134 * @brief Check for pump.io contact
1136 * @param array $webfinger Webfinger data
1138 * @return array pump.io data
1140 private function pumpio($webfinger) {
1143 foreach ($webfinger["links"] as $link) {
1144 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1145 AND ($link["type"] == "text/html")
1146 AND ($link["href"] != "")
1148 $data["url"] = $link["href"];
1149 } elseif (($link["rel"] == "activity-inbox") AND ($link["href"] != "")) {
1150 $data["notify"] = $link["href"];
1151 } elseif (($link["rel"] == "activity-outbox") AND ($link["href"] != "")) {
1152 $data["poll"] = $link["href"];
1153 } elseif (($link["rel"] == "dialback") AND ($link["href"] != "")) {
1154 $data["dialback"] = $link["href"];
1157 if (isset($data["poll"]) AND isset($data["notify"])
1158 AND isset($data["dialback"])
1159 AND isset($data["url"])
1161 // by now we use these fields only for the network type detection
1162 // So we unset all data that isn't used at the moment
1163 unset($data["dialback"]);
1165 $data["network"] = NETWORK_PUMPIO;
1170 $profile_data = self::pumpioProfileData($data["url"]);
1172 if (!$profile_data) {
1176 $data = array_merge($data, $profile_data);
1182 * @brief Check page for feed link
1184 * @param string $url Page link
1186 * @return string feed link
1188 private function getFeedLink($url) {
1189 $doc = new \DOMDocument();
1191 if (!@$doc->loadHTMLFile($url)) {
1195 $xpath = new \DomXPath($doc);
1197 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1198 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1199 if (!is_object($feeds)) {
1203 if ($feeds->length == 0) {
1209 foreach ($feeds as $feed) {
1211 foreach ($feed->attributes as $attribute) {
1212 $attr[$attribute->name] = trim($attribute->value);
1215 if ($feed_url == "") {
1216 $feed_url = $attr["href"];
1224 * @brief Check for feed contact
1226 * @param string $url Profile link
1227 * @param boolean $probe Do a probe if the page contains a feed link
1229 * @return array feed data
1231 private function feed($url, $probe = true) {
1232 $ret = z_fetch_url($url);
1233 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1236 $feed = $ret['body'];
1237 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1244 $feed_url = self::getFeedLink($url);
1250 return self::feed($feed_url, false);
1253 if ($feed_data["header"]["author-name"] != "") {
1254 $data["name"] = $feed_data["header"]["author-name"];
1257 if ($feed_data["header"]["author-nick"] != "") {
1258 $data["nick"] = $feed_data["header"]["author-nick"];
1261 if ($feed_data["header"]["author-avatar"] != "") {
1262 $data["photo"] = $feed_data["header"]["author-avatar"];
1265 if ($feed_data["header"]["author-id"] != "") {
1266 $data["alias"] = $feed_data["header"]["author-id"];
1269 $data["url"] = $url;
1270 $data["poll"] = $url;
1272 if ($feed_data["header"]["author-link"] != "") {
1273 $data["baseurl"] = $feed_data["header"]["author-link"];
1275 $data["baseurl"] = $data["url"];
1278 $data["network"] = NETWORK_FEED;
1284 * @brief Check for mail contact
1286 * @param string $uri Profile link
1287 * @param integer $uid User ID
1289 * @return array mail data
1291 private function mail($uri, $uid) {
1293 if (!validate_email($uri)) {
1297 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1299 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1301 if (\dbm::is_result($x) && \dbm::is_result($r)) {
1302 $mailbox = construct_mailbox_name($r[0]);
1304 openssl_private_decrypt(hex2bin($r[0]['pass']), $password, $x[0]['prvkey']);
1305 $mbox = email_connect($mailbox, $r[0]['user'], $password);
1311 $msgs = email_poll($mbox, $uri);
1312 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1314 if (!count($msgs)) {
1318 $phost = substr($uri, strpos($uri, '@') + 1);
1321 $data["addr"] = $uri;
1322 $data["network"] = NETWORK_MAIL;
1323 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1324 $data["nick"] = $data["name"];
1325 $data["photo"] = avatar_img($uri);
1326 $data["url"] = 'http://'.$phost."/".$data["nick"];
1327 $data["notify"] = 'smtp '.random_string();
1328 $data["poll"] = 'email '.random_string();
1330 $x = email_msg_meta($mbox, $msgs[0]);
1331 if (stristr($x[0]->from, $uri)) {
1332 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1333 } elseif (stristr($x[0]->to, $uri)) {
1334 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1337 foreach ($adr as $feadr) {
1338 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1339 &&(strcasecmp($feadr->host, $phost) == 0)
1340 && (strlen($feadr->personal))
1342 $personal = imap_mime_header_decode($feadr->personal);
1344 foreach ($personal as $perspart) {
1345 if ($perspart->charset != "default") {
1346 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1348 $data["name"] .= $perspart->text;
1352 $data["name"] = notags($data["name"]);
1362 * @brief Mix two paths together to possibly fix missing parts
1364 * @param string $avatar Path to the avatar
1365 * @param string $base Another path that is hopefully complete
1367 * @return string fixed avatar path
1369 public static function fixAvatar($avatar, $base) {
1370 $base_parts = parse_url($base);
1372 // Remove all parts that could create a problem
1373 unset($base_parts['path']);
1374 unset($base_parts['query']);
1375 unset($base_parts['fragment']);
1377 $avatar_parts = parse_url($avatar);
1380 $parts = array_merge($base_parts, $avatar_parts);
1382 // And put them together again
1383 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1384 $host = isset($parts['host']) ? $parts['host'] : '';
1385 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1386 $path = isset($parts['path']) ? $parts['path'] : '';
1387 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1388 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1390 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1392 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);