3 namespace Friendica\Network;
6 * @file src/Network/Probe.php
7 * @brief Functions for probing URL
12 use Friendica\Core\Config;
13 use Friendica\Core\PConfig;
15 require_once("include/feed.php");
16 require_once('include/email.php');
17 require_once('include/network.php');
20 * @brief This class contain functions for probing URL
25 private static $baseurl;
28 * @brief Rearrange the array so that it always has the same order
30 * @param array $data Unordered data
32 * @return array Ordered data
34 private function rearrange_data($data) {
35 $fields = array("name", "nick", "guid", "url", "addr", "alias",
36 "photo", "community", "keywords", "location", "about",
37 "batch", "notify", "poll", "request", "confirm", "poco",
38 "priority", "network", "pubkey", "baseurl");
41 foreach ($fields AS $field)
42 if (isset($data[$field]))
43 $newdata[$field] = $data[$field];
45 $newdata[$field] = "";
47 // We don't use the "priority" field anymore and replace it with a dummy.
48 $newdata["priority"] = 0;
54 * @brief Probes for XRD data
57 * 'lrdd' => Link to LRDD endpoint
58 * 'lrdd-xml' => Link to LRDD endpoint in XML format
59 * 'lrdd-json' => Link to LRDD endpoint in JSON format
61 private function xrd($host) {
63 // Reset the static variable
66 $ssl_url = "https://".$host."/.well-known/host-meta";
67 $url = "http://".$host."/.well-known/host-meta";
69 $xrd_timeout = Config::get('system','xrd_timeout', 20);
72 $ret = z_fetch_url($ssl_url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
73 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
78 $xrd = parse_xml_string($xml, false);
80 if (!is_object($xrd)) {
81 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
82 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
86 $xrd = parse_xml_string($xml, false);
91 $links = \xml::element_to_array($xrd);
92 if (!isset($links["xrd"]["link"]))
97 foreach ($links["xrd"]["link"] AS $value => $link) {
98 if (isset($link["@attributes"]))
99 $attributes = $link["@attributes"];
100 elseif ($value == "@attributes")
105 if (($attributes["rel"] == "lrdd") AND
106 ($attributes["type"] == "application/xrd+xml"))
107 $xrd_data["lrdd-xml"] = $attributes["template"];
108 elseif (($attributes["rel"] == "lrdd") AND
109 ($attributes["type"] == "application/json"))
110 $xrd_data["lrdd-json"] = $attributes["template"];
111 elseif ($attributes["rel"] == "lrdd")
112 $xrd_data["lrdd"] = $attributes["template"];
115 self::$baseurl = "http://".$host;
121 * @brief Perform Webfinger lookup and return DFRN data
123 * Given an email style address, perform webfinger lookup and
124 * return the resulting DFRN profile URL, or if no DFRN profile URL
125 * is located, returns an OStatus subscription template (prefixed
126 * with the string 'stat:' to identify it as on OStatus template).
127 * If this isn't an email style address just return $webbie.
128 * Return an empty string if email-style addresses but webfinger fails,
129 * or if the resultant personal XRD doesn't contain a supported
130 * subscription/friend-request attribute.
132 * amended 7/9/2011 to return an hcard which could save potentially loading
133 * a lengthy content page to scrape dfrn attributes
135 * @param string $webbie Address that should be probed
136 * @param string $hcard Link to the hcard - is returned by reference
138 * @return string profile link
141 public static function webfinger_dfrn($webbie, &$hcard) {
145 $links = self::lrdd($webbie);
146 logger('webfinger_dfrn: '.$webbie.':'.print_r($links,true), LOGGER_DATA);
148 foreach ($links as $link) {
149 if ($link['@attributes']['rel'] === NAMESPACE_DFRN)
150 $profile_link = $link['@attributes']['href'];
151 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) AND ($profile_link == ""))
152 $profile_link = 'stat:'.$link['@attributes']['template'];
153 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
154 $hcard = $link['@attributes']['href'];
157 return $profile_link;
161 * @brief Check an URI for LRDD data
163 * this is a replacement for the "lrdd" function in include/network.php.
164 * It isn't used in this class and has some redundancies in the code.
165 * When time comes we can check the existing calls for "lrdd" if we can rework them.
167 * @param string $uri Address that should be probed
169 * @return array uri data
171 public static function lrdd($uri) {
173 $lrdd = self::xrd($uri);
176 $parts = @parse_url($uri);
180 $host = $parts["host"];
181 if (isset($parts["port"])) {
182 $host .= ':'.$parts["port"];
185 $path_parts = explode("/", trim($parts["path"], "/"));
187 $nick = array_pop($path_parts);
190 $lrdd = self::xrd($host);
191 $host .= "/".array_shift($path_parts);
192 } while (!$lrdd AND (sizeof($path_parts) > 0));
198 foreach ($lrdd AS $key => $link) {
202 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json")))
205 $path = str_replace('{uri}', urlencode($uri), $link);
206 $webfinger = self::webfinger($path);
208 if (!$webfinger AND (strstr($uri, "@"))) {
209 $path = str_replace('{uri}', urlencode("acct:".$uri), $link);
210 $webfinger = self::webfinger($path);
213 // Special treatment for Mastodon
214 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
215 // But the webfinger for this format fails.
216 if (!$webfinger AND isset($nick)) {
217 // Mastodon uses a "@" as prefix for usernames in their url format
218 $nick = ltrim($nick, '@');
220 $addr = $nick."@".$host;
222 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
223 $webfinger = self::webfinger($path);
227 if (!is_array($webfinger["links"]))
232 foreach ($webfinger["links"] AS $link)
233 $data[] = array("@attributes" => $link);
235 if (is_array($webfinger["aliases"]))
236 foreach ($webfinger["aliases"] AS $alias)
237 $data[] = array("@attributes" =>
238 array("rel" => "alias",
245 * @brief Fetch information (protocol endpoints and user information) about a given uri
247 * @param string $uri Address that should be probed
248 * @param string $network Test for this specific network
249 * @param integer $uid User ID for the probe (only used for mails)
250 * @param boolean $cache Use cached values?
252 * @return array uri data
254 public static function uri($uri, $network = "", $uid = 0, $cache = true) {
257 $result = \Cache::get("probe_url:".$network.":".$uri);
258 if (!is_null($result)) {
266 $data = self::detect($uri, $network, $uid);
268 if (!isset($data["url"]))
271 if ($data["photo"] != "")
272 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
274 $data["photo"] = App::get_baseurl().'/images/person-175.jpg';
276 if (!isset($data["name"]) OR ($data["name"] == "")) {
277 if (isset($data["nick"]))
278 $data["name"] = $data["nick"];
280 if ($data["name"] == "")
281 $data["name"] = $data["url"];
284 if (!isset($data["nick"]) OR ($data["nick"] == "")) {
285 $data["nick"] = strtolower($data["name"]);
287 if (strpos($data['nick'], ' '))
288 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
291 if (self::$baseurl != "") {
292 $data["baseurl"] = self::$baseurl;
295 if (!isset($data["network"])) {
296 $data["network"] = NETWORK_PHANTOM;
299 $data = self::rearrange_data($data);
301 // Only store into the cache if the value seems to be valid
302 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
303 \Cache::set("probe_url:".$network.":".$uri, $data, CACHE_DAY);
305 /// @todo temporary fix - we need a real contact update function that updates only changing fields
306 /// The biggest problem is the avatar picture that could have a reduced image size.
307 /// It should only be updated if the existing picture isn't existing anymore.
308 if (($data['network'] != NETWORK_FEED) AND ($mode == PROBE_NORMAL) AND
309 $data["name"] AND $data["nick"] AND $data["url"] AND $data["addr"] AND $data["poll"])
310 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `url` = '%s', `addr` = '%s',
311 `notify` = '%s', `poll` = '%s', `alias` = '%s', `success_update` = '%s'
312 WHERE `nurl` = '%s' AND NOT `self` AND `uid` = 0",
313 dbesc($data["name"]),
314 dbesc($data["nick"]),
316 dbesc($data["addr"]),
317 dbesc($data["notify"]),
318 dbesc($data["poll"]),
319 dbesc($data["alias"]),
320 dbesc(datetime_convert()),
321 dbesc(normalise_link($data['url']))
329 * @brief Fetch information (protocol endpoints and user information) about a given uri
331 * This function is only called by the "uri" function that adds caching and rearranging of data.
333 * @param string $uri Address that should be probed
334 * @param string $network Test for this specific network
335 * @param integer $uid User ID for the probe (only used for mails)
337 * @return array uri data
339 private function detect($uri, $network, $uid) {
340 $parts = parse_url($uri);
342 if (isset($parts["scheme"]) AND isset($parts["host"]) AND isset($parts["path"])) {
344 $host = $parts["host"];
345 if (isset($parts["port"])) {
346 $host .= ':'.$parts["port"];
349 if ($host == 'twitter.com') {
350 return array("network" => NETWORK_TWITTER);
352 $lrdd = self::xrd($host);
354 $path_parts = explode("/", trim($parts["path"], "/"));
356 while (!$lrdd AND (sizeof($path_parts) > 1)) {
357 $host .= "/".array_shift($path_parts);
358 $lrdd = self::xrd($host);
361 return self::feed($uri);
363 $nick = array_pop($path_parts);
365 // Mastodon uses a "@" as prefix for usernames in their url format
366 $nick = ltrim($nick, '@');
368 $addr = $nick."@".$host;
369 } elseif (strstr($uri, '@')) {
370 // If the URI starts with "mailto:" then jump directly to the mail detection
371 if (strpos($url,'mailto:') !== false) {
372 $uri = str_replace('mailto:', '', $url);
373 return self::mail($uri, $uid);
376 if ($network == NETWORK_MAIL) {
377 return self::mail($uri, $uid);
379 // Remove "acct:" from the URI
380 $uri = str_replace('acct:', '', $uri);
382 $host = substr($uri,strpos($uri, '@') + 1);
383 $nick = substr($uri,0, strpos($uri, '@'));
385 if (strpos($uri, '@twitter.com')) {
386 return array("network" => NETWORK_TWITTER);
388 $lrdd = self::xrd($host);
391 return self::mail($uri, $uid);
400 /// @todo Do we need the prefix "acct:" or "acct://"?
402 foreach ($lrdd AS $key => $link) {
406 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
409 // At first try it with the given uri
410 $path = str_replace('{uri}', urlencode($uri), $link);
411 $webfinger = self::webfinger($path);
413 // We cannot be sure that the detected address was correct, so we don't use the values
414 if ($webfinger AND ($uri != $addr)) {
419 // Try webfinger with the address (user@domain.tld)
421 $path = str_replace('{uri}', urlencode($addr), $link);
422 $webfinger = self::webfinger($path);
425 // Mastodon needs to have it with "acct:"
427 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
428 $webfinger = self::webfinger($path);
432 return self::feed($uri);
437 logger("Probing ".$uri, LOGGER_DEBUG);
439 if (in_array($network, array("", NETWORK_DFRN)))
440 $result = self::dfrn($webfinger);
441 if ((!$result AND ($network == "")) OR ($network == NETWORK_DIASPORA))
442 $result = self::diaspora($webfinger);
443 if ((!$result AND ($network == "")) OR ($network == NETWORK_OSTATUS))
444 $result = self::ostatus($webfinger);
445 if ((!$result AND ($network == "")) OR ($network == NETWORK_PUMPIO))
446 $result = self::pumpio($webfinger);
447 if ((!$result AND ($network == "")) OR ($network == NETWORK_FEED))
448 $result = self::feed($uri);
450 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
451 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
452 if ((!isset($result["nick"]) OR ($result["nick"] == "") OR (strstr($result["nick"], " "))) AND ($nick != ""))
453 $result["nick"] = $nick;
455 if ((!isset($result["addr"]) OR ($result["addr"] == "")) AND ($addr != ""))
456 $result["addr"] = $addr;
459 logger($uri." is ".$result["network"], LOGGER_DEBUG);
461 if (!isset($result["baseurl"]) OR ($result["baseurl"] == "")) {
462 $pos = strpos($result["url"], $host);
464 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
471 * @brief Perform a webfinger request.
473 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
475 * @param string $url Address that should be probed
477 * @return array webfinger data
479 private function webfinger($url) {
481 $xrd_timeout = Config::get('system','xrd_timeout', 20);
484 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
485 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
488 $data = $ret['body'];
490 $xrd = parse_xml_string($data, false);
492 if (!is_object($xrd)) {
493 // If it is not XML, maybe it is JSON
494 $webfinger = json_decode($data, true);
496 if (!isset($webfinger["links"]))
502 $xrd_arr = \xml::element_to_array($xrd);
503 if (!isset($xrd_arr["xrd"]["link"]))
506 $webfinger = array();
508 if (isset($xrd_arr["xrd"]["subject"]))
509 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
511 if (isset($xrd_arr["xrd"]["alias"]))
512 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
514 $webfinger["links"] = array();
516 foreach ($xrd_arr["xrd"]["link"] AS $value => $data) {
517 if (isset($data["@attributes"]))
518 $attributes = $data["@attributes"];
519 elseif ($value == "@attributes")
524 $webfinger["links"][] = $attributes;
530 * @brief Poll the Friendica specific noscrape page.
532 * "noscrape" is a faster alternative to fetch the data from the hcard.
533 * This functionality was originally created for the directory.
535 * @param string $noscrape Link to the noscrape page
536 * @param array $data The already fetched data
538 * @return array noscrape data
540 private function poll_noscrape($noscrape, $data) {
541 $ret = z_fetch_url($noscrape);
542 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
545 $content = $ret['body'];
550 $json = json_decode($content, true);
551 if (!is_array($json))
554 if (isset($json["fn"]))
555 $data["name"] = $json["fn"];
557 if (isset($json["addr"]))
558 $data["addr"] = $json["addr"];
560 if (isset($json["nick"]))
561 $data["nick"] = $json["nick"];
563 if (isset($json["comm"]))
564 $data["community"] = $json["comm"];
566 if (isset($json["tags"])) {
567 $keywords = implode(" ", $json["tags"]);
569 $data["keywords"] = $keywords;
572 $location = formatted_location($json);
574 $data["location"] = $location;
576 if (isset($json["about"]))
577 $data["about"] = $json["about"];
579 if (isset($json["key"]))
580 $data["pubkey"] = $json["key"];
582 if (isset($json["photo"]))
583 $data["photo"] = $json["photo"];
585 if (isset($json["dfrn-request"]))
586 $data["request"] = $json["dfrn-request"];
588 if (isset($json["dfrn-confirm"]))
589 $data["confirm"] = $json["dfrn-confirm"];
591 if (isset($json["dfrn-notify"]))
592 $data["notify"] = $json["dfrn-notify"];
594 if (isset($json["dfrn-poll"]))
595 $data["poll"] = $json["dfrn-poll"];
601 * @brief Check for valid DFRN data
603 * @param array $data DFRN data
605 * @return int Number of errors
607 public static function valid_dfrn($data) {
609 if(!isset($data['key']))
611 if(!isset($data['dfrn-request']))
613 if(!isset($data['dfrn-confirm']))
615 if(!isset($data['dfrn-notify']))
617 if(!isset($data['dfrn-poll']))
623 * @brief Fetch data from a DFRN profile page and via "noscrape"
625 * @param string $profile Link to the profile page
627 * @return array profile data
629 public static function profile($profile) {
633 logger("Check profile ".$profile, LOGGER_DEBUG);
635 // Fetch data via noscrape - this is faster
636 $noscrape = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile);
637 $data = self::poll_noscrape($noscrape, $data);
639 if (!isset($data["notify"]) OR !isset($data["confirm"]) OR
640 !isset($data["request"]) OR !isset($data["poll"]) OR
641 !isset($data["poco"]) OR !isset($data["name"]) OR
642 !isset($data["photo"]))
643 $data = self::poll_hcard($profile, $data, true);
645 $prof_data = array();
646 $prof_data["addr"] = $data["addr"];
647 $prof_data["nick"] = $data["nick"];
648 $prof_data["dfrn-request"] = $data["request"];
649 $prof_data["dfrn-confirm"] = $data["confirm"];
650 $prof_data["dfrn-notify"] = $data["notify"];
651 $prof_data["dfrn-poll"] = $data["poll"];
652 $prof_data["dfrn-poco"] = $data["poco"];
653 $prof_data["photo"] = $data["photo"];
654 $prof_data["fn"] = $data["name"];
655 $prof_data["key"] = $data["pubkey"];
657 logger("Result for profile ".$profile.": ".print_r($prof_data, true), LOGGER_DEBUG);
663 * @brief Check for DFRN contact
665 * @param array $webfinger Webfinger data
667 * @return array DFRN data
669 private function dfrn($webfinger) {
673 foreach ($webfinger["links"] AS $link) {
674 if (($link["rel"] == NAMESPACE_DFRN) AND ($link["href"] != ""))
675 $data["network"] = NETWORK_DFRN;
676 elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
677 $data["poll"] = $link["href"];
678 elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
679 ($link["type"] == "text/html") AND ($link["href"] != ""))
680 $data["url"] = $link["href"];
681 elseif (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != ""))
682 $hcard = $link["href"];
683 elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != ""))
684 $data["poco"] = $link["href"];
685 elseif (($link["rel"] == "http://webfinger.net/rel/avatar") AND ($link["href"] != ""))
686 $data["photo"] = $link["href"];
688 elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != ""))
689 $data["baseurl"] = trim($link["href"], '/');
690 elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != ""))
691 $data["guid"] = $link["href"];
692 elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
693 $data["pubkey"] = base64_decode($link["href"]);
695 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
696 if (strstr($data["pubkey"], 'RSA '))
697 $data["pubkey"] = rsatopem($data["pubkey"]);
701 if (!isset($data["network"]) OR ($hcard == ""))
704 // Fetch data via noscrape - this is faster
705 $noscrape = str_replace("/hcard/", "/noscrape/", $hcard);
706 $data = self::poll_noscrape($noscrape, $data);
708 if (isset($data["notify"]) AND isset($data["confirm"]) AND isset($data["request"]) AND
709 isset($data["poll"]) AND isset($data["name"]) AND isset($data["photo"]))
712 $data = self::poll_hcard($hcard, $data, true);
718 * @brief Poll the hcard page (Diaspora and Friendica specific)
720 * @param string $hcard Link to the hcard page
721 * @param array $data The already fetched data
722 * @param boolean $dfrn Poll DFRN specific data
724 * @return array hcard data
726 private function poll_hcard($hcard, $data, $dfrn = false) {
727 $ret = z_fetch_url($hcard);
728 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
731 $content = $ret['body'];
736 $doc = new \DOMDocument();
737 if (!@$doc->loadHTML($content))
740 $xpath = new \DomXPath($doc);
742 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
743 if (!is_object($vcards))
746 if ($vcards->length > 0) {
747 $vcard = $vcards->item(0);
749 // We have to discard the guid from the hcard in favour of the guid from lrdd
750 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
751 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
752 if (($search->length > 0) AND ($data["guid"] == ""))
753 $data["guid"] = $search->item(0)->nodeValue;
755 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
756 if ($search->length > 0)
757 $data["nick"] = $search->item(0)->nodeValue;
759 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
760 if ($search->length > 0)
761 $data["name"] = $search->item(0)->nodeValue;
763 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
764 if ($search->length > 0)
765 $data["searchable"] = $search->item(0)->nodeValue;
767 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
768 if ($search->length > 0) {
769 $data["pubkey"] = $search->item(0)->nodeValue;
770 if (strstr($data["pubkey"], 'RSA '))
771 $data["pubkey"] = rsatopem($data["pubkey"]);
774 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
775 if ($search->length > 0)
776 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
780 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
781 foreach ($photos AS $photo) {
783 foreach ($photo->attributes as $attribute) {
784 $attr[$attribute->name] = trim($attribute->value);
787 if (isset($attr["src"]) AND isset($attr["width"])) {
788 $avatar[$attr["width"]] = $attr["src"];
791 // We don't have a width. So we just take everything that we got.
792 // This is a Hubzilla workaround which doesn't send a width.
793 if ((sizeof($avatar) == 0) AND isset($attr["src"])) {
794 $avatar[] = $attr["src"];
798 if (sizeof($avatar)) {
800 $data["photo"] = self::fix_avatar(array_pop($avatar), $data["baseurl"]);
804 // Poll DFRN specific data
805 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
806 if ($search->length > 0) {
807 foreach ($search AS $link) {
808 //$data["request"] = $search->item(0)->nodeValue;
810 foreach ($link->attributes as $attribute)
811 $attr[$attribute->name] = trim($attribute->value);
813 $data[substr($attr["rel"], 5)] = $attr["href"];
817 // Older Friendica versions had used the "uid" field differently than newer versions
818 if ($data["nick"] == $data["guid"])
819 unset($data["guid"]);
827 * @brief Check for Diaspora contact
829 * @param array $webfinger Webfinger data
831 * @return array Diaspora data
833 private function diaspora($webfinger) {
837 foreach ($webfinger["links"] AS $link) {
838 if (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != ""))
839 $hcard = $link["href"];
840 elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != ""))
841 $data["baseurl"] = trim($link["href"], '/');
842 elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != ""))
843 $data["guid"] = $link["href"];
844 elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
845 ($link["type"] == "text/html") AND ($link["href"] != ""))
846 $data["url"] = $link["href"];
847 elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
848 $data["poll"] = $link["href"];
849 elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != ""))
850 $data["poco"] = $link["href"];
851 elseif (($link["rel"] == "salmon") AND ($link["href"] != ""))
852 $data["notify"] = $link["href"];
853 elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
854 $data["pubkey"] = base64_decode($link["href"]);
856 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
857 if (strstr($data["pubkey"], 'RSA '))
858 $data["pubkey"] = rsatopem($data["pubkey"]);
862 if (!isset($data["url"]) OR ($hcard == ""))
865 if (is_array($webfinger["aliases"]))
866 foreach ($webfinger["aliases"] AS $alias)
867 if (normalise_link($alias) != normalise_link($data["url"]) AND !strstr($alias, "@"))
868 $data["alias"] = $alias;
870 // Fetch further information from the hcard
871 $data = self::poll_hcard($hcard, $data);
876 if (isset($data["url"]) AND isset($data["guid"]) AND isset($data["baseurl"]) AND
877 isset($data["pubkey"]) AND ($hcard != "")) {
878 $data["network"] = NETWORK_DIASPORA;
880 // The Diaspora handle must always be lowercase
881 $data["addr"] = strtolower($data["addr"]);
883 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
884 $data["notify"] = $data["baseurl"]."/receive/users/".$data["guid"];
885 $data["batch"] = $data["baseurl"]."/receive/public";
893 * @brief Check for OStatus contact
895 * @param array $webfinger Webfinger data
897 * @return array OStatus data
899 private function ostatus($webfinger) {
901 if (is_array($webfinger["aliases"])) {
902 foreach ($webfinger["aliases"] AS $alias) {
903 if (strstr($alias, "@")) {
904 $data["addr"] = str_replace('acct:', '', $alias);
909 if (is_string($webfinger["subject"]) AND strstr($webfinger["subject"], "@")) {
910 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
913 foreach ($webfinger["links"] AS $link) {
914 if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
915 ($link["type"] == "text/html") AND ($link["href"] != "")) {
916 $data["url"] = $link["href"];
917 } elseif (($link["rel"] == "salmon") AND ($link["href"] != "")) {
918 $data["notify"] = $link["href"];
919 } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
920 $data["poll"] = $link["href"];
921 } elseif (($link["rel"] == "magic-public-key") AND ($link["href"] != "")) {
922 $pubkey = $link["href"];
924 if (substr($pubkey, 0, 5) === 'data:') {
925 if (strstr($pubkey, ',')) {
926 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
928 $pubkey = substr($pubkey, 5);
930 } elseif (normalise_link($pubkey) == 'http://') {
931 $ret = z_fetch_url($pubkey);
932 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
935 $pubkey = $ret['body'];
938 $key = explode(".", $pubkey);
940 if (sizeof($key) >= 3) {
941 $m = base64url_decode($key[1]);
942 $e = base64url_decode($key[2]);
943 $data["pubkey"] = metopem($m,$e);
948 if (isset($data["notify"]) AND isset($data["pubkey"]) AND
949 isset($data["poll"]) AND isset($data["url"])) {
950 $data["network"] = NETWORK_OSTATUS;
954 // Fetch all additional data from the feed
955 $ret = z_fetch_url($data["poll"]);
956 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
959 $feed = $ret['body'];
960 $feed_data = feed_import($feed,$dummy1,$dummy2, $dummy3, true);
964 if ($feed_data["header"]["author-name"] != "") {
965 $data["name"] = $feed_data["header"]["author-name"];
967 if ($feed_data["header"]["author-nick"] != "") {
968 $data["nick"] = $feed_data["header"]["author-nick"];
970 if ($feed_data["header"]["author-avatar"] != "") {
971 $data["photo"] = self::fix_avatar($feed_data["header"]["author-avatar"], $data["url"]);
973 if ($feed_data["header"]["author-id"] != "") {
974 $data["alias"] = $feed_data["header"]["author-id"];
976 if ($feed_data["header"]["author-location"] != "") {
977 $data["location"] = $feed_data["header"]["author-location"];
979 if ($feed_data["header"]["author-about"] != "") {
980 $data["about"] = $feed_data["header"]["author-about"];
982 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
983 // So we take the value that we just fetched, although the other one worked as well
984 if ($feed_data["header"]["author-link"] != "") {
985 $data["url"] = $feed_data["header"]["author-link"];
987 /// @todo Fetch location and "about" from the feed as well
992 * @brief Fetch data from a pump.io profile page
994 * @param string $profile Link to the profile page
996 * @return array profile data
998 private function pumpio_profile_data($profile) {
1000 $doc = new \DOMDocument();
1001 if (!@$doc->loadHTMLFile($profile))
1004 $xpath = new \DomXPath($doc);
1008 // This is ugly - but pump.io doesn't seem to know a better way for it
1009 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1010 $pos = strpos($data["name"], chr(10));
1012 $data["name"] = trim(substr($data["name"], 0, $pos));
1014 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1016 foreach ($avatar->attributes as $attribute)
1017 if ($attribute->name == "src")
1018 $data["photo"] = trim($attribute->value);
1020 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
1021 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
1027 * @brief Check for pump.io contact
1029 * @param array $webfinger Webfinger data
1031 * @return array pump.io data
1033 private function pumpio($webfinger) {
1036 foreach ($webfinger["links"] AS $link) {
1037 if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
1038 ($link["type"] == "text/html") AND ($link["href"] != ""))
1039 $data["url"] = $link["href"];
1040 elseif (($link["rel"] == "activity-inbox") AND ($link["href"] != ""))
1041 $data["notify"] = $link["href"];
1042 elseif (($link["rel"] == "activity-outbox") AND ($link["href"] != ""))
1043 $data["poll"] = $link["href"];
1044 elseif (($link["rel"] == "dialback") AND ($link["href"] != ""))
1045 $data["dialback"] = $link["href"];
1047 if (isset($data["poll"]) AND isset($data["notify"]) AND
1048 isset($data["dialback"]) AND isset($data["url"])) {
1050 // by now we use these fields only for the network type detection
1051 // So we unset all data that isn't used at the moment
1052 unset($data["dialback"]);
1054 $data["network"] = NETWORK_PUMPIO;
1058 $profile_data = self::pumpio_profile_data($data["url"]);
1063 $data = array_merge($data, $profile_data);
1069 * @brief Check page for feed link
1071 * @param string $url Page link
1073 * @return string feed link
1075 private function get_feed_link($url) {
1076 $doc = new \DOMDocument();
1078 if (!@$doc->loadHTMLFile($url))
1081 $xpath = new \DomXPath($doc);
1083 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1084 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1085 if (!is_object($feeds))
1088 if ($feeds->length == 0)
1093 foreach ($feeds AS $feed) {
1095 foreach ($feed->attributes as $attribute)
1096 $attr[$attribute->name] = trim($attribute->value);
1098 if ($feed_url == "")
1099 $feed_url = $attr["href"];
1106 * @brief Check for feed contact
1108 * @param string $url Profile link
1109 * @param boolean $probe Do a probe if the page contains a feed link
1111 * @return array feed data
1113 private function feed($url, $probe = true) {
1114 $ret = z_fetch_url($url);
1115 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1118 $feed = $ret['body'];
1119 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1125 $feed_url = self::get_feed_link($url);
1130 return self::feed($feed_url, false);
1133 if ($feed_data["header"]["author-name"] != "")
1134 $data["name"] = $feed_data["header"]["author-name"];
1136 if ($feed_data["header"]["author-nick"] != "")
1137 $data["nick"] = $feed_data["header"]["author-nick"];
1139 if ($feed_data["header"]["author-avatar"] != "")
1140 $data["photo"] = $feed_data["header"]["author-avatar"];
1142 if ($feed_data["header"]["author-id"] != "")
1143 $data["alias"] = $feed_data["header"]["author-id"];
1145 $data["url"] = $url;
1146 $data["poll"] = $url;
1148 if ($feed_data["header"]["author-link"] != "")
1149 $data["baseurl"] = $feed_data["header"]["author-link"];
1151 $data["baseurl"] = $data["url"];
1153 $data["network"] = NETWORK_FEED;
1159 * @brief Check for mail contact
1161 * @param string $uri Profile link
1162 * @param integer $uid User ID
1164 * @return array mail data
1166 private function mail($uri, $uid) {
1168 if (!validate_email($uri))
1171 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1173 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1175 if (\dbm::is_result($x) && \dbm::is_result($r)) {
1176 $mailbox = construct_mailbox_name($r[0]);
1178 openssl_private_decrypt(hex2bin($r[0]['pass']), $password,$x[0]['prvkey']);
1179 $mbox = email_connect($mailbox,$r[0]['user'], $password);
1184 $msgs = email_poll($mbox, $uri);
1185 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1192 $data["addr"] = $uri;
1193 $data["network"] = NETWORK_MAIL;
1194 $data["name"] = substr($uri, 0, strpos($uri,'@'));
1195 $data["nick"] = $data["name"];
1196 $data["photo"] = avatar_img($uri);
1198 $phost = substr($uri, strpos($uri,'@') + 1);
1199 $data["url"] = 'http://'.$phost."/".$data["nick"];
1200 $data["notify"] = 'smtp '.random_string();
1201 $data["poll"] = 'email '.random_string();
1203 $x = email_msg_meta($mbox, $msgs[0]);
1204 if(stristr($x[0]->from, $uri))
1205 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1206 elseif(stristr($x[0]->to, $uri))
1207 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1209 foreach($adr as $feadr) {
1210 if((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1211 &&(strcasecmp($feadr->host, $phost) == 0)
1212 && (strlen($feadr->personal))) {
1214 $personal = imap_mime_header_decode($feadr->personal);
1216 foreach($personal as $perspart)
1217 if ($perspart->charset != "default")
1218 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1220 $data["name"] .= $perspart->text;
1222 $data["name"] = notags($data["name"]);
1232 * @brief Mix two paths together to possibly fix missing parts
1234 * @param string $avatar Path to the avatar
1235 * @param string $base Another path that is hopefully complete
1237 * @return string fixed avatar path
1239 public static function fix_avatar($avatar, $base) {
1240 $base_parts = parse_url($base);
1242 // Remove all parts that could create a problem
1243 unset($base_parts['path']);
1244 unset($base_parts['query']);
1245 unset($base_parts['fragment']);
1247 $avatar_parts = parse_url($avatar);
1250 $parts = array_merge($base_parts, $avatar_parts);
1252 // And put them together again
1253 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1254 $host = isset($parts['host']) ? $parts['host'] : '';
1255 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1256 $path = isset($parts['path']) ? $parts['path'] : '';
1257 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1258 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1260 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1262 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);