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 rearrangeData($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
56 * @param string $host The host part of an url
59 * 'lrdd' => Link to LRDD endpoint
60 * 'lrdd-xml' => Link to LRDD endpoint in XML format
61 * 'lrdd-json' => Link to LRDD endpoint in JSON format
63 private function xrd($host) {
65 // Reset the static variable
68 $ssl_url = "https://".$host."/.well-known/host-meta";
69 $url = "http://".$host."/.well-known/host-meta";
71 $xrd_timeout = Config::get('system','xrd_timeout', 20);
74 $ret = z_fetch_url($ssl_url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
75 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
80 $xrd = parse_xml_string($xml, false);
82 if (!is_object($xrd)) {
83 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
84 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
88 $xrd = parse_xml_string($xml, false);
93 $links = \xml::element_to_array($xrd);
94 if (!isset($links["xrd"]["link"]))
99 foreach ($links["xrd"]["link"] AS $value => $link) {
100 if (isset($link["@attributes"]))
101 $attributes = $link["@attributes"];
102 elseif ($value == "@attributes")
107 if (($attributes["rel"] == "lrdd") AND
108 ($attributes["type"] == "application/xrd+xml"))
109 $xrd_data["lrdd-xml"] = $attributes["template"];
110 elseif (($attributes["rel"] == "lrdd") AND
111 ($attributes["type"] == "application/json"))
112 $xrd_data["lrdd-json"] = $attributes["template"];
113 elseif ($attributes["rel"] == "lrdd")
114 $xrd_data["lrdd"] = $attributes["template"];
117 self::$baseurl = "http://".$host;
123 * @brief Perform Webfinger lookup and return DFRN data
125 * Given an email style address, perform webfinger lookup and
126 * return the resulting DFRN profile URL, or if no DFRN profile URL
127 * is located, returns an OStatus subscription template (prefixed
128 * with the string 'stat:' to identify it as on OStatus template).
129 * If this isn't an email style address just return $webbie.
130 * Return an empty string if email-style addresses but webfinger fails,
131 * or if the resultant personal XRD doesn't contain a supported
132 * subscription/friend-request attribute.
134 * amended 7/9/2011 to return an hcard which could save potentially loading
135 * a lengthy content page to scrape dfrn attributes
137 * @param string $webbie Address that should be probed
138 * @param string $hcard Link to the hcard - is returned by reference
140 * @return string profile link
143 public static function webfingerDfrn($webbie, &$hcard) {
147 $links = self::lrdd($webbie);
148 logger('webfingerDfrn: '.$webbie.':'.print_r($links,true), LOGGER_DATA);
150 foreach ($links as $link) {
151 if ($link['@attributes']['rel'] === NAMESPACE_DFRN)
152 $profile_link = $link['@attributes']['href'];
153 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) AND ($profile_link == ""))
154 $profile_link = 'stat:'.$link['@attributes']['template'];
155 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
156 $hcard = $link['@attributes']['href'];
159 return $profile_link;
163 * @brief Check an URI for LRDD data
165 * this is a replacement for the "lrdd" function in include/network.php.
166 * It isn't used in this class and has some redundancies in the code.
167 * When time comes we can check the existing calls for "lrdd" if we can rework them.
169 * @param string $uri Address that should be probed
171 * @return array uri data
173 public static function lrdd($uri) {
175 $lrdd = self::xrd($uri);
178 $parts = @parse_url($uri);
182 $host = $parts["host"];
183 if (isset($parts["port"])) {
184 $host .= ':'.$parts["port"];
187 $path_parts = explode("/", trim($parts["path"], "/"));
189 $nick = array_pop($path_parts);
192 $lrdd = self::xrd($host);
193 $host .= "/".array_shift($path_parts);
194 } while (!$lrdd AND (sizeof($path_parts) > 0));
200 foreach ($lrdd AS $key => $link) {
204 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json")))
207 $path = str_replace('{uri}', urlencode($uri), $link);
208 $webfinger = self::webfinger($path);
210 if (!$webfinger AND (strstr($uri, "@"))) {
211 $path = str_replace('{uri}', urlencode("acct:".$uri), $link);
212 $webfinger = self::webfinger($path);
215 // Special treatment for Mastodon
216 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
217 // But the webfinger for this format fails.
218 if (!$webfinger AND isset($nick)) {
219 // Mastodon uses a "@" as prefix for usernames in their url format
220 $nick = ltrim($nick, '@');
222 $addr = $nick."@".$host;
224 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
225 $webfinger = self::webfinger($path);
229 if (!is_array($webfinger["links"]))
234 foreach ($webfinger["links"] AS $link)
235 $data[] = array("@attributes" => $link);
237 if (is_array($webfinger["aliases"]))
238 foreach ($webfinger["aliases"] AS $alias)
239 $data[] = array("@attributes" =>
240 array("rel" => "alias",
247 * @brief Fetch information (protocol endpoints and user information) about a given uri
249 * @param string $uri Address that should be probed
250 * @param string $network Test for this specific network
251 * @param integer $uid User ID for the probe (only used for mails)
252 * @param boolean $cache Use cached values?
254 * @return array uri data
256 public static function uri($uri, $network = "", $uid = 0, $cache = true) {
259 $result = \Cache::get("probe_url:".$network.":".$uri);
260 if (!is_null($result)) {
268 $data = self::detect($uri, $network, $uid);
270 if (!isset($data["url"]))
273 if ($data["photo"] != "")
274 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
276 $data["photo"] = App::get_baseurl().'/images/person-175.jpg';
278 if (!isset($data["name"]) OR ($data["name"] == "")) {
279 if (isset($data["nick"]))
280 $data["name"] = $data["nick"];
282 if ($data["name"] == "")
283 $data["name"] = $data["url"];
286 if (!isset($data["nick"]) OR ($data["nick"] == "")) {
287 $data["nick"] = strtolower($data["name"]);
289 if (strpos($data['nick'], ' '))
290 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
293 if (self::$baseurl != "") {
294 $data["baseurl"] = self::$baseurl;
297 if (!isset($data["network"])) {
298 $data["network"] = NETWORK_PHANTOM;
301 $data = self::rearrangeData($data);
303 // Only store into the cache if the value seems to be valid
304 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
305 \Cache::set("probe_url:".$network.":".$uri, $data, CACHE_DAY);
307 /// @todo temporary fix - we need a real contact update function that updates only changing fields
308 /// The biggest problem is the avatar picture that could have a reduced image size.
309 /// It should only be updated if the existing picture isn't existing anymore.
310 if (($data['network'] != NETWORK_FEED) AND ($mode == PROBE_NORMAL) AND
311 $data["name"] AND $data["nick"] AND $data["url"] AND $data["addr"] AND $data["poll"])
312 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `url` = '%s', `addr` = '%s',
313 `notify` = '%s', `poll` = '%s', `alias` = '%s', `success_update` = '%s'
314 WHERE `nurl` = '%s' AND NOT `self` AND `uid` = 0",
315 dbesc($data["name"]),
316 dbesc($data["nick"]),
318 dbesc($data["addr"]),
319 dbesc($data["notify"]),
320 dbesc($data["poll"]),
321 dbesc($data["alias"]),
322 dbesc(datetime_convert()),
323 dbesc(normalise_link($data['url']))
331 * @brief Fetch information (protocol endpoints and user information) about a given uri
333 * This function is only called by the "uri" function that adds caching and rearranging of data.
335 * @param string $uri Address that should be probed
336 * @param string $network Test for this specific network
337 * @param integer $uid User ID for the probe (only used for mails)
339 * @return array uri data
341 private function detect($uri, $network, $uid) {
342 $parts = parse_url($uri);
344 if (isset($parts["scheme"]) AND isset($parts["host"]) AND isset($parts["path"])) {
346 $host = $parts["host"];
347 if (isset($parts["port"])) {
348 $host .= ':'.$parts["port"];
351 if ($host == 'twitter.com') {
352 return array("network" => NETWORK_TWITTER);
354 $lrdd = self::xrd($host);
356 $path_parts = explode("/", trim($parts["path"], "/"));
358 while (!$lrdd AND (sizeof($path_parts) > 1)) {
359 $host .= "/".array_shift($path_parts);
360 $lrdd = self::xrd($host);
363 return self::feed($uri);
365 $nick = array_pop($path_parts);
367 // Mastodon uses a "@" as prefix for usernames in their url format
368 $nick = ltrim($nick, '@');
370 $addr = $nick."@".$host;
371 } elseif (strstr($uri, '@')) {
372 // If the URI starts with "mailto:" then jump directly to the mail detection
373 if (strpos($url,'mailto:') !== false) {
374 $uri = str_replace('mailto:', '', $url);
375 return self::mail($uri, $uid);
378 if ($network == NETWORK_MAIL) {
379 return self::mail($uri, $uid);
381 // Remove "acct:" from the URI
382 $uri = str_replace('acct:', '', $uri);
384 $host = substr($uri,strpos($uri, '@') + 1);
385 $nick = substr($uri,0, strpos($uri, '@'));
387 if (strpos($uri, '@twitter.com')) {
388 return array("network" => NETWORK_TWITTER);
390 $lrdd = self::xrd($host);
393 return self::mail($uri, $uid);
402 /// @todo Do we need the prefix "acct:" or "acct://"?
404 foreach ($lrdd AS $key => $link) {
408 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
411 // At first try it with the given uri
412 $path = str_replace('{uri}', urlencode($uri), $link);
413 $webfinger = self::webfinger($path);
415 // We cannot be sure that the detected address was correct, so we don't use the values
416 if ($webfinger AND ($uri != $addr)) {
421 // Try webfinger with the address (user@domain.tld)
423 $path = str_replace('{uri}', urlencode($addr), $link);
424 $webfinger = self::webfinger($path);
427 // Mastodon needs to have it with "acct:"
429 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
430 $webfinger = self::webfinger($path);
434 return self::feed($uri);
439 logger("Probing ".$uri, LOGGER_DEBUG);
441 if (in_array($network, array("", NETWORK_DFRN)))
442 $result = self::dfrn($webfinger);
443 if ((!$result AND ($network == "")) OR ($network == NETWORK_DIASPORA))
444 $result = self::diaspora($webfinger);
445 if ((!$result AND ($network == "")) OR ($network == NETWORK_OSTATUS))
446 $result = self::ostatus($webfinger);
447 if ((!$result AND ($network == "")) OR ($network == NETWORK_PUMPIO))
448 $result = self::pumpio($webfinger);
449 if ((!$result AND ($network == "")) OR ($network == NETWORK_FEED))
450 $result = self::feed($uri);
452 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
453 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
454 if ((!isset($result["nick"]) OR ($result["nick"] == "") OR (strstr($result["nick"], " "))) AND ($nick != ""))
455 $result["nick"] = $nick;
457 if ((!isset($result["addr"]) OR ($result["addr"] == "")) AND ($addr != ""))
458 $result["addr"] = $addr;
461 logger($uri." is ".$result["network"], LOGGER_DEBUG);
463 if (!isset($result["baseurl"]) OR ($result["baseurl"] == "")) {
464 $pos = strpos($result["url"], $host);
466 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
473 * @brief Perform a webfinger request.
475 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
477 * @param string $url Address that should be probed
479 * @return array webfinger data
481 private function webfinger($url) {
483 $xrd_timeout = Config::get('system','xrd_timeout', 20);
486 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
487 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
490 $data = $ret['body'];
492 $xrd = parse_xml_string($data, false);
494 if (!is_object($xrd)) {
495 // If it is not XML, maybe it is JSON
496 $webfinger = json_decode($data, true);
498 if (!isset($webfinger["links"]))
504 $xrd_arr = \xml::element_to_array($xrd);
505 if (!isset($xrd_arr["xrd"]["link"]))
508 $webfinger = array();
510 if (isset($xrd_arr["xrd"]["subject"]))
511 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
513 if (isset($xrd_arr["xrd"]["alias"]))
514 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
516 $webfinger["links"] = array();
518 foreach ($xrd_arr["xrd"]["link"] AS $value => $data) {
519 if (isset($data["@attributes"]))
520 $attributes = $data["@attributes"];
521 elseif ($value == "@attributes")
526 $webfinger["links"][] = $attributes;
532 * @brief Poll the Friendica specific noscrape page.
534 * "noscrape" is a faster alternative to fetch the data from the hcard.
535 * This functionality was originally created for the directory.
537 * @param string $noscrape Link to the noscrape page
538 * @param array $data The already fetched data
540 * @return array noscrape data
542 private function pollNoscrape($noscrape, $data) {
543 $ret = z_fetch_url($noscrape);
544 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
547 $content = $ret['body'];
552 $json = json_decode($content, true);
553 if (!is_array($json))
556 if (isset($json["fn"]))
557 $data["name"] = $json["fn"];
559 if (isset($json["addr"]))
560 $data["addr"] = $json["addr"];
562 if (isset($json["nick"]))
563 $data["nick"] = $json["nick"];
565 if (isset($json["comm"]))
566 $data["community"] = $json["comm"];
568 if (isset($json["tags"])) {
569 $keywords = implode(" ", $json["tags"]);
571 $data["keywords"] = $keywords;
574 $location = formatted_location($json);
576 $data["location"] = $location;
578 if (isset($json["about"]))
579 $data["about"] = $json["about"];
581 if (isset($json["key"]))
582 $data["pubkey"] = $json["key"];
584 if (isset($json["photo"]))
585 $data["photo"] = $json["photo"];
587 if (isset($json["dfrn-request"]))
588 $data["request"] = $json["dfrn-request"];
590 if (isset($json["dfrn-confirm"]))
591 $data["confirm"] = $json["dfrn-confirm"];
593 if (isset($json["dfrn-notify"]))
594 $data["notify"] = $json["dfrn-notify"];
596 if (isset($json["dfrn-poll"]))
597 $data["poll"] = $json["dfrn-poll"];
603 * @brief Check for valid DFRN data
605 * @param array $data DFRN data
607 * @return int Number of errors
609 public static function validDfrn($data) {
611 if(!isset($data['key']))
613 if(!isset($data['dfrn-request']))
615 if(!isset($data['dfrn-confirm']))
617 if(!isset($data['dfrn-notify']))
619 if(!isset($data['dfrn-poll']))
625 * @brief Fetch data from a DFRN profile page and via "noscrape"
627 * @param string $profile Link to the profile page
629 * @return array profile data
631 public static function profile($profile) {
635 logger("Check profile ".$profile, LOGGER_DEBUG);
637 // Fetch data via noscrape - this is faster
638 $noscrape = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile);
639 $data = self::pollNoscrape($noscrape, $data);
641 if (!isset($data["notify"]) OR !isset($data["confirm"]) OR
642 !isset($data["request"]) OR !isset($data["poll"]) OR
643 !isset($data["poco"]) OR !isset($data["name"]) OR
644 !isset($data["photo"]))
645 $data = self::pollHcard($profile, $data, true);
647 $prof_data = array();
648 $prof_data["addr"] = $data["addr"];
649 $prof_data["nick"] = $data["nick"];
650 $prof_data["dfrn-request"] = $data["request"];
651 $prof_data["dfrn-confirm"] = $data["confirm"];
652 $prof_data["dfrn-notify"] = $data["notify"];
653 $prof_data["dfrn-poll"] = $data["poll"];
654 $prof_data["dfrn-poco"] = $data["poco"];
655 $prof_data["photo"] = $data["photo"];
656 $prof_data["fn"] = $data["name"];
657 $prof_data["key"] = $data["pubkey"];
659 logger("Result for profile ".$profile.": ".print_r($prof_data, true), LOGGER_DEBUG);
665 * @brief Check for DFRN contact
667 * @param array $webfinger Webfinger data
669 * @return array DFRN data
671 private function dfrn($webfinger) {
675 foreach ($webfinger["links"] AS $link) {
676 if (($link["rel"] == NAMESPACE_DFRN) AND ($link["href"] != ""))
677 $data["network"] = NETWORK_DFRN;
678 elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
679 $data["poll"] = $link["href"];
680 elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
681 ($link["type"] == "text/html") AND ($link["href"] != ""))
682 $data["url"] = $link["href"];
683 elseif (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != ""))
684 $hcard = $link["href"];
685 elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != ""))
686 $data["poco"] = $link["href"];
687 elseif (($link["rel"] == "http://webfinger.net/rel/avatar") AND ($link["href"] != ""))
688 $data["photo"] = $link["href"];
690 elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != ""))
691 $data["baseurl"] = trim($link["href"], '/');
692 elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != ""))
693 $data["guid"] = $link["href"];
694 elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
695 $data["pubkey"] = base64_decode($link["href"]);
697 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
698 if (strstr($data["pubkey"], 'RSA '))
699 $data["pubkey"] = rsatopem($data["pubkey"]);
703 if (!isset($data["network"]) OR ($hcard == ""))
706 // Fetch data via noscrape - this is faster
707 $noscrape = str_replace("/hcard/", "/noscrape/", $hcard);
708 $data = self::pollNoscrape($noscrape, $data);
710 if (isset($data["notify"]) AND isset($data["confirm"]) AND isset($data["request"]) AND
711 isset($data["poll"]) AND isset($data["name"]) AND isset($data["photo"]))
714 $data = self::pollHcard($hcard, $data, true);
720 * @brief Poll the hcard page (Diaspora and Friendica specific)
722 * @param string $hcard Link to the hcard page
723 * @param array $data The already fetched data
724 * @param boolean $dfrn Poll DFRN specific data
726 * @return array hcard data
728 private function pollHcard($hcard, $data, $dfrn = false) {
729 $ret = z_fetch_url($hcard);
730 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
733 $content = $ret['body'];
738 $doc = new \DOMDocument();
739 if (!@$doc->loadHTML($content))
742 $xpath = new \DomXPath($doc);
744 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
745 if (!is_object($vcards))
748 if ($vcards->length > 0) {
749 $vcard = $vcards->item(0);
751 // We have to discard the guid from the hcard in favour of the guid from lrdd
752 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
753 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
754 if (($search->length > 0) AND ($data["guid"] == ""))
755 $data["guid"] = $search->item(0)->nodeValue;
757 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
758 if ($search->length > 0)
759 $data["nick"] = $search->item(0)->nodeValue;
761 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
762 if ($search->length > 0)
763 $data["name"] = $search->item(0)->nodeValue;
765 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
766 if ($search->length > 0)
767 $data["searchable"] = $search->item(0)->nodeValue;
769 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
770 if ($search->length > 0) {
771 $data["pubkey"] = $search->item(0)->nodeValue;
772 if (strstr($data["pubkey"], 'RSA '))
773 $data["pubkey"] = rsatopem($data["pubkey"]);
776 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
777 if ($search->length > 0)
778 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
782 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
783 foreach ($photos AS $photo) {
785 foreach ($photo->attributes as $attribute) {
786 $attr[$attribute->name] = trim($attribute->value);
789 if (isset($attr["src"]) AND isset($attr["width"])) {
790 $avatar[$attr["width"]] = $attr["src"];
793 // We don't have a width. So we just take everything that we got.
794 // This is a Hubzilla workaround which doesn't send a width.
795 if ((sizeof($avatar) == 0) AND isset($attr["src"])) {
796 $avatar[] = $attr["src"];
800 if (sizeof($avatar)) {
802 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
806 // Poll DFRN specific data
807 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
808 if ($search->length > 0) {
809 foreach ($search AS $link) {
810 //$data["request"] = $search->item(0)->nodeValue;
812 foreach ($link->attributes as $attribute)
813 $attr[$attribute->name] = trim($attribute->value);
815 $data[substr($attr["rel"], 5)] = $attr["href"];
819 // Older Friendica versions had used the "uid" field differently than newer versions
820 if ($data["nick"] == $data["guid"])
821 unset($data["guid"]);
829 * @brief Check for Diaspora contact
831 * @param array $webfinger Webfinger data
833 * @return array Diaspora data
835 private function diaspora($webfinger) {
839 foreach ($webfinger["links"] AS $link) {
840 if (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != ""))
841 $hcard = $link["href"];
842 elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != ""))
843 $data["baseurl"] = trim($link["href"], '/');
844 elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != ""))
845 $data["guid"] = $link["href"];
846 elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
847 ($link["type"] == "text/html") AND ($link["href"] != ""))
848 $data["url"] = $link["href"];
849 elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
850 $data["poll"] = $link["href"];
851 elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != ""))
852 $data["poco"] = $link["href"];
853 elseif (($link["rel"] == "salmon") AND ($link["href"] != ""))
854 $data["notify"] = $link["href"];
855 elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
856 $data["pubkey"] = base64_decode($link["href"]);
858 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
859 if (strstr($data["pubkey"], 'RSA '))
860 $data["pubkey"] = rsatopem($data["pubkey"]);
864 if (!isset($data["url"]) OR ($hcard == ""))
867 if (is_array($webfinger["aliases"]))
868 foreach ($webfinger["aliases"] AS $alias)
869 if (normalise_link($alias) != normalise_link($data["url"]) AND !strstr($alias, "@"))
870 $data["alias"] = $alias;
872 // Fetch further information from the hcard
873 $data = self::pollHcard($hcard, $data);
878 if (isset($data["url"]) AND isset($data["guid"]) AND isset($data["baseurl"]) AND
879 isset($data["pubkey"]) AND ($hcard != "")) {
880 $data["network"] = NETWORK_DIASPORA;
882 // The Diaspora handle must always be lowercase
883 $data["addr"] = strtolower($data["addr"]);
885 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
886 $data["notify"] = $data["baseurl"]."/receive/users/".$data["guid"];
887 $data["batch"] = $data["baseurl"]."/receive/public";
895 * @brief Check for OStatus contact
897 * @param array $webfinger Webfinger data
899 * @return array OStatus data
901 private function ostatus($webfinger) {
903 if (is_array($webfinger["aliases"])) {
904 foreach ($webfinger["aliases"] AS $alias) {
905 if (strstr($alias, "@")) {
906 $data["addr"] = str_replace('acct:', '', $alias);
911 if (is_string($webfinger["subject"]) AND strstr($webfinger["subject"], "@")) {
912 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
915 foreach ($webfinger["links"] AS $link) {
916 if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
917 ($link["type"] == "text/html") AND ($link["href"] != "")) {
918 $data["url"] = $link["href"];
919 } elseif (($link["rel"] == "salmon") AND ($link["href"] != "")) {
920 $data["notify"] = $link["href"];
921 } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
922 $data["poll"] = $link["href"];
923 } elseif (($link["rel"] == "magic-public-key") AND ($link["href"] != "")) {
924 $pubkey = $link["href"];
926 if (substr($pubkey, 0, 5) === 'data:') {
927 if (strstr($pubkey, ',')) {
928 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
930 $pubkey = substr($pubkey, 5);
932 } elseif (normalise_link($pubkey) == 'http://') {
933 $ret = z_fetch_url($pubkey);
934 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
937 $pubkey = $ret['body'];
940 $key = explode(".", $pubkey);
942 if (sizeof($key) >= 3) {
943 $m = base64url_decode($key[1]);
944 $e = base64url_decode($key[2]);
945 $data["pubkey"] = metopem($m,$e);
950 if (isset($data["notify"]) AND isset($data["pubkey"]) AND
951 isset($data["poll"]) AND isset($data["url"])) {
952 $data["network"] = NETWORK_OSTATUS;
956 // Fetch all additional data from the feed
957 $ret = z_fetch_url($data["poll"]);
958 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
961 $feed = $ret['body'];
962 $feed_data = feed_import($feed,$dummy1,$dummy2, $dummy3, true);
966 if ($feed_data["header"]["author-name"] != "") {
967 $data["name"] = $feed_data["header"]["author-name"];
969 if ($feed_data["header"]["author-nick"] != "") {
970 $data["nick"] = $feed_data["header"]["author-nick"];
972 if ($feed_data["header"]["author-avatar"] != "") {
973 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
975 if ($feed_data["header"]["author-id"] != "") {
976 $data["alias"] = $feed_data["header"]["author-id"];
978 if ($feed_data["header"]["author-location"] != "") {
979 $data["location"] = $feed_data["header"]["author-location"];
981 if ($feed_data["header"]["author-about"] != "") {
982 $data["about"] = $feed_data["header"]["author-about"];
984 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
985 // So we take the value that we just fetched, although the other one worked as well
986 if ($feed_data["header"]["author-link"] != "") {
987 $data["url"] = $feed_data["header"]["author-link"];
989 /// @todo Fetch location and "about" from the feed as well
994 * @brief Fetch data from a pump.io profile page
996 * @param string $profile Link to the profile page
998 * @return array profile data
1000 private function pumpioProfileData($profile) {
1002 $doc = new \DOMDocument();
1003 if (!@$doc->loadHTMLFile($profile))
1006 $xpath = new \DomXPath($doc);
1010 // This is ugly - but pump.io doesn't seem to know a better way for it
1011 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1012 $pos = strpos($data["name"], chr(10));
1014 $data["name"] = trim(substr($data["name"], 0, $pos));
1016 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1018 foreach ($avatar->attributes as $attribute)
1019 if ($attribute->name == "src")
1020 $data["photo"] = trim($attribute->value);
1022 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
1023 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
1029 * @brief Check for pump.io contact
1031 * @param array $webfinger Webfinger data
1033 * @return array pump.io data
1035 private function pumpio($webfinger) {
1038 foreach ($webfinger["links"] AS $link) {
1039 if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
1040 ($link["type"] == "text/html") AND ($link["href"] != ""))
1041 $data["url"] = $link["href"];
1042 elseif (($link["rel"] == "activity-inbox") AND ($link["href"] != ""))
1043 $data["notify"] = $link["href"];
1044 elseif (($link["rel"] == "activity-outbox") AND ($link["href"] != ""))
1045 $data["poll"] = $link["href"];
1046 elseif (($link["rel"] == "dialback") AND ($link["href"] != ""))
1047 $data["dialback"] = $link["href"];
1049 if (isset($data["poll"]) AND isset($data["notify"]) AND
1050 isset($data["dialback"]) AND isset($data["url"])) {
1052 // by now we use these fields only for the network type detection
1053 // So we unset all data that isn't used at the moment
1054 unset($data["dialback"]);
1056 $data["network"] = NETWORK_PUMPIO;
1060 $profile_data = self::pumpioProfileData($data["url"]);
1065 $data = array_merge($data, $profile_data);
1071 * @brief Check page for feed link
1073 * @param string $url Page link
1075 * @return string feed link
1077 private function getFeedLink($url) {
1078 $doc = new \DOMDocument();
1080 if (!@$doc->loadHTMLFile($url))
1083 $xpath = new \DomXPath($doc);
1085 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1086 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1087 if (!is_object($feeds))
1090 if ($feeds->length == 0)
1095 foreach ($feeds AS $feed) {
1097 foreach ($feed->attributes as $attribute)
1098 $attr[$attribute->name] = trim($attribute->value);
1100 if ($feed_url == "")
1101 $feed_url = $attr["href"];
1108 * @brief Check for feed contact
1110 * @param string $url Profile link
1111 * @param boolean $probe Do a probe if the page contains a feed link
1113 * @return array feed data
1115 private function feed($url, $probe = true) {
1116 $ret = z_fetch_url($url);
1117 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1120 $feed = $ret['body'];
1121 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1127 $feed_url = self::getFeedLink($url);
1132 return self::feed($feed_url, false);
1135 if ($feed_data["header"]["author-name"] != "")
1136 $data["name"] = $feed_data["header"]["author-name"];
1138 if ($feed_data["header"]["author-nick"] != "")
1139 $data["nick"] = $feed_data["header"]["author-nick"];
1141 if ($feed_data["header"]["author-avatar"] != "")
1142 $data["photo"] = $feed_data["header"]["author-avatar"];
1144 if ($feed_data["header"]["author-id"] != "")
1145 $data["alias"] = $feed_data["header"]["author-id"];
1147 $data["url"] = $url;
1148 $data["poll"] = $url;
1150 if ($feed_data["header"]["author-link"] != "")
1151 $data["baseurl"] = $feed_data["header"]["author-link"];
1153 $data["baseurl"] = $data["url"];
1155 $data["network"] = NETWORK_FEED;
1161 * @brief Check for mail contact
1163 * @param string $uri Profile link
1164 * @param integer $uid User ID
1166 * @return array mail data
1168 private function mail($uri, $uid) {
1170 if (!validate_email($uri))
1173 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1175 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1177 if (\dbm::is_result($x) && \dbm::is_result($r)) {
1178 $mailbox = construct_mailbox_name($r[0]);
1180 openssl_private_decrypt(hex2bin($r[0]['pass']), $password,$x[0]['prvkey']);
1181 $mbox = email_connect($mailbox,$r[0]['user'], $password);
1186 $msgs = email_poll($mbox, $uri);
1187 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1194 $data["addr"] = $uri;
1195 $data["network"] = NETWORK_MAIL;
1196 $data["name"] = substr($uri, 0, strpos($uri,'@'));
1197 $data["nick"] = $data["name"];
1198 $data["photo"] = avatar_img($uri);
1200 $phost = substr($uri, strpos($uri,'@') + 1);
1201 $data["url"] = 'http://'.$phost."/".$data["nick"];
1202 $data["notify"] = 'smtp '.random_string();
1203 $data["poll"] = 'email '.random_string();
1205 $x = email_msg_meta($mbox, $msgs[0]);
1206 if(stristr($x[0]->from, $uri))
1207 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1208 elseif(stristr($x[0]->to, $uri))
1209 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1211 foreach($adr as $feadr) {
1212 if((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1213 &&(strcasecmp($feadr->host, $phost) == 0)
1214 && (strlen($feadr->personal))) {
1216 $personal = imap_mime_header_decode($feadr->personal);
1218 foreach($personal as $perspart)
1219 if ($perspart->charset != "default")
1220 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1222 $data["name"] .= $perspart->text;
1224 $data["name"] = notags($data["name"]);
1234 * @brief Mix two paths together to possibly fix missing parts
1236 * @param string $avatar Path to the avatar
1237 * @param string $base Another path that is hopefully complete
1239 * @return string fixed avatar path
1241 public static function fixAvatar($avatar, $base) {
1242 $base_parts = parse_url($base);
1244 // Remove all parts that could create a problem
1245 unset($base_parts['path']);
1246 unset($base_parts['query']);
1247 unset($base_parts['fragment']);
1249 $avatar_parts = parse_url($avatar);
1252 $parts = array_merge($base_parts, $avatar_parts);
1254 // And put them together again
1255 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1256 $host = isset($parts['host']) ? $parts['host'] : '';
1257 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1258 $path = isset($parts['path']) ? $parts['path'] : '';
1259 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1260 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1262 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1264 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);