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 $ssl_url = "https://".$host."/.well-known/host-meta";
60 $url = "http://".$host."/.well-known/host-meta";
62 $baseurl = "http://".$host;
64 $xrd_timeout = Config::get('system','xrd_timeout', 20);
67 $ret = z_fetch_url($ssl_url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
68 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
73 $xrd = parse_xml_string($xml, false);
75 if (!is_object($xrd)) {
76 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
77 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
81 $xrd = parse_xml_string($xml, false);
86 $links = xml::element_to_array($xrd);
87 if (!isset($links["xrd"]["link"]))
92 foreach ($links["xrd"]["link"] AS $value => $link) {
93 if (isset($link["@attributes"]))
94 $attributes = $link["@attributes"];
95 elseif ($value == "@attributes")
100 if (($attributes["rel"] == "lrdd") AND
101 ($attributes["type"] == "application/xrd+xml"))
102 $xrd_data["lrdd-xml"] = $attributes["template"];
103 elseif (($attributes["rel"] == "lrdd") AND
104 ($attributes["type"] == "application/json"))
105 $xrd_data["lrdd-json"] = $attributes["template"];
106 elseif ($attributes["rel"] == "lrdd")
107 $xrd_data["lrdd"] = $attributes["template"];
110 self::$baseurl = $baseurl;
116 * @brief Perform Webfinger lookup and return DFRN data
118 * Given an email style address, perform webfinger lookup and
119 * return the resulting DFRN profile URL, or if no DFRN profile URL
120 * is located, returns an OStatus subscription template (prefixed
121 * with the string 'stat:' to identify it as on OStatus template).
122 * If this isn't an email style address just return $webbie.
123 * Return an empty string if email-style addresses but webfinger fails,
124 * or if the resultant personal XRD doesn't contain a supported
125 * subscription/friend-request attribute.
127 * amended 7/9/2011 to return an hcard which could save potentially loading
128 * a lengthy content page to scrape dfrn attributes
130 * @param string $webbie Address that should be probed
131 * @param string $hcard Link to the hcard - is returned by reference
133 * @return string profile link
136 public static function webfinger_dfrn($webbie, &$hcard) {
140 $links = self::lrdd($webbie);
141 logger('webfinger_dfrn: '.$webbie.':'.print_r($links,true), LOGGER_DATA);
143 foreach ($links as $link) {
144 if ($link['@attributes']['rel'] === NAMESPACE_DFRN)
145 $profile_link = $link['@attributes']['href'];
146 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) AND ($profile_link == ""))
147 $profile_link = 'stat:'.$link['@attributes']['template'];
148 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
149 $hcard = $link['@attributes']['href'];
152 return $profile_link;
156 * @brief Check an URI for LRDD data
158 * this is a replacement for the "lrdd" function in include/network.php.
159 * It isn't used in this class and has some redundancies in the code.
160 * When time comes we can check the existing calls for "lrdd" if we can rework them.
162 * @param string $uri Address that should be probed
164 * @return array uri data
166 public static function lrdd($uri) {
168 $lrdd = self::xrd($uri);
171 $parts = @parse_url($uri);
175 $host = $parts["host"];
177 $path_parts = explode("/", trim($parts["path"], "/"));
180 $lrdd = self::xrd($host);
181 $host .= "/".array_shift($path_parts);
182 } while (!$lrdd AND (sizeof($path_parts) > 0));
188 foreach ($lrdd AS $key => $link) {
192 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json")))
195 $path = str_replace('{uri}', urlencode($uri), $link);
196 $webfinger = self::webfinger($path);
198 if (!$webfinger AND (strstr($uri, "@"))) {
199 $path = str_replace('{uri}', urlencode("acct:".$uri), $link);
200 $webfinger = self::webfinger($path);
204 if (!is_array($webfinger["links"]))
209 foreach ($webfinger["links"] AS $link)
210 $data[] = array("@attributes" => $link);
212 if (is_array($webfinger["aliases"]))
213 foreach ($webfinger["aliases"] AS $alias)
214 $data[] = array("@attributes" =>
215 array("rel" => "alias",
222 * @brief Fetch information (protocol endpoints and user information) about a given uri
224 * @param string $uri Address that should be probed
225 * @param string $network Test for this specific network
226 * @param integer $uid User ID for the probe (only used for mails)
227 * @param boolean $cache Use cached values?
229 * @return array uri data
231 public static function uri($uri, $network = "", $uid = 0, $cache = true) {
234 $result = Cache::get("probe_url:".$network.":".$uri);
235 if (!is_null($result)) {
243 $data = self::detect($uri, $network, $uid);
245 if (!isset($data["url"]))
248 if ($data["photo"] != "")
249 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
251 $data["photo"] = App::get_baseurl().'/images/person-175.jpg';
253 if (!isset($data["name"]) OR ($data["name"] == "")) {
254 if (isset($data["nick"]))
255 $data["name"] = $data["nick"];
257 if ($data["name"] == "")
258 $data["name"] = $data["url"];
261 if (!isset($data["nick"]) OR ($data["nick"] == "")) {
262 $data["nick"] = strtolower($data["name"]);
264 if (strpos($data['nick'], ' '))
265 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
268 if (self::$baseurl != "") {
269 $data["baseurl"] = self::$baseurl;
272 if (!isset($data["network"])) {
273 $data["network"] = NETWORK_PHANTOM;
276 $data = self::rearrange_data($data);
278 // Only store into the cache if the value seems to be valid
279 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
280 Cache::set("probe_url:".$network.":".$uri, $data, CACHE_DAY);
282 /// @todo temporary fix - we need a real contact update function that updates only changing fields
283 /// The biggest problem is the avatar picture that could have a reduced image size.
284 /// It should only be updated if the existing picture isn't existing anymore.
285 if (($data['network'] != NETWORK_FEED) AND ($mode == PROBE_NORMAL) AND
286 $data["name"] AND $data["nick"] AND $data["url"] AND $data["addr"] AND $data["poll"])
287 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `url` = '%s', `addr` = '%s',
288 `notify` = '%s', `poll` = '%s', `alias` = '%s', `success_update` = '%s'
289 WHERE `nurl` = '%s' AND NOT `self` AND `uid` = 0",
290 dbesc($data["name"]),
291 dbesc($data["nick"]),
293 dbesc($data["addr"]),
294 dbesc($data["notify"]),
295 dbesc($data["poll"]),
296 dbesc($data["alias"]),
297 dbesc(datetime_convert()),
298 dbesc(normalise_link($data['url']))
306 * @brief Fetch information (protocol endpoints and user information) about a given uri
308 * This function is only called by the "uri" function that adds caching and rearranging of data.
310 * @param string $uri Address that should be probed
311 * @param string $network Test for this specific network
312 * @param integer $uid User ID for the probe (only used for mails)
314 * @return array uri data
316 private function detect($uri, $network, $uid) {
317 if (strstr($uri, '@')) {
318 // If the URI starts with "mailto:" then jump directly to the mail detection
319 if (strpos($url,'mailto:') !== false) {
320 $uri = str_replace('mailto:', '', $url);
321 return self::mail($uri, $uid);
324 if ($network == NETWORK_MAIL)
325 return self::mail($uri, $uid);
327 // Remove "acct:" from the URI
328 $uri = str_replace('acct:', '', $uri);
330 $host = substr($uri,strpos($uri, '@') + 1);
331 $nick = substr($uri,0, strpos($uri, '@'));
333 if (strpos($uri, '@twitter.com'))
334 return array("network" => NETWORK_TWITTER);
336 $lrdd = self::xrd($host);
339 return self::mail($uri, $uid);
343 $parts = parse_url($uri);
344 if (!isset($parts["scheme"]) OR
345 !isset($parts["host"]) OR
346 !isset($parts["path"]))
350 $host = $parts["host"];
352 if ($host == 'twitter.com')
353 return array("network" => NETWORK_TWITTER);
355 $lrdd = self::xrd($host);
357 $path_parts = explode("/", trim($parts["path"], "/"));
359 while (!$lrdd AND (sizeof($path_parts) > 1)) {
360 $host .= "/".array_shift($path_parts);
361 $lrdd = self::xrd($host);
364 return self::feed($uri);
366 $nick = array_pop($path_parts);
367 $addr = $nick."@".$host;
371 /// @todo Do we need the prefix "acct:" or "acct://"?
373 foreach ($lrdd AS $key => $link) {
377 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json")))
380 // Try webfinger with the address (user@domain.tld)
381 $path = str_replace('{uri}', urlencode($addr), $link);
382 $webfinger = self::webfinger($path);
384 // Mastodon needs to have it with "acct:"
386 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
387 $webfinger = self::webfinger($path);
390 // If webfinger wasn't successful then try it with the URL - possibly in the format https://...
391 if (!$webfinger AND ($uri != $addr)) {
392 $path = str_replace('{uri}', urlencode($uri), $link);
393 $webfinger = self::webfinger($path);
395 // Since the detection with the address wasn't successful, we delete it.
404 return self::feed($uri);
408 logger("Probing ".$uri, LOGGER_DEBUG);
410 if (in_array($network, array("", NETWORK_DFRN)))
411 $result = self::dfrn($webfinger);
412 if ((!$result AND ($network == "")) OR ($network == NETWORK_DIASPORA))
413 $result = self::diaspora($webfinger);
414 if ((!$result AND ($network == "")) OR ($network == NETWORK_OSTATUS))
415 $result = self::ostatus($webfinger);
416 if ((!$result AND ($network == "")) OR ($network == NETWORK_PUMPIO))
417 $result = self::pumpio($webfinger);
418 if ((!$result AND ($network == "")) OR ($network == NETWORK_FEED))
419 $result = self::feed($uri);
421 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
422 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
423 if ((!isset($result["nick"]) OR ($result["nick"] == "") OR (strstr($result["nick"], " "))) AND ($nick != ""))
424 $result["nick"] = $nick;
426 if ((!isset($result["addr"]) OR ($result["addr"] == "")) AND ($addr != ""))
427 $result["addr"] = $addr;
430 logger($uri." is ".$result["network"], LOGGER_DEBUG);
432 if (!isset($result["baseurl"]) OR ($result["baseurl"] == "")) {
433 $pos = strpos($result["url"], $host);
435 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
442 * @brief Perform a webfinger request.
444 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
446 * @param string $url Address that should be probed
448 * @return array webfinger data
450 private function webfinger($url) {
452 $xrd_timeout = Config::get('system','xrd_timeout', 20);
455 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
456 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
459 $data = $ret['body'];
461 $xrd = parse_xml_string($data, false);
463 if (!is_object($xrd)) {
464 // If it is not XML, maybe it is JSON
465 $webfinger = json_decode($data, true);
467 if (!isset($webfinger["links"]))
473 $xrd_arr = xml::element_to_array($xrd);
474 if (!isset($xrd_arr["xrd"]["link"]))
477 $webfinger = array();
479 if (isset($xrd_arr["xrd"]["subject"]))
480 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
482 if (isset($xrd_arr["xrd"]["alias"]))
483 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
485 $webfinger["links"] = array();
487 foreach ($xrd_arr["xrd"]["link"] AS $value => $data) {
488 if (isset($data["@attributes"]))
489 $attributes = $data["@attributes"];
490 elseif ($value == "@attributes")
495 $webfinger["links"][] = $attributes;
501 * @brief Poll the Friendica specific noscrape page.
503 * "noscrape" is a faster alternative to fetch the data from the hcard.
504 * This functionality was originally created for the directory.
506 * @param string $noscrape Link to the noscrape page
507 * @param array $data The already fetched data
509 * @return array noscrape data
511 private function poll_noscrape($noscrape, $data) {
512 $ret = z_fetch_url($noscrape);
513 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
516 $content = $ret['body'];
521 $json = json_decode($content, true);
522 if (!is_array($json))
525 if (isset($json["fn"]))
526 $data["name"] = $json["fn"];
528 if (isset($json["addr"]))
529 $data["addr"] = $json["addr"];
531 if (isset($json["nick"]))
532 $data["nick"] = $json["nick"];
534 if (isset($json["comm"]))
535 $data["community"] = $json["comm"];
537 if (isset($json["tags"])) {
538 $keywords = implode(" ", $json["tags"]);
540 $data["keywords"] = $keywords;
543 $location = formatted_location($json);
545 $data["location"] = $location;
547 if (isset($json["about"]))
548 $data["about"] = $json["about"];
550 if (isset($json["key"]))
551 $data["pubkey"] = $json["key"];
553 if (isset($json["photo"]))
554 $data["photo"] = $json["photo"];
556 if (isset($json["dfrn-request"]))
557 $data["request"] = $json["dfrn-request"];
559 if (isset($json["dfrn-confirm"]))
560 $data["confirm"] = $json["dfrn-confirm"];
562 if (isset($json["dfrn-notify"]))
563 $data["notify"] = $json["dfrn-notify"];
565 if (isset($json["dfrn-poll"]))
566 $data["poll"] = $json["dfrn-poll"];
572 * @brief Check for valid DFRN data
574 * @param array $data DFRN data
576 * @return int Number of errors
578 public static function valid_dfrn($data) {
580 if(!isset($data['key']))
582 if(!isset($data['dfrn-request']))
584 if(!isset($data['dfrn-confirm']))
586 if(!isset($data['dfrn-notify']))
588 if(!isset($data['dfrn-poll']))
594 * @brief Fetch data from a DFRN profile page and via "noscrape"
596 * @param string $profile Link to the profile page
598 * @return array profile data
600 public static function profile($profile) {
604 logger("Check profile ".$profile, LOGGER_DEBUG);
606 // Fetch data via noscrape - this is faster
607 $noscrape = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile);
608 $data = self::poll_noscrape($noscrape, $data);
610 if (!isset($data["notify"]) OR !isset($data["confirm"]) OR
611 !isset($data["request"]) OR !isset($data["poll"]) OR
612 !isset($data["poco"]) OR !isset($data["name"]) OR
613 !isset($data["photo"]))
614 $data = self::poll_hcard($profile, $data, true);
616 $prof_data = array();
617 $prof_data["addr"] = $data["addr"];
618 $prof_data["nick"] = $data["nick"];
619 $prof_data["dfrn-request"] = $data["request"];
620 $prof_data["dfrn-confirm"] = $data["confirm"];
621 $prof_data["dfrn-notify"] = $data["notify"];
622 $prof_data["dfrn-poll"] = $data["poll"];
623 $prof_data["dfrn-poco"] = $data["poco"];
624 $prof_data["photo"] = $data["photo"];
625 $prof_data["fn"] = $data["name"];
626 $prof_data["key"] = $data["pubkey"];
628 logger("Result for profile ".$profile.": ".print_r($prof_data, true), LOGGER_DEBUG);
634 * @brief Check for DFRN contact
636 * @param array $webfinger Webfinger data
638 * @return array DFRN data
640 private function dfrn($webfinger) {
644 foreach ($webfinger["links"] AS $link) {
645 if (($link["rel"] == NAMESPACE_DFRN) AND ($link["href"] != ""))
646 $data["network"] = NETWORK_DFRN;
647 elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
648 $data["poll"] = $link["href"];
649 elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
650 ($link["type"] == "text/html") AND ($link["href"] != ""))
651 $data["url"] = $link["href"];
652 elseif (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != ""))
653 $hcard = $link["href"];
654 elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != ""))
655 $data["poco"] = $link["href"];
656 elseif (($link["rel"] == "http://webfinger.net/rel/avatar") AND ($link["href"] != ""))
657 $data["photo"] = $link["href"];
659 elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != ""))
660 $data["baseurl"] = trim($link["href"], '/');
661 elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != ""))
662 $data["guid"] = $link["href"];
663 elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
664 $data["pubkey"] = base64_decode($link["href"]);
666 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
667 if (strstr($data["pubkey"], 'RSA '))
668 $data["pubkey"] = rsatopem($data["pubkey"]);
672 if (!isset($data["network"]) OR ($hcard == ""))
675 // Fetch data via noscrape - this is faster
676 $noscrape = str_replace("/hcard/", "/noscrape/", $hcard);
677 $data = self::poll_noscrape($noscrape, $data);
679 if (isset($data["notify"]) AND isset($data["confirm"]) AND isset($data["request"]) AND
680 isset($data["poll"]) AND isset($data["name"]) AND isset($data["photo"]))
683 $data = self::poll_hcard($hcard, $data, true);
689 * @brief Poll the hcard page (Diaspora and Friendica specific)
691 * @param string $hcard Link to the hcard page
692 * @param array $data The already fetched data
693 * @param boolean $dfrn Poll DFRN specific data
695 * @return array hcard data
697 private function poll_hcard($hcard, $data, $dfrn = false) {
698 $ret = z_fetch_url($hcard);
699 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
702 $content = $ret['body'];
707 $doc = new DOMDocument();
708 if (!@$doc->loadHTML($content))
711 $xpath = new DomXPath($doc);
713 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
714 if (!is_object($vcards))
717 if ($vcards->length > 0) {
718 $vcard = $vcards->item(0);
720 // We have to discard the guid from the hcard in favour of the guid from lrdd
721 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
722 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
723 if (($search->length > 0) AND ($data["guid"] == ""))
724 $data["guid"] = $search->item(0)->nodeValue;
726 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
727 if ($search->length > 0)
728 $data["nick"] = $search->item(0)->nodeValue;
730 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
731 if ($search->length > 0)
732 $data["name"] = $search->item(0)->nodeValue;
734 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
735 if ($search->length > 0)
736 $data["searchable"] = $search->item(0)->nodeValue;
738 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
739 if ($search->length > 0) {
740 $data["pubkey"] = $search->item(0)->nodeValue;
741 if (strstr($data["pubkey"], 'RSA '))
742 $data["pubkey"] = rsatopem($data["pubkey"]);
745 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
746 if ($search->length > 0)
747 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
751 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
752 foreach ($photos AS $photo) {
754 foreach ($photo->attributes as $attribute) {
755 $attr[$attribute->name] = trim($attribute->value);
758 if (isset($attr["src"]) AND isset($attr["width"])) {
759 $avatar[$attr["width"]] = $attr["src"];
762 // We don't have a width. So we just take everything that we got.
763 // This is a Hubzilla workaround which doesn't send a width.
764 if ((sizeof($avatar) == 0) AND isset($attr["src"])) {
765 $avatar[] = $attr["src"];
769 if (sizeof($avatar)) {
771 $data["photo"] = array_pop($avatar);
775 // Poll DFRN specific data
776 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
777 if ($search->length > 0) {
778 foreach ($search AS $link) {
779 //$data["request"] = $search->item(0)->nodeValue;
781 foreach ($link->attributes as $attribute)
782 $attr[$attribute->name] = trim($attribute->value);
784 $data[substr($attr["rel"], 5)] = $attr["href"];
788 // Older Friendica versions had used the "uid" field differently than newer versions
789 if ($data["nick"] == $data["guid"])
790 unset($data["guid"]);
798 * @brief Check for Diaspora contact
800 * @param array $webfinger Webfinger data
802 * @return array Diaspora data
804 private function diaspora($webfinger) {
808 foreach ($webfinger["links"] AS $link) {
809 if (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != ""))
810 $hcard = $link["href"];
811 elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != ""))
812 $data["baseurl"] = trim($link["href"], '/');
813 elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != ""))
814 $data["guid"] = $link["href"];
815 elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
816 ($link["type"] == "text/html") AND ($link["href"] != ""))
817 $data["url"] = $link["href"];
818 elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
819 $data["poll"] = $link["href"];
820 elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != ""))
821 $data["poco"] = $link["href"];
822 elseif (($link["rel"] == "salmon") AND ($link["href"] != ""))
823 $data["notify"] = $link["href"];
824 elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
825 $data["pubkey"] = base64_decode($link["href"]);
827 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
828 if (strstr($data["pubkey"], 'RSA '))
829 $data["pubkey"] = rsatopem($data["pubkey"]);
833 if (!isset($data["url"]) OR ($hcard == ""))
836 if (is_array($webfinger["aliases"]))
837 foreach ($webfinger["aliases"] AS $alias)
838 if (normalise_link($alias) != normalise_link($data["url"]) AND !strstr($alias, "@"))
839 $data["alias"] = $alias;
841 // Fetch further information from the hcard
842 $data = self::poll_hcard($hcard, $data);
847 if (isset($data["url"]) AND isset($data["guid"]) AND isset($data["baseurl"]) AND
848 isset($data["pubkey"]) AND ($hcard != "")) {
849 $data["network"] = NETWORK_DIASPORA;
851 // The Diaspora handle must always be lowercase
852 $data["addr"] = strtolower($data["addr"]);
854 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
855 $data["notify"] = $data["baseurl"]."/receive/users/".$data["guid"];
856 $data["batch"] = $data["baseurl"]."/receive/public";
864 * @brief Check for OStatus contact
866 * @param array $webfinger Webfinger data
868 * @return array OStatus data
870 private function ostatus($webfinger) {
873 if (is_array($webfinger["aliases"]))
874 foreach($webfinger["aliases"] AS $alias)
875 if (strstr($alias, "@"))
876 $data["addr"] = str_replace('acct:', '', $alias);
878 if (is_string($webfinger["subject"]) AND strstr($webfinger["subject"], "@"))
879 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
882 foreach ($webfinger["links"] AS $link) {
883 if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
884 ($link["type"] == "text/html") AND ($link["href"] != ""))
885 $data["url"] = $link["href"];
886 elseif (($link["rel"] == "salmon") AND ($link["href"] != ""))
887 $data["notify"] = $link["href"];
888 elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
889 $data["poll"] = $link["href"];
890 elseif (($link["rel"] == "magic-public-key") AND ($link["href"] != "")) {
891 $pubkey = $link["href"];
893 if (substr($pubkey, 0, 5) === 'data:') {
894 if (strstr($pubkey, ','))
895 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
897 $pubkey = substr($pubkey, 5);
898 } elseif (normalise_link($pubkey) == 'http://') {
899 $ret = z_fetch_url($pubkey);
900 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
903 $pubkey = $ret['body'];
906 $key = explode(".", $pubkey);
908 if (sizeof($key) >= 3) {
909 $m = base64url_decode($key[1]);
910 $e = base64url_decode($key[2]);
911 $data["pubkey"] = metopem($m,$e);
917 if (isset($data["notify"]) AND isset($data["pubkey"]) AND
918 isset($data["poll"]) AND isset($data["url"])) {
919 $data["network"] = NETWORK_OSTATUS;
923 // Fetch all additional data from the feed
924 $ret = z_fetch_url($data["poll"]);
925 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
928 $feed = $ret['body'];
929 $feed_data = feed_import($feed,$dummy1,$dummy2, $dummy3, true);
933 if ($feed_data["header"]["author-name"] != "")
934 $data["name"] = $feed_data["header"]["author-name"];
936 if ($feed_data["header"]["author-nick"] != "")
937 $data["nick"] = $feed_data["header"]["author-nick"];
939 if ($feed_data["header"]["author-avatar"] != "")
940 $data["photo"] = $feed_data["header"]["author-avatar"];
942 if ($feed_data["header"]["author-id"] != "")
943 $data["alias"] = $feed_data["header"]["author-id"];
945 if ($feed_data["header"]["author-location"] != "")
946 $data["location"] = $feed_data["header"]["author-location"];
948 if ($feed_data["header"]["author-about"] != "")
949 $data["about"] = $feed_data["header"]["author-about"];
951 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
952 // So we take the value that we just fetched, although the other one worked as well
953 if ($feed_data["header"]["author-link"] != "")
954 $data["url"] = $feed_data["header"]["author-link"];
956 /// @todo Fetch location and "about" from the feed as well
961 * @brief Fetch data from a pump.io profile page
963 * @param string $profile Link to the profile page
965 * @return array profile data
967 private function pumpio_profile_data($profile) {
969 $doc = new DOMDocument();
970 if (!@$doc->loadHTMLFile($profile))
973 $xpath = new DomXPath($doc);
977 // This is ugly - but pump.io doesn't seem to know a better way for it
978 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
979 $pos = strpos($data["name"], chr(10));
981 $data["name"] = trim(substr($data["name"], 0, $pos));
983 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
985 foreach ($avatar->attributes as $attribute)
986 if ($attribute->name == "src")
987 $data["photo"] = trim($attribute->value);
989 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
990 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
996 * @brief Check for pump.io contact
998 * @param array $webfinger Webfinger data
1000 * @return array pump.io data
1002 private function pumpio($webfinger) {
1005 foreach ($webfinger["links"] AS $link) {
1006 if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
1007 ($link["type"] == "text/html") AND ($link["href"] != ""))
1008 $data["url"] = $link["href"];
1009 elseif (($link["rel"] == "activity-inbox") AND ($link["href"] != ""))
1010 $data["notify"] = $link["href"];
1011 elseif (($link["rel"] == "activity-outbox") AND ($link["href"] != ""))
1012 $data["poll"] = $link["href"];
1013 elseif (($link["rel"] == "dialback") AND ($link["href"] != ""))
1014 $data["dialback"] = $link["href"];
1016 if (isset($data["poll"]) AND isset($data["notify"]) AND
1017 isset($data["dialback"]) AND isset($data["url"])) {
1019 // by now we use these fields only for the network type detection
1020 // So we unset all data that isn't used at the moment
1021 unset($data["dialback"]);
1023 $data["network"] = NETWORK_PUMPIO;
1027 $profile_data = self::pumpio_profile_data($data["url"]);
1032 $data = array_merge($data, $profile_data);
1038 * @brief Check page for feed link
1040 * @param string $url Page link
1042 * @return string feed link
1044 private function get_feed_link($url) {
1045 $doc = new DOMDocument();
1047 if (!@$doc->loadHTMLFile($url))
1050 $xpath = new DomXPath($doc);
1052 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1053 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1054 if (!is_object($feeds))
1057 if ($feeds->length == 0)
1062 foreach ($feeds AS $feed) {
1064 foreach ($feed->attributes as $attribute)
1065 $attr[$attribute->name] = trim($attribute->value);
1067 if ($feed_url == "")
1068 $feed_url = $attr["href"];
1075 * @brief Check for feed contact
1077 * @param string $url Profile link
1078 * @param boolean $probe Do a probe if the page contains a feed link
1080 * @return array feed data
1082 private function feed($url, $probe = true) {
1083 $ret = z_fetch_url($url);
1084 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1087 $feed = $ret['body'];
1088 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1094 $feed_url = self::get_feed_link($url);
1099 return self::feed($feed_url, false);
1102 if ($feed_data["header"]["author-name"] != "")
1103 $data["name"] = $feed_data["header"]["author-name"];
1105 if ($feed_data["header"]["author-nick"] != "")
1106 $data["nick"] = $feed_data["header"]["author-nick"];
1108 if ($feed_data["header"]["author-avatar"] != "")
1109 $data["photo"] = $feed_data["header"]["author-avatar"];
1111 if ($feed_data["header"]["author-id"] != "")
1112 $data["alias"] = $feed_data["header"]["author-id"];
1114 $data["url"] = $url;
1115 $data["poll"] = $url;
1117 if ($feed_data["header"]["author-link"] != "")
1118 $data["baseurl"] = $feed_data["header"]["author-link"];
1120 $data["baseurl"] = $data["url"];
1122 $data["network"] = NETWORK_FEED;
1128 * @brief Check for mail contact
1130 * @param string $uri Profile link
1131 * @param integer $uid User ID
1133 * @return array mail data
1135 private function mail($uri, $uid) {
1137 if (!validate_email($uri))
1140 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1142 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1144 if (dbm::is_result($x) && dbm::is_result($r)) {
1145 $mailbox = construct_mailbox_name($r[0]);
1147 openssl_private_decrypt(hex2bin($r[0]['pass']), $password,$x[0]['prvkey']);
1148 $mbox = email_connect($mailbox,$r[0]['user'], $password);
1153 $msgs = email_poll($mbox, $uri);
1154 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1161 $data["addr"] = $uri;
1162 $data["network"] = NETWORK_MAIL;
1163 $data["name"] = substr($uri, 0, strpos($uri,'@'));
1164 $data["nick"] = $data["name"];
1165 $data["photo"] = avatar_img($uri);
1167 $phost = substr($uri, strpos($uri,'@') + 1);
1168 $data["url"] = 'http://'.$phost."/".$data["nick"];
1169 $data["notify"] = 'smtp '.random_string();
1170 $data["poll"] = 'email '.random_string();
1172 $x = email_msg_meta($mbox, $msgs[0]);
1173 if(stristr($x[0]->from, $uri))
1174 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1175 elseif(stristr($x[0]->to, $uri))
1176 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1178 foreach($adr as $feadr) {
1179 if((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1180 &&(strcasecmp($feadr->host, $phost) == 0)
1181 && (strlen($feadr->personal))) {
1183 $personal = imap_mime_header_decode($feadr->personal);
1185 foreach($personal as $perspart)
1186 if ($perspart->charset != "default")
1187 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1189 $data["name"] .= $perspart->text;
1191 $data["name"] = notags($data["name"]);