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
22 * @brief Rearrange the array so that it always has the same order
24 * @param array $data Unordered data
26 * @return array Ordered data
28 private function rearrange_data($data) {
29 $fields = array("name", "nick", "guid", "url", "addr", "alias",
30 "photo", "community", "keywords", "location", "about",
31 "batch", "notify", "poll", "request", "confirm", "poco",
32 "priority", "network", "pubkey", "baseurl");
35 foreach ($fields AS $field)
36 if (isset($data[$field]))
37 $newdata[$field] = $data[$field];
39 $newdata[$field] = "";
41 // We don't use the "priority" field anymore and replace it with a dummy.
42 $newdata["priority"] = 0;
48 * @brief Probes for XRD data
51 * 'lrdd' => Link to LRDD endpoint
52 * 'lrdd-xml' => Link to LRDD endpoint in XML format
53 * 'lrdd-json' => Link to LRDD endpoint in JSON format
55 private function xrd($host) {
57 $ssl_url = "https://".$host."/.well-known/host-meta";
58 $url = "http://".$host."/.well-known/host-meta";
60 $xrd_timeout = Config::get('system','xrd_timeout', 20);
63 $xml = fetch_url($ssl_url, false, $redirects, $xrd_timeout, "application/xrd+xml");
64 $xrd = parse_xml_string($xml, false);
66 if (!is_object($xrd)) {
67 $xml = fetch_url($url, false, $redirects, $xrd_timeout, "application/xrd+xml");
68 $xrd = parse_xml_string($xml, false);
73 $links = xml::element_to_array($xrd);
74 if (!isset($links["xrd"]["link"]))
79 foreach ($links["xrd"]["link"] AS $value => $link) {
80 if (isset($link["@attributes"]))
81 $attributes = $link["@attributes"];
82 elseif ($value == "@attributes")
87 if (($attributes["rel"] == "lrdd") AND
88 ($attributes["type"] == "application/xrd+xml"))
89 $xrd_data["lrdd-xml"] = $attributes["template"];
90 elseif (($attributes["rel"] == "lrdd") AND
91 ($attributes["type"] == "application/json"))
92 $xrd_data["lrdd-json"] = $attributes["template"];
93 elseif ($attributes["rel"] == "lrdd")
94 $xrd_data["lrdd"] = $attributes["template"];
100 * @brief Perform Webfinger lookup and return DFRN data
102 * Given an email style address, perform webfinger lookup and
103 * return the resulting DFRN profile URL, or if no DFRN profile URL
104 * is located, returns an OStatus subscription template (prefixed
105 * with the string 'stat:' to identify it as on OStatus template).
106 * If this isn't an email style address just return $webbie.
107 * Return an empty string if email-style addresses but webfinger fails,
108 * or if the resultant personal XRD doesn't contain a supported
109 * subscription/friend-request attribute.
111 * amended 7/9/2011 to return an hcard which could save potentially loading
112 * a lengthy content page to scrape dfrn attributes
114 * @param string $webbie Address that should be probed
115 * @param string $hcard Link to the hcard - is returned by reference
117 * @return string profile link
120 public static function webfinger_dfrn($webbie, &$hcard) {
121 if (!strstr($webbie, '@'))
126 $links = self::webfinger($webbie);
127 logger('webfinger_dfrn: '.$webbie.':'.print_r($links,true), LOGGER_DATA);
129 foreach ($links as $link) {
130 if ($link['@attributes']['rel'] === NAMESPACE_DFRN)
131 $profile_link = $link['@attributes']['href'];
132 if ($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
133 $profile_link = 'stat:'.$link['@attributes']['template'];
134 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
135 $hcard = $link['@attributes']['href'];
138 return $profile_link;
142 * @brief Check an URI for LRDD data
144 * this is a replacement for the "lrdd" function in include/network.php.
145 * It isn't used in this class and has some redundancies in the code.
146 * When time comes we can check the existing calls for "lrdd" if we can rework them.
148 * @param string $uri Address that should be probed
150 * @return array uri data
152 public static function lrdd($uri) {
154 $lrdd = self::xrd($uri);
157 $parts = @parse_url($uri);
161 $host = $parts["host"];
163 $path_parts = explode("/", trim($parts["path"], "/"));
166 $lrdd = self::xrd($host);
167 $host .= "/".array_shift($path_parts);
168 } while (!$lrdd AND (sizeof($path_parts) > 0));
174 foreach ($lrdd AS $key => $link) {
178 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json")))
181 $path = str_replace('{uri}', urlencode($uri), $link);
182 $webfinger = self::webfinger($path);
185 if (!is_array($webfinger["links"]))
190 foreach ($webfinger["links"] AS $link)
191 $data[] = array("@attributes" => $link);
193 if (is_array($webfinger["aliases"]))
194 foreach ($webfinger["aliases"] AS $alias)
195 $data[] = array("@attributes" =>
196 array("rel" => "alias",
203 * @brief Fetch information (protocol endpoints and user information) about a given uri
205 * @param string $uri Address that should be probed
206 * @param string $network Test for this specific network
207 * @param integer $uid User ID for the probe (only used for mails)
208 * @param boolean $cache Use cached values?
210 * @return array uri data
212 public static function uri($uri, $network = "", $uid = 0, $cache = true) {
215 $result = Cache::get("probe_url:".$network.":".$uri);
216 if (!is_null($result)) {
217 $result = unserialize($result);
225 $data = self::detect($uri, $network, $uid);
227 if (!isset($data["url"]))
230 if ($data["photo"] != "")
231 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
233 $data["photo"] = App::get_baseurl().'/images/person-175.jpg';
235 if (!isset($data["name"]) OR ($data["name"] == "")) {
236 if (isset($data["nick"]))
237 $data["name"] = $data["nick"];
239 if ($data["name"] == "")
240 $data["name"] = $data["url"];
243 if (!isset($data["nick"]) OR ($data["nick"] == "")) {
244 $data["nick"] = strtolower($data["name"]);
246 if (strpos($data['nick'], ' '))
247 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
250 if (!isset($data["network"]))
251 $data["network"] = NETWORK_PHANTOM;
253 $data = self::rearrange_data($data);
255 // Only store into the cache if the value seems to be valid
256 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
257 Cache::set("probe_url:".$network.":".$uri,serialize($data), CACHE_DAY);
259 /// @todo temporary fix - we need a real contact update function that updates only changing fields
260 /// The biggest problem is the avatar picture that could have a reduced image size.
261 /// It should only be updated if the existing picture isn't existing anymore.
262 if (($data['network'] != NETWORK_FEED) AND ($mode == PROBE_NORMAL) AND
263 $data["name"] AND $data["nick"] AND $data["url"] AND $data["addr"] AND $data["poll"])
264 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `url` = '%s', `addr` = '%s',
265 `notify` = '%s', `poll` = '%s', `alias` = '%s', `success_update` = '%s'
266 WHERE `nurl` = '%s' AND NOT `self` AND `uid` = 0",
267 dbesc($data["name"]),
268 dbesc($data["nick"]),
270 dbesc($data["addr"]),
271 dbesc($data["notify"]),
272 dbesc($data["poll"]),
273 dbesc($data["alias"]),
274 dbesc(datetime_convert()),
275 dbesc(normalise_link($data['url']))
282 * @brief Fetch information (protocol endpoints and user information) about a given uri
284 * This function is only called by the "uri" function that adds caching and rearranging of data.
286 * @param string $uri Address that should be probed
287 * @param string $network Test for this specific network
288 * @param integer $uid User ID for the probe (only used for mails)
290 * @return array uri data
292 private function detect($uri, $network, $uid) {
293 if (strstr($uri, '@')) {
294 // If the URI starts with "mailto:" then jump directly to the mail detection
295 if (strpos($url,'mailto:') !== false) {
296 $uri = str_replace('mailto:', '', $url);
297 return self::mail($uri, $uid);
300 if ($network == NETWORK_MAIL)
301 return self::mail($uri, $uid);
303 // Remove "acct:" from the URI
304 $uri = str_replace('acct:', '', $uri);
306 $host = substr($uri,strpos($uri, '@') + 1);
307 $nick = substr($uri,0, strpos($uri, '@'));
309 if (strpos($uri, '@twitter.com'))
310 return array("network" => NETWORK_TWITTER);
312 $lrdd = self::xrd($host);
314 return self::mail($uri, $uid);
318 $parts = parse_url($uri);
319 if (!isset($parts["scheme"]) OR
320 !isset($parts["host"]) OR
321 !isset($parts["path"]))
325 $host = $parts["host"];
327 if ($host == 'twitter.com')
328 return array("network" => NETWORK_TWITTER);
330 $lrdd = self::xrd($host);
332 $path_parts = explode("/", trim($parts["path"], "/"));
334 while (!$lrdd AND (sizeof($path_parts) > 1)) {
335 $host .= "/".array_shift($path_parts);
336 $lrdd = self::xrd($host);
339 return self::feed($uri);
341 $nick = array_pop($path_parts);
342 $addr = $nick."@".$host;
346 /// @todo Do we need the prefix "acct:" or "acct://"?
348 foreach ($lrdd AS $key => $link) {
352 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json")))
355 // Try webfinger with the address (user@domain.tld)
356 $path = str_replace('{uri}', urlencode($addr), $link);
357 $webfinger = self::webfinger($path);
359 // If webfinger wasn't successful then try it with the URL - possibly in the format https://...
360 if (!$webfinger AND ($uri != $addr)) {
361 $path = str_replace('{uri}', urlencode($uri), $link);
362 $webfinger = self::webfinger($path);
364 // Since the detection with the address wasn't successful, we delete it.
373 return self::feed($uri);
377 logger("Probing ".$uri, LOGGER_DEBUG);
379 if (in_array($network, array("", NETWORK_DFRN)))
380 $result = self::dfrn($webfinger);
381 if ((!$result AND ($network == "")) OR ($network == NETWORK_DIASPORA))
382 $result = self::diaspora($webfinger);
383 if ((!$result AND ($network == "")) OR ($network == NETWORK_OSTATUS))
384 $result = self::ostatus($webfinger);
385 if ((!$result AND ($network == "")) OR ($network == NETWORK_PUMPIO))
386 $result = self::pumpio($webfinger);
387 if ((!$result AND ($network == "")) OR ($network == NETWORK_FEED))
388 $result = self::feed($uri);
390 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
391 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
392 if ((!isset($result["nick"]) OR ($result["nick"] == "") OR (strstr($result["nick"], " "))) AND ($nick != ""))
393 $result["nick"] = $nick;
395 if ((!isset($result["addr"]) OR ($result["addr"] == "")) AND ($addr != ""))
396 $result["addr"] = $addr;
399 logger($uri." is ".$result["network"], LOGGER_DEBUG);
401 if (!isset($result["baseurl"]) OR ($result["baseurl"] == "")) {
402 $pos = strpos($result["url"], $host);
404 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
411 * @brief Do a webfinger request. For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
413 * @param string $url Address that should be probed
415 * @return array webfinger data
417 private function webfinger($url) {
419 $xrd_timeout = Config::get('system','xrd_timeout', 20);
422 $data = fetch_url($url, false, $redirects, $xrd_timeout, "application/xrd+xml");
423 $xrd = parse_xml_string($data, false);
425 if (!is_object($xrd)) {
426 // If it is not XML, maybe it is JSON
427 $webfinger = json_decode($data, true);
429 if (!isset($webfinger["links"]))
435 $xrd_arr = xml::element_to_array($xrd);
436 if (!isset($xrd_arr["xrd"]["link"]))
439 $webfinger = array();
441 if (isset($xrd_arr["xrd"]["subject"]))
442 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
444 if (isset($xrd_arr["xrd"]["alias"]))
445 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
447 $webfinger["links"] = array();
449 foreach ($xrd_arr["xrd"]["link"] AS $value => $data) {
450 if (isset($data["@attributes"]))
451 $attributes = $data["@attributes"];
452 elseif ($value == "@attributes")
457 $webfinger["links"][] = $attributes;
463 * @brief Poll the noscrape page (Friendica specific)
465 * "noscrape" is a faster alternative to fetching the data from the hcard.
467 * @param string $noscrape Link to the noscrape page
468 * @param array $data The already fetched data
470 * @return array noscrape data
472 private function poll_noscrape($noscrape, $data) {
473 $content = fetch_url($noscrape);
477 $json = json_decode($content, true);
478 if (!is_array($json))
481 if (isset($json["fn"]))
482 $data["name"] = $json["fn"];
484 if (isset($json["addr"]))
485 $data["addr"] = $json["addr"];
487 if (isset($json["nick"]))
488 $data["nick"] = $json["nick"];
490 if (isset($json["comm"]))
491 $data["community"] = $json["comm"];
493 if (isset($json["tags"])) {
494 $keywords = implode(" ", $json["tags"]);
496 $data["keywords"] = $keywords;
499 $location = formatted_location($json);
501 $data["location"] = $location;
503 if (isset($json["about"]))
504 $data["about"] = $json["about"];
506 if (isset($json["key"]))
507 $data["pubkey"] = $json["key"];
509 if (isset($json["photo"]))
510 $data["photo"] = $json["photo"];
512 if (isset($json["dfrn-request"]))
513 $data["request"] = $json["dfrn-request"];
515 if (isset($json["dfrn-confirm"]))
516 $data["confirm"] = $json["dfrn-confirm"];
518 if (isset($json["dfrn-notify"]))
519 $data["notify"] = $json["dfrn-notify"];
521 if (isset($json["dfrn-poll"]))
522 $data["poll"] = $json["dfrn-poll"];
528 * @brief Check for valid DFRN data
530 * @param array $data DFRN data
532 * @return int Number of errors
534 public static function valid_dfrn($data) {
536 if(!isset($data['key']))
538 if(!isset($data['dfrn-request']))
540 if(!isset($data['dfrn-confirm']))
542 if(!isset($data['dfrn-notify']))
544 if(!isset($data['dfrn-poll']))
550 * @brief Fetch data from a DFRN profile page and via "noscrape"
552 * @param string $profile Link to the profile page
554 * @return array profile data
556 public static function profile($profile) {
560 // Fetch data via noscrape - this is faster
561 $noscrape = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile);
562 $data = self::poll_noscrape($noscrape, $data);
564 if (!isset($data["notify"]) OR !isset($data["confirm"]) OR
565 !isset($data["request"]) OR !isset($data["poll"]) OR
566 !isset($data["poco"]) OR !isset($data["name"]) OR
567 !isset($data["photo"]))
568 $data = self::poll_hcard($profile, $data, true);
570 $prof_data = array();
571 $prof_data["addr"] = $data["addr"];
572 $prof_data["nick"] = $data["nick"];
573 $prof_data["dfrn-request"] = $data["request"];
574 $prof_data["dfrn-confirm"] = $data["confirm"];
575 $prof_data["dfrn-notify"] = $data["notify"];
576 $prof_data["dfrn-poll"] = $data["poll"];
577 $prof_data["dfrn-poco"] = $data["poco"];
578 $prof_data["photo"] = $data["photo"];
579 $prof_data["fn"] = $data["name"];
580 $prof_data["key"] = $data["pubkey"];
586 * @brief Check for DFRN contact
588 * @param array $webfinger Webfinger data
590 * @return array DFRN data
592 private function dfrn($webfinger) {
596 foreach ($webfinger["links"] AS $link) {
597 if (($link["rel"] == NAMESPACE_DFRN) AND ($link["href"] != ""))
598 $data["network"] = NETWORK_DFRN;
599 elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
600 $data["poll"] = $link["href"];
601 elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
602 ($link["type"] == "text/html") AND ($link["href"] != ""))
603 $data["url"] = $link["href"];
604 elseif (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != ""))
605 $hcard = $link["href"];
606 elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != ""))
607 $data["poco"] = $link["href"];
608 elseif (($link["rel"] == "http://webfinger.net/rel/avatar") AND ($link["href"] != ""))
609 $data["photo"] = $link["href"];
611 elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != ""))
612 $data["baseurl"] = trim($link["href"], '/');
613 elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != ""))
614 $data["guid"] = $link["href"];
615 elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
616 $data["pubkey"] = base64_decode($link["href"]);
618 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
619 if (strstr($data["pubkey"], 'RSA '))
620 $data["pubkey"] = rsatopem($data["pubkey"]);
624 if (!isset($data["network"]) OR ($hcard == ""))
627 // Fetch data via noscrape - this is faster
628 $noscrape = str_replace("/hcard/", "/noscrape/", $hcard);
629 $data = self::poll_noscrape($noscrape, $data);
631 if (isset($data["notify"]) AND isset($data["confirm"]) AND isset($data["request"]) AND
632 isset($data["poll"]) AND isset($data["name"]) AND isset($data["photo"]))
635 $data = self::poll_hcard($hcard, $data, true);
641 * @brief Poll the hcard page (Diaspora and Friendica specific)
643 * @param string $hcard Link to the hcard page
644 * @param array $data The already fetched data
645 * @param boolean $dfrn Poll DFRN specific data
647 * @return array hcard data
649 private function poll_hcard($hcard, $data, $dfrn = false) {
651 $doc = new DOMDocument();
652 if (!@$doc->loadHTMLFile($hcard))
655 $xpath = new DomXPath($doc);
657 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
658 if (!is_object($vcards))
661 if ($vcards->length == 0)
664 $vcard = $vcards->item(0);
666 // We have to discard the guid from the hcard in favour of the guid from lrdd
667 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
668 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
669 if (($search->length > 0) AND ($data["guid"] == ""))
670 $data["guid"] = $search->item(0)->nodeValue;
672 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
673 if ($search->length > 0)
674 $data["nick"] = $search->item(0)->nodeValue;
676 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
677 if ($search->length > 0)
678 $data["name"] = $search->item(0)->nodeValue;
680 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
681 if ($search->length > 0)
682 $data["searchable"] = $search->item(0)->nodeValue;
684 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
685 if ($search->length > 0) {
686 $data["pubkey"] = $search->item(0)->nodeValue;
687 if (strstr($data["pubkey"], 'RSA '))
688 $data["pubkey"] = rsatopem($data["pubkey"]);
691 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
692 if ($search->length > 0)
693 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
696 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
697 foreach ($photos AS $photo) {
699 foreach ($photo->attributes as $attribute)
700 $attr[$attribute->name] = trim($attribute->value);
702 if (isset($attr["src"]) AND isset($attr["width"]))
703 $avatar[$attr["width"]] = $attr["src"];
706 if (sizeof($avatar)) {
708 $data["photo"] = array_pop($avatar);
712 // Poll DFRN specific data
713 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
714 if ($search->length > 0) {
715 foreach ($search AS $link) {
716 //$data["request"] = $search->item(0)->nodeValue;
718 foreach ($link->attributes as $attribute)
719 $attr[$attribute->name] = trim($attribute->value);
721 $data[substr($attr["rel"], 5)] = $attr["href"];
725 // Older Friendica versions had used the "uid" field differently than newer versions
726 if ($data["nick"] == $data["guid"])
727 unset($data["guid"]);
735 * @brief Check for Diaspora contact
737 * @param array $webfinger Webfinger data
739 * @return array Diaspora data
741 private function diaspora($webfinger) {
745 foreach ($webfinger["links"] AS $link) {
746 if (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != ""))
747 $hcard = $link["href"];
748 elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != ""))
749 $data["baseurl"] = trim($link["href"], '/');
750 elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != ""))
751 $data["guid"] = $link["href"];
752 elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
753 ($link["type"] == "text/html") AND ($link["href"] != ""))
754 $data["url"] = $link["href"];
755 elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
756 $data["poll"] = $link["href"];
757 elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != ""))
758 $data["poco"] = $link["href"];
759 elseif (($link["rel"] == "salmon") AND ($link["href"] != ""))
760 $data["notify"] = $link["href"];
761 elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
762 $data["pubkey"] = base64_decode($link["href"]);
764 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
765 if (strstr($data["pubkey"], 'RSA '))
766 $data["pubkey"] = rsatopem($data["pubkey"]);
770 if (!isset($data["url"]) OR ($hcard == ""))
773 if (is_array($webfinger["aliases"]))
774 foreach ($webfinger["aliases"] AS $alias)
775 if (normalise_link($alias) != normalise_link($data["url"]) AND !strstr($alias, "@"))
776 $data["alias"] = $alias;
778 // Fetch further information from the hcard
779 $data = self::poll_hcard($hcard, $data);
784 if (isset($data["url"]) AND isset($data["guid"]) AND isset($data["baseurl"]) AND
785 isset($data["pubkey"]) AND ($hcard != "")) {
786 $data["network"] = NETWORK_DIASPORA;
788 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
789 $data["notify"] = $data["baseurl"]."/receive/users/".$data["guid"];
790 $data["batch"] = $data["baseurl"]."/receive/public";
798 * @brief Check for OStatus contact
800 * @param array $webfinger Webfinger data
802 * @return array OStatus data
804 private function ostatus($webfinger) {
807 if (is_array($webfinger["aliases"]))
808 foreach($webfinger["aliases"] AS $alias)
809 if (strstr($alias, "@"))
810 $data["addr"] = str_replace('acct:', '', $alias);
813 foreach ($webfinger["links"] AS $link) {
814 if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
815 ($link["type"] == "text/html") AND ($link["href"] != ""))
816 $data["url"] = $link["href"];
817 elseif (($link["rel"] == "salmon") AND ($link["href"] != ""))
818 $data["notify"] = $link["href"];
819 elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
820 $data["poll"] = $link["href"];
821 elseif (($link["rel"] == "magic-public-key") AND ($link["href"] != "")) {
822 $pubkey = $link["href"];
824 if (substr($pubkey, 0, 5) === 'data:') {
825 if (strstr($pubkey, ','))
826 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
828 $pubkey = substr($pubkey, 5);
830 $pubkey = fetch_url($pubkey);
832 $key = explode(".", $pubkey);
834 if (sizeof($key) >= 3) {
835 $m = base64url_decode($key[1]);
836 $e = base64url_decode($key[2]);
837 $data["pubkey"] = metopem($m,$e);
843 if (isset($data["notify"]) AND isset($data["pubkey"]) AND
844 isset($data["poll"]) AND isset($data["url"])) {
845 $data["network"] = NETWORK_OSTATUS;
849 // Fetch all additional data from the feed
850 $feed = fetch_url($data["poll"]);
851 $feed_data = feed_import($feed,$dummy1,$dummy2, $dummy3, true);
855 if ($feed_data["header"]["author-name"] != "")
856 $data["name"] = $feed_data["header"]["author-name"];
858 if ($feed_data["header"]["author-nick"] != "")
859 $data["nick"] = $feed_data["header"]["author-nick"];
861 if ($feed_data["header"]["author-avatar"] != "")
862 $data["photo"] = $feed_data["header"]["author-avatar"];
864 if ($feed_data["header"]["author-id"] != "")
865 $data["alias"] = $feed_data["header"]["author-id"];
867 if ($feed_data["header"]["author-location"] != "")
868 $data["location"] = $feed_data["header"]["author-location"];
870 if ($feed_data["header"]["author-about"] != "")
871 $data["about"] = $feed_data["header"]["author-about"];
873 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
874 // So we take the value that we just fetched, although the other one worked as well
875 if ($feed_data["header"]["author-link"] != "")
876 $data["url"] = $feed_data["header"]["author-link"];
878 /// @todo Fetch location and "about" from the feed as well
883 * @brief Fetch data from a pump.io profile page
885 * @param string $profile Link to the profile page
887 * @return array profile data
889 private function pumpio_profile_data($profile) {
891 $doc = new DOMDocument();
892 if (!@$doc->loadHTMLFile($profile))
895 $xpath = new DomXPath($doc);
899 // This is ugly - but pump.io doesn't seem to know a better way for it
900 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
901 $pos = strpos($data["name"], chr(10));
903 $data["name"] = trim(substr($data["name"], 0, $pos));
905 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
907 foreach ($avatar->attributes as $attribute)
908 if ($attribute->name == "src")
909 $data["photo"] = trim($attribute->value);
911 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
912 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
918 * @brief Check for pump.io contact
920 * @param array $webfinger Webfinger data
922 * @return array pump.io data
924 private function pumpio($webfinger) {
927 foreach ($webfinger["links"] AS $link) {
928 if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
929 ($link["type"] == "text/html") AND ($link["href"] != ""))
930 $data["url"] = $link["href"];
931 elseif (($link["rel"] == "activity-inbox") AND ($link["href"] != ""))
932 $data["notify"] = $link["href"];
933 elseif (($link["rel"] == "activity-outbox") AND ($link["href"] != ""))
934 $data["poll"] = $link["href"];
935 elseif (($link["rel"] == "dialback") AND ($link["href"] != ""))
936 $data["dialback"] = $link["href"];
938 if (isset($data["poll"]) AND isset($data["notify"]) AND
939 isset($data["dialback"]) AND isset($data["url"])) {
941 // by now we use these fields only for the network type detection
942 // So we unset all data that isn't used at the moment
943 unset($data["dialback"]);
945 $data["network"] = NETWORK_PUMPIO;
949 $profile_data = self::pumpio_profile_data($data["url"]);
954 $data = array_merge($data, $profile_data);
960 * @brief Check page for feed link
962 * @param string $url Page link
964 * @return string feed link
966 private function get_feed_link($url) {
967 $doc = new DOMDocument();
969 if (!@$doc->loadHTMLFile($url))
972 $xpath = new DomXPath($doc);
974 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
975 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
976 if (!is_object($feeds))
979 if ($feeds->length == 0)
984 foreach ($feeds AS $feed) {
986 foreach ($feed->attributes as $attribute)
987 $attr[$attribute->name] = trim($attribute->value);
990 $feed_url = $attr["href"];
997 * @brief Check for feed contact
999 * @param string $url Profile link
1000 * @param boolean $probe Do a probe if the page contains a feed link
1002 * @return array feed data
1004 private function feed($url, $probe = true) {
1005 $feed = fetch_url($url);
1006 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1012 $feed_url = self::get_feed_link($url);
1017 return self::feed($feed_url, false);
1020 if ($feed_data["header"]["author-name"] != "")
1021 $data["name"] = $feed_data["header"]["author-name"];
1023 if ($feed_data["header"]["author-nick"] != "")
1024 $data["nick"] = $feed_data["header"]["author-nick"];
1026 if ($feed_data["header"]["author-avatar"] != "")
1027 $data["photo"] = $feed_data["header"]["author-avatar"];
1029 if ($feed_data["header"]["author-id"] != "")
1030 $data["alias"] = $feed_data["header"]["author-id"];
1032 $data["url"] = $url;
1033 $data["poll"] = $url;
1035 if ($feed_data["header"]["author-link"] != "")
1036 $data["baseurl"] = $feed_data["header"]["author-link"];
1038 $data["baseurl"] = $data["url"];
1040 $data["network"] = NETWORK_FEED;
1046 * @brief Check for mail contact
1048 * @param string $uri Profile link
1049 * @param integer $uid User ID
1051 * @return array mail data
1053 private function mail($uri, $uid) {
1055 if (!validate_email($uri))
1058 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1060 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1062 if(count($x) && count($r)) {
1063 $mailbox = construct_mailbox_name($r[0]);
1065 openssl_private_decrypt(hex2bin($r[0]['pass']), $password,$x[0]['prvkey']);
1066 $mbox = email_connect($mailbox,$r[0]['user'], $password);
1071 $msgs = email_poll($mbox, $uri);
1072 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1079 $data["addr"] = $uri;
1080 $data["network"] = NETWORK_MAIL;
1081 $data["name"] = substr($uri, 0, strpos($uri,'@'));
1082 $data["nick"] = $data["name"];
1083 $data["photo"] = avatar_img($uri);
1085 $phost = substr($uri, strpos($uri,'@') + 1);
1086 $data["url"] = 'http://'.$phost."/".$data["nick"];
1087 $data["notify"] = 'smtp '.random_string();
1088 $data["poll"] = 'email '.random_string();
1090 $x = email_msg_meta($mbox, $msgs[0]);
1091 if(stristr($x[0]->from, $uri))
1092 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1093 elseif(stristr($x[0]->to, $uri))
1094 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1096 foreach($adr as $feadr) {
1097 if((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1098 &&(strcasecmp($feadr->host, $phost) == 0)
1099 && (strlen($feadr->personal))) {
1101 $personal = imap_mime_header_decode($feadr->personal);
1103 foreach($personal as $perspart)
1104 if ($perspart->charset != "default")
1105 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1107 $data["name"] .= $perspart->text;
1109 $data["name"] = notags($data["name"]);