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