3 * @file include/Probe.php
4 * @brief Functions for probing URL
8 use \Friendica\Core\Config;
9 use \Friendica\Core\PConfig;
11 require_once("include/feed.php");
12 require_once('include/email.php');
13 require_once('include/network.php');
16 * @brief This class contain functions for probing URL
21 private static $baseurl;
24 * @brief Rearrange the array so that it always has the same order
26 * @param array $data Unordered data
28 * @return array Ordered data
30 private function rearrange_data($data) {
31 $fields = array("name", "nick", "guid", "url", "addr", "alias",
32 "photo", "community", "keywords", "location", "about",
33 "batch", "notify", "poll", "request", "confirm", "poco",
34 "priority", "network", "pubkey", "baseurl");
37 foreach ($fields AS $field)
38 if (isset($data[$field]))
39 $newdata[$field] = $data[$field];
41 $newdata[$field] = "";
43 // We don't use the "priority" field anymore and replace it with a dummy.
44 $newdata["priority"] = 0;
50 * @brief Probes for XRD data
53 * 'lrdd' => Link to LRDD endpoint
54 * 'lrdd-xml' => Link to LRDD endpoint in XML format
55 * 'lrdd-json' => Link to LRDD endpoint in JSON format
57 private function xrd($host) {
59 // Reset the static variable
62 $ssl_url = "https://".$host."/.well-known/host-meta";
63 $url = "http://".$host."/.well-known/host-meta";
65 $xrd_timeout = Config::get('system','xrd_timeout', 20);
68 $ret = z_fetch_url($ssl_url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
69 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
74 $xrd = parse_xml_string($xml, false);
76 if (!is_object($xrd)) {
77 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
78 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
82 $xrd = parse_xml_string($xml, false);
87 $links = xml::element_to_array($xrd);
88 if (!isset($links["xrd"]["link"]))
93 foreach ($links["xrd"]["link"] AS $value => $link) {
94 if (isset($link["@attributes"]))
95 $attributes = $link["@attributes"];
96 elseif ($value == "@attributes")
101 if (($attributes["rel"] == "lrdd") AND
102 ($attributes["type"] == "application/xrd+xml"))
103 $xrd_data["lrdd-xml"] = $attributes["template"];
104 elseif (($attributes["rel"] == "lrdd") AND
105 ($attributes["type"] == "application/json"))
106 $xrd_data["lrdd-json"] = $attributes["template"];
107 elseif ($attributes["rel"] == "lrdd")
108 $xrd_data["lrdd"] = $attributes["template"];
111 self::$baseurl = "http://".$host;
117 * @brief Perform Webfinger lookup and return DFRN data
119 * Given an email style address, perform webfinger lookup and
120 * return the resulting DFRN profile URL, or if no DFRN profile URL
121 * is located, returns an OStatus subscription template (prefixed
122 * with the string 'stat:' to identify it as on OStatus template).
123 * If this isn't an email style address just return $webbie.
124 * Return an empty string if email-style addresses but webfinger fails,
125 * or if the resultant personal XRD doesn't contain a supported
126 * subscription/friend-request attribute.
128 * amended 7/9/2011 to return an hcard which could save potentially loading
129 * a lengthy content page to scrape dfrn attributes
131 * @param string $webbie Address that should be probed
132 * @param string $hcard Link to the hcard - is returned by reference
134 * @return string profile link
137 public static function webfinger_dfrn($webbie, &$hcard) {
141 $links = self::lrdd($webbie);
142 logger('webfinger_dfrn: '.$webbie.':'.print_r($links,true), LOGGER_DATA);
144 foreach ($links as $link) {
145 if ($link['@attributes']['rel'] === NAMESPACE_DFRN)
146 $profile_link = $link['@attributes']['href'];
147 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) AND ($profile_link == ""))
148 $profile_link = 'stat:'.$link['@attributes']['template'];
149 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
150 $hcard = $link['@attributes']['href'];
153 return $profile_link;
157 * @brief Check an URI for LRDD data
159 * this is a replacement for the "lrdd" function in include/network.php.
160 * It isn't used in this class and has some redundancies in the code.
161 * When time comes we can check the existing calls for "lrdd" if we can rework them.
163 * @param string $uri Address that should be probed
165 * @return array uri data
167 public static function lrdd($uri) {
169 $lrdd = self::xrd($uri);
172 $parts = @parse_url($uri);
176 $host = $parts["host"];
178 $path_parts = explode("/", trim($parts["path"], "/"));
181 $lrdd = self::xrd($host);
182 $host .= "/".array_shift($path_parts);
183 } while (!$lrdd AND (sizeof($path_parts) > 0));
189 foreach ($lrdd AS $key => $link) {
193 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json")))
196 $path = str_replace('{uri}', urlencode($uri), $link);
197 $webfinger = self::webfinger($path);
199 if (!$webfinger AND (strstr($uri, "@"))) {
200 $path = str_replace('{uri}', urlencode("acct:".$uri), $link);
201 $webfinger = self::webfinger($path);
205 if (!is_array($webfinger["links"]))
210 foreach ($webfinger["links"] AS $link)
211 $data[] = array("@attributes" => $link);
213 if (is_array($webfinger["aliases"]))
214 foreach ($webfinger["aliases"] AS $alias)
215 $data[] = array("@attributes" =>
216 array("rel" => "alias",
223 * @brief Fetch information (protocol endpoints and user information) about a given uri
225 * @param string $uri Address that should be probed
226 * @param string $network Test for this specific network
227 * @param integer $uid User ID for the probe (only used for mails)
228 * @param boolean $cache Use cached values?
230 * @return array uri data
232 public static function uri($uri, $network = "", $uid = 0, $cache = true) {
235 $result = Cache::get("probe_url:".$network.":".$uri);
236 if (!is_null($result)) {
244 $data = self::detect($uri, $network, $uid);
246 if (!isset($data["url"]))
249 if ($data["photo"] != "")
250 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
252 $data["photo"] = App::get_baseurl().'/images/person-175.jpg';
254 if (!isset($data["name"]) OR ($data["name"] == "")) {
255 if (isset($data["nick"]))
256 $data["name"] = $data["nick"];
258 if ($data["name"] == "")
259 $data["name"] = $data["url"];
262 if (!isset($data["nick"]) OR ($data["nick"] == "")) {
263 $data["nick"] = strtolower($data["name"]);
265 if (strpos($data['nick'], ' '))
266 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
269 if (self::$baseurl != "") {
270 $data["baseurl"] = self::$baseurl;
273 if (!isset($data["network"])) {
274 $data["network"] = NETWORK_PHANTOM;
277 $data = self::rearrange_data($data);
279 // Only store into the cache if the value seems to be valid
280 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
281 Cache::set("probe_url:".$network.":".$uri, $data, CACHE_DAY);
283 /// @todo temporary fix - we need a real contact update function that updates only changing fields
284 /// The biggest problem is the avatar picture that could have a reduced image size.
285 /// It should only be updated if the existing picture isn't existing anymore.
286 if (($data['network'] != NETWORK_FEED) AND ($mode == PROBE_NORMAL) AND
287 $data["name"] AND $data["nick"] AND $data["url"] AND $data["addr"] AND $data["poll"])
288 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `url` = '%s', `addr` = '%s',
289 `notify` = '%s', `poll` = '%s', `alias` = '%s', `success_update` = '%s'
290 WHERE `nurl` = '%s' AND NOT `self` AND `uid` = 0",
291 dbesc($data["name"]),
292 dbesc($data["nick"]),
294 dbesc($data["addr"]),
295 dbesc($data["notify"]),
296 dbesc($data["poll"]),
297 dbesc($data["alias"]),
298 dbesc(datetime_convert()),
299 dbesc(normalise_link($data['url']))
307 * @brief Fetch information (protocol endpoints and user information) about a given uri
309 * This function is only called by the "uri" function that adds caching and rearranging of data.
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)
315 * @return array uri data
317 private function detect($uri, $network, $uid) {
318 if (strstr($uri, '@')) {
319 // If the URI starts with "mailto:" then jump directly to the mail detection
320 if (strpos($url,'mailto:') !== false) {
321 $uri = str_replace('mailto:', '', $url);
322 return self::mail($uri, $uid);
325 if ($network == NETWORK_MAIL)
326 return self::mail($uri, $uid);
328 // Remove "acct:" from the URI
329 $uri = str_replace('acct:', '', $uri);
331 $host = substr($uri,strpos($uri, '@') + 1);
332 $nick = substr($uri,0, strpos($uri, '@'));
334 if (strpos($uri, '@twitter.com'))
335 return array("network" => NETWORK_TWITTER);
337 $lrdd = self::xrd($host);
340 return self::mail($uri, $uid);
344 $parts = parse_url($uri);
345 if (!isset($parts["scheme"]) OR
346 !isset($parts["host"]) OR
347 !isset($parts["path"]))
351 $host = $parts["host"];
353 if ($host == 'twitter.com')
354 return array("network" => NETWORK_TWITTER);
356 $lrdd = self::xrd($host);
358 $path_parts = explode("/", trim($parts["path"], "/"));
360 while (!$lrdd AND (sizeof($path_parts) > 1)) {
361 $host .= "/".array_shift($path_parts);
362 $lrdd = self::xrd($host);
365 return self::feed($uri);
367 $nick = array_pop($path_parts);
368 $addr = $nick."@".$host;
372 /// @todo Do we need the prefix "acct:" or "acct://"?
374 foreach ($lrdd AS $key => $link) {
378 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json")))
381 // Try webfinger with the address (user@domain.tld)
382 $path = str_replace('{uri}', urlencode($addr), $link);
383 $webfinger = self::webfinger($path);
385 // Mastodon needs to have it with "acct:"
387 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
388 $webfinger = self::webfinger($path);
391 // If webfinger wasn't successful then try it with the URL - possibly in the format https://...
392 if (!$webfinger AND ($uri != $addr)) {
393 $path = str_replace('{uri}', urlencode($uri), $link);
394 $webfinger = self::webfinger($path);
396 // Since the detection with the address wasn't successful, we delete it.
405 return self::feed($uri);
409 logger("Probing ".$uri, LOGGER_DEBUG);
411 if (in_array($network, array("", NETWORK_DFRN)))
412 $result = self::dfrn($webfinger);
413 if ((!$result AND ($network == "")) OR ($network == NETWORK_DIASPORA))
414 $result = self::diaspora($webfinger);
415 if ((!$result AND ($network == "")) OR ($network == NETWORK_OSTATUS))
416 $result = self::ostatus($webfinger);
417 if ((!$result AND ($network == "")) OR ($network == NETWORK_PUMPIO))
418 $result = self::pumpio($webfinger);
419 if ((!$result AND ($network == "")) OR ($network == NETWORK_FEED))
420 $result = self::feed($uri);
422 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
423 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
424 if ((!isset($result["nick"]) OR ($result["nick"] == "") OR (strstr($result["nick"], " "))) AND ($nick != ""))
425 $result["nick"] = $nick;
427 if ((!isset($result["addr"]) OR ($result["addr"] == "")) AND ($addr != ""))
428 $result["addr"] = $addr;
431 logger($uri." is ".$result["network"], LOGGER_DEBUG);
433 if (!isset($result["baseurl"]) OR ($result["baseurl"] == "")) {
434 $pos = strpos($result["url"], $host);
436 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
443 * @brief Perform a webfinger request.
445 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
447 * @param string $url Address that should be probed
449 * @return array webfinger data
451 private function webfinger($url) {
453 $xrd_timeout = Config::get('system','xrd_timeout', 20);
456 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
457 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
460 $data = $ret['body'];
462 $xrd = parse_xml_string($data, false);
464 if (!is_object($xrd)) {
465 // If it is not XML, maybe it is JSON
466 $webfinger = json_decode($data, true);
468 if (!isset($webfinger["links"]))
474 $xrd_arr = xml::element_to_array($xrd);
475 if (!isset($xrd_arr["xrd"]["link"]))
478 $webfinger = array();
480 if (isset($xrd_arr["xrd"]["subject"]))
481 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
483 if (isset($xrd_arr["xrd"]["alias"]))
484 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
486 $webfinger["links"] = array();
488 foreach ($xrd_arr["xrd"]["link"] AS $value => $data) {
489 if (isset($data["@attributes"]))
490 $attributes = $data["@attributes"];
491 elseif ($value == "@attributes")
496 $webfinger["links"][] = $attributes;
502 * @brief Poll the Friendica specific noscrape page.
504 * "noscrape" is a faster alternative to fetch the data from the hcard.
505 * This functionality was originally created for the directory.
507 * @param string $noscrape Link to the noscrape page
508 * @param array $data The already fetched data
510 * @return array noscrape data
512 private function poll_noscrape($noscrape, $data) {
513 $ret = z_fetch_url($noscrape);
514 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
517 $content = $ret['body'];
522 $json = json_decode($content, true);
523 if (!is_array($json))
526 if (isset($json["fn"]))
527 $data["name"] = $json["fn"];
529 if (isset($json["addr"]))
530 $data["addr"] = $json["addr"];
532 if (isset($json["nick"]))
533 $data["nick"] = $json["nick"];
535 if (isset($json["comm"]))
536 $data["community"] = $json["comm"];
538 if (isset($json["tags"])) {
539 $keywords = implode(" ", $json["tags"]);
541 $data["keywords"] = $keywords;
544 $location = formatted_location($json);
546 $data["location"] = $location;
548 if (isset($json["about"]))
549 $data["about"] = $json["about"];
551 if (isset($json["key"]))
552 $data["pubkey"] = $json["key"];
554 if (isset($json["photo"]))
555 $data["photo"] = $json["photo"];
557 if (isset($json["dfrn-request"]))
558 $data["request"] = $json["dfrn-request"];
560 if (isset($json["dfrn-confirm"]))
561 $data["confirm"] = $json["dfrn-confirm"];
563 if (isset($json["dfrn-notify"]))
564 $data["notify"] = $json["dfrn-notify"];
566 if (isset($json["dfrn-poll"]))
567 $data["poll"] = $json["dfrn-poll"];
573 * @brief Check for valid DFRN data
575 * @param array $data DFRN data
577 * @return int Number of errors
579 public static function valid_dfrn($data) {
581 if(!isset($data['key']))
583 if(!isset($data['dfrn-request']))
585 if(!isset($data['dfrn-confirm']))
587 if(!isset($data['dfrn-notify']))
589 if(!isset($data['dfrn-poll']))
595 * @brief Fetch data from a DFRN profile page and via "noscrape"
597 * @param string $profile Link to the profile page
599 * @return array profile data
601 public static function profile($profile) {
605 logger("Check profile ".$profile, LOGGER_DEBUG);
607 // Fetch data via noscrape - this is faster
608 $noscrape = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile);
609 $data = self::poll_noscrape($noscrape, $data);
611 if (!isset($data["notify"]) OR !isset($data["confirm"]) OR
612 !isset($data["request"]) OR !isset($data["poll"]) OR
613 !isset($data["poco"]) OR !isset($data["name"]) OR
614 !isset($data["photo"]))
615 $data = self::poll_hcard($profile, $data, true);
617 $prof_data = array();
618 $prof_data["addr"] = $data["addr"];
619 $prof_data["nick"] = $data["nick"];
620 $prof_data["dfrn-request"] = $data["request"];
621 $prof_data["dfrn-confirm"] = $data["confirm"];
622 $prof_data["dfrn-notify"] = $data["notify"];
623 $prof_data["dfrn-poll"] = $data["poll"];
624 $prof_data["dfrn-poco"] = $data["poco"];
625 $prof_data["photo"] = $data["photo"];
626 $prof_data["fn"] = $data["name"];
627 $prof_data["key"] = $data["pubkey"];
629 logger("Result for profile ".$profile.": ".print_r($prof_data, true), LOGGER_DEBUG);
635 * @brief Check for DFRN contact
637 * @param array $webfinger Webfinger data
639 * @return array DFRN data
641 private function dfrn($webfinger) {
645 foreach ($webfinger["links"] AS $link) {
646 if (($link["rel"] == NAMESPACE_DFRN) AND ($link["href"] != ""))
647 $data["network"] = NETWORK_DFRN;
648 elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
649 $data["poll"] = $link["href"];
650 elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
651 ($link["type"] == "text/html") AND ($link["href"] != ""))
652 $data["url"] = $link["href"];
653 elseif (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != ""))
654 $hcard = $link["href"];
655 elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != ""))
656 $data["poco"] = $link["href"];
657 elseif (($link["rel"] == "http://webfinger.net/rel/avatar") AND ($link["href"] != ""))
658 $data["photo"] = $link["href"];
660 elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != ""))
661 $data["baseurl"] = trim($link["href"], '/');
662 elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != ""))
663 $data["guid"] = $link["href"];
664 elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
665 $data["pubkey"] = base64_decode($link["href"]);
667 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
668 if (strstr($data["pubkey"], 'RSA '))
669 $data["pubkey"] = rsatopem($data["pubkey"]);
673 if (!isset($data["network"]) OR ($hcard == ""))
676 // Fetch data via noscrape - this is faster
677 $noscrape = str_replace("/hcard/", "/noscrape/", $hcard);
678 $data = self::poll_noscrape($noscrape, $data);
680 if (isset($data["notify"]) AND isset($data["confirm"]) AND isset($data["request"]) AND
681 isset($data["poll"]) AND isset($data["name"]) AND isset($data["photo"]))
684 $data = self::poll_hcard($hcard, $data, true);
690 * @brief Poll the hcard page (Diaspora and Friendica specific)
692 * @param string $hcard Link to the hcard page
693 * @param array $data The already fetched data
694 * @param boolean $dfrn Poll DFRN specific data
696 * @return array hcard data
698 private function poll_hcard($hcard, $data, $dfrn = false) {
699 $ret = z_fetch_url($hcard);
700 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
703 $content = $ret['body'];
708 $doc = new DOMDocument();
709 if (!@$doc->loadHTML($content))
712 $xpath = new DomXPath($doc);
714 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
715 if (!is_object($vcards))
718 if ($vcards->length > 0) {
719 $vcard = $vcards->item(0);
721 // We have to discard the guid from the hcard in favour of the guid from lrdd
722 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
723 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
724 if (($search->length > 0) AND ($data["guid"] == ""))
725 $data["guid"] = $search->item(0)->nodeValue;
727 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
728 if ($search->length > 0)
729 $data["nick"] = $search->item(0)->nodeValue;
731 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
732 if ($search->length > 0)
733 $data["name"] = $search->item(0)->nodeValue;
735 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
736 if ($search->length > 0)
737 $data["searchable"] = $search->item(0)->nodeValue;
739 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
740 if ($search->length > 0) {
741 $data["pubkey"] = $search->item(0)->nodeValue;
742 if (strstr($data["pubkey"], 'RSA '))
743 $data["pubkey"] = rsatopem($data["pubkey"]);
746 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
747 if ($search->length > 0)
748 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
752 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
753 foreach ($photos AS $photo) {
755 foreach ($photo->attributes as $attribute) {
756 $attr[$attribute->name] = trim($attribute->value);
759 if (isset($attr["src"]) AND isset($attr["width"])) {
760 $avatar[$attr["width"]] = $attr["src"];
763 // We don't have a width. So we just take everything that we got.
764 // This is a Hubzilla workaround which doesn't send a width.
765 if ((sizeof($avatar) == 0) AND isset($attr["src"])) {
766 $avatar[] = $attr["src"];
770 if (sizeof($avatar)) {
772 $data["photo"] = array_pop($avatar);
776 // Poll DFRN specific data
777 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
778 if ($search->length > 0) {
779 foreach ($search AS $link) {
780 //$data["request"] = $search->item(0)->nodeValue;
782 foreach ($link->attributes as $attribute)
783 $attr[$attribute->name] = trim($attribute->value);
785 $data[substr($attr["rel"], 5)] = $attr["href"];
789 // Older Friendica versions had used the "uid" field differently than newer versions
790 if ($data["nick"] == $data["guid"])
791 unset($data["guid"]);
799 * @brief Check for Diaspora contact
801 * @param array $webfinger Webfinger data
803 * @return array Diaspora data
805 private function diaspora($webfinger) {
809 foreach ($webfinger["links"] AS $link) {
810 if (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != ""))
811 $hcard = $link["href"];
812 elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != ""))
813 $data["baseurl"] = trim($link["href"], '/');
814 elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != ""))
815 $data["guid"] = $link["href"];
816 elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
817 ($link["type"] == "text/html") AND ($link["href"] != ""))
818 $data["url"] = $link["href"];
819 elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
820 $data["poll"] = $link["href"];
821 elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != ""))
822 $data["poco"] = $link["href"];
823 elseif (($link["rel"] == "salmon") AND ($link["href"] != ""))
824 $data["notify"] = $link["href"];
825 elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
826 $data["pubkey"] = base64_decode($link["href"]);
828 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
829 if (strstr($data["pubkey"], 'RSA '))
830 $data["pubkey"] = rsatopem($data["pubkey"]);
834 if (!isset($data["url"]) OR ($hcard == ""))
837 if (is_array($webfinger["aliases"]))
838 foreach ($webfinger["aliases"] AS $alias)
839 if (normalise_link($alias) != normalise_link($data["url"]) AND !strstr($alias, "@"))
840 $data["alias"] = $alias;
842 // Fetch further information from the hcard
843 $data = self::poll_hcard($hcard, $data);
848 if (isset($data["url"]) AND isset($data["guid"]) AND isset($data["baseurl"]) AND
849 isset($data["pubkey"]) AND ($hcard != "")) {
850 $data["network"] = NETWORK_DIASPORA;
852 // The Diaspora handle must always be lowercase
853 $data["addr"] = strtolower($data["addr"]);
855 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
856 $data["notify"] = $data["baseurl"]."/receive/users/".$data["guid"];
857 $data["batch"] = $data["baseurl"]."/receive/public";
865 * @brief Check for OStatus contact
867 * @param array $webfinger Webfinger data
869 * @return array OStatus data
871 private function ostatus($webfinger) {
874 if (is_array($webfinger["aliases"]))
875 foreach($webfinger["aliases"] AS $alias)
876 if (strstr($alias, "@"))
877 $data["addr"] = str_replace('acct:', '', $alias);
879 if (is_string($webfinger["subject"]) AND strstr($webfinger["subject"], "@"))
880 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
883 foreach ($webfinger["links"] AS $link) {
884 if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
885 ($link["type"] == "text/html") AND ($link["href"] != ""))
886 $data["url"] = $link["href"];
887 elseif (($link["rel"] == "salmon") AND ($link["href"] != ""))
888 $data["notify"] = $link["href"];
889 elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
890 $data["poll"] = $link["href"];
891 elseif (($link["rel"] == "magic-public-key") AND ($link["href"] != "")) {
892 $pubkey = $link["href"];
894 if (substr($pubkey, 0, 5) === 'data:') {
895 if (strstr($pubkey, ','))
896 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
898 $pubkey = substr($pubkey, 5);
899 } elseif (normalise_link($pubkey) == 'http://') {
900 $ret = z_fetch_url($pubkey);
901 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
904 $pubkey = $ret['body'];
907 $key = explode(".", $pubkey);
909 if (sizeof($key) >= 3) {
910 $m = base64url_decode($key[1]);
911 $e = base64url_decode($key[2]);
912 $data["pubkey"] = metopem($m,$e);
918 if (isset($data["notify"]) AND isset($data["pubkey"]) AND
919 isset($data["poll"]) AND isset($data["url"])) {
920 $data["network"] = NETWORK_OSTATUS;
924 // Fetch all additional data from the feed
925 $ret = z_fetch_url($data["poll"]);
926 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
929 $feed = $ret['body'];
930 $feed_data = feed_import($feed,$dummy1,$dummy2, $dummy3, true);
934 if ($feed_data["header"]["author-name"] != "")
935 $data["name"] = $feed_data["header"]["author-name"];
937 if ($feed_data["header"]["author-nick"] != "")
938 $data["nick"] = $feed_data["header"]["author-nick"];
940 if ($feed_data["header"]["author-avatar"] != "")
941 $data["photo"] = $feed_data["header"]["author-avatar"];
943 if ($feed_data["header"]["author-id"] != "")
944 $data["alias"] = $feed_data["header"]["author-id"];
946 if ($feed_data["header"]["author-location"] != "")
947 $data["location"] = $feed_data["header"]["author-location"];
949 if ($feed_data["header"]["author-about"] != "")
950 $data["about"] = $feed_data["header"]["author-about"];
952 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
953 // So we take the value that we just fetched, although the other one worked as well
954 if ($feed_data["header"]["author-link"] != "")
955 $data["url"] = $feed_data["header"]["author-link"];
957 /// @todo Fetch location and "about" from the feed as well
962 * @brief Fetch data from a pump.io profile page
964 * @param string $profile Link to the profile page
966 * @return array profile data
968 private function pumpio_profile_data($profile) {
970 $doc = new DOMDocument();
971 if (!@$doc->loadHTMLFile($profile))
974 $xpath = new DomXPath($doc);
978 // This is ugly - but pump.io doesn't seem to know a better way for it
979 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
980 $pos = strpos($data["name"], chr(10));
982 $data["name"] = trim(substr($data["name"], 0, $pos));
984 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
986 foreach ($avatar->attributes as $attribute)
987 if ($attribute->name == "src")
988 $data["photo"] = trim($attribute->value);
990 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
991 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
997 * @brief Check for pump.io contact
999 * @param array $webfinger Webfinger data
1001 * @return array pump.io data
1003 private function pumpio($webfinger) {
1006 foreach ($webfinger["links"] AS $link) {
1007 if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
1008 ($link["type"] == "text/html") AND ($link["href"] != ""))
1009 $data["url"] = $link["href"];
1010 elseif (($link["rel"] == "activity-inbox") AND ($link["href"] != ""))
1011 $data["notify"] = $link["href"];
1012 elseif (($link["rel"] == "activity-outbox") AND ($link["href"] != ""))
1013 $data["poll"] = $link["href"];
1014 elseif (($link["rel"] == "dialback") AND ($link["href"] != ""))
1015 $data["dialback"] = $link["href"];
1017 if (isset($data["poll"]) AND isset($data["notify"]) AND
1018 isset($data["dialback"]) AND isset($data["url"])) {
1020 // by now we use these fields only for the network type detection
1021 // So we unset all data that isn't used at the moment
1022 unset($data["dialback"]);
1024 $data["network"] = NETWORK_PUMPIO;
1028 $profile_data = self::pumpio_profile_data($data["url"]);
1033 $data = array_merge($data, $profile_data);
1039 * @brief Check page for feed link
1041 * @param string $url Page link
1043 * @return string feed link
1045 private function get_feed_link($url) {
1046 $doc = new DOMDocument();
1048 if (!@$doc->loadHTMLFile($url))
1051 $xpath = new DomXPath($doc);
1053 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1054 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1055 if (!is_object($feeds))
1058 if ($feeds->length == 0)
1063 foreach ($feeds AS $feed) {
1065 foreach ($feed->attributes as $attribute)
1066 $attr[$attribute->name] = trim($attribute->value);
1068 if ($feed_url == "")
1069 $feed_url = $attr["href"];
1076 * @brief Check for feed contact
1078 * @param string $url Profile link
1079 * @param boolean $probe Do a probe if the page contains a feed link
1081 * @return array feed data
1083 private function feed($url, $probe = true) {
1084 $ret = z_fetch_url($url);
1085 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1088 $feed = $ret['body'];
1089 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1095 $feed_url = self::get_feed_link($url);
1100 return self::feed($feed_url, false);
1103 if ($feed_data["header"]["author-name"] != "")
1104 $data["name"] = $feed_data["header"]["author-name"];
1106 if ($feed_data["header"]["author-nick"] != "")
1107 $data["nick"] = $feed_data["header"]["author-nick"];
1109 if ($feed_data["header"]["author-avatar"] != "")
1110 $data["photo"] = $feed_data["header"]["author-avatar"];
1112 if ($feed_data["header"]["author-id"] != "")
1113 $data["alias"] = $feed_data["header"]["author-id"];
1115 $data["url"] = $url;
1116 $data["poll"] = $url;
1118 if ($feed_data["header"]["author-link"] != "")
1119 $data["baseurl"] = $feed_data["header"]["author-link"];
1121 $data["baseurl"] = $data["url"];
1123 $data["network"] = NETWORK_FEED;
1129 * @brief Check for mail contact
1131 * @param string $uri Profile link
1132 * @param integer $uid User ID
1134 * @return array mail data
1136 private function mail($uri, $uid) {
1138 if (!validate_email($uri))
1141 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1143 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1145 if (dbm::is_result($x) && dbm::is_result($r)) {
1146 $mailbox = construct_mailbox_name($r[0]);
1148 openssl_private_decrypt(hex2bin($r[0]['pass']), $password,$x[0]['prvkey']);
1149 $mbox = email_connect($mailbox,$r[0]['user'], $password);
1154 $msgs = email_poll($mbox, $uri);
1155 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1162 $data["addr"] = $uri;
1163 $data["network"] = NETWORK_MAIL;
1164 $data["name"] = substr($uri, 0, strpos($uri,'@'));
1165 $data["nick"] = $data["name"];
1166 $data["photo"] = avatar_img($uri);
1168 $phost = substr($uri, strpos($uri,'@') + 1);
1169 $data["url"] = 'http://'.$phost."/".$data["nick"];
1170 $data["notify"] = 'smtp '.random_string();
1171 $data["poll"] = 'email '.random_string();
1173 $x = email_msg_meta($mbox, $msgs[0]);
1174 if(stristr($x[0]->from, $uri))
1175 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1176 elseif(stristr($x[0]->to, $uri))
1177 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1179 foreach($adr as $feadr) {
1180 if((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1181 &&(strcasecmp($feadr->host, $phost) == 0)
1182 && (strlen($feadr->personal))) {
1184 $personal = imap_mime_header_decode($feadr->personal);
1186 foreach($personal as $perspart)
1187 if ($perspart->charset != "default")
1188 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1190 $data["name"] .= $perspart->text;
1192 $data["name"] = notags($data["name"]);