3 * @brief This class contain functions for probing URL
7 use \Friendica\Core\Config;
8 use \Friendica\Core\PConfig;
10 require_once("include/feed.php");
11 require_once('include/email.php');
15 private function rearrange_data($data) {
16 $fields = array("name", "nick", "guid", "url", "addr", "alias",
17 "photo", "community", "keywords", "location", "about",
18 "batch", "notify", "poll", "request", "confirm", "poco",
19 "priority", "network", "pubkey", "baseurl");
22 foreach ($fields AS $field)
23 if (isset($data[$field]))
24 $newdata[$field] = $data[$field];
26 $newdata[$field] = "";
28 // We don't use the "priority" field anymore and replace it with a dummy.
29 $newdata["priority"] = 0;
35 * @brief Probes for XRD data
38 * 'lrdd' => Link to LRDD endpoint
39 * 'lrdd-xml' => Link to LRDD endpoint in XML format
40 * 'lrdd-json' => Link to LRDD endpoint in JSON format
42 private function xrd($host) {
44 $ssl_url = "https://".$host."/.well-known/host-meta";
45 $url = "http://".$host."/.well-known/host-meta";
47 $xrd_timeout = Config::get('system','xrd_timeout', 20);
50 $xml = fetch_url($ssl_url, false, $redirects, $xrd_timeout, "application/xrd+xml");
51 $xrd = parse_xml_string($xml, false);
53 if (!is_object($xrd)) {
54 $xml = fetch_url($url, false, $redirects, $xrd_timeout, "application/xrd+xml");
55 $xrd = parse_xml_string($xml, false);
60 $links = xml::element_to_array($xrd);
61 if (!isset($links["xrd"]["link"]))
65 foreach ($links["xrd"]["link"] AS $value => $link) {
66 if (isset($link["@attributes"]))
67 $attributes = $link["@attributes"];
68 elseif ($value == "@attributes")
73 if (($attributes["rel"] == "lrdd") AND
74 ($attributes["type"] == "application/xrd+xml"))
75 $xrd_data["lrdd-xml"] = $attributes["template"];
76 elseif (($attributes["rel"] == "lrdd") AND
77 ($attributes["type"] == "application/json"))
78 $xrd_data["lrdd-json"] = $attributes["template"];
79 elseif ($attributes["rel"] == "lrdd")
80 $xrd_data["lrdd"] = $attributes["template"];
85 public static function uri($uri, $network = "") {
87 $result = Cache::get("probe_url:".$network.":".$uri);
88 if (!is_null($result)) {
89 $result = unserialize($result);
93 $data = self::detect($uri, $network);
95 if (!isset($data["url"]))
98 if ($data["photo"] != "")
99 $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
101 $data["photo"] = App::get_baseurl().'/images/person-175.jpg';
103 if (!isset($data["name"]))
104 $data["name"] = $data["url"];
106 if (!isset($data["nick"]))
107 $data["nick"] = strtolower($data["name"]);
109 if (!isset($data["network"]))
110 $data["network"] = NETWORK_PHANTOM;
112 $data = self::rearrange_data($data);
114 // Only store into the cache if the value seems to be valid
115 if ($data['network'] != NETWORK_PHANTOM) {
116 Cache::set("probe_url:".$network.":".$uri,serialize($data), CACHE_DAY);
118 /// @todo temporary fix - we need a real contact update function that updates only changing fields
119 /// The biggest problem is the avatar picture that could have a reduced image size.
120 /// It should only be updated if the existing picture isn't existing anymore.
121 if (($data['network'] != NETWORK_FEED) AND ($mode == PROBE_NORMAL) AND
122 $data["name"] AND $data["nick"] AND $data["url"] AND $data["addr"] AND $data["poll"])
123 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `url` = '%s', `addr` = '%s',
124 `notify` = '%s', `poll` = '%s', `alias` = '%s', `success_update` = '%s'
125 WHERE `nurl` = '%s' AND NOT `self` AND `uid` = 0",
126 dbesc($data["name"]),
127 dbesc($data["nick"]),
129 dbesc($data["addr"]),
130 dbesc($data["notify"]),
131 dbesc($data["poll"]),
132 dbesc($data["alias"]),
133 dbesc(datetime_convert()),
134 dbesc(normalise_link($data['url']))
140 private function detect($uri, $network) {
141 if (strstr($uri, '@')) {
142 // If the URI starts with "mailto:" then jum directly to the mail detection
143 if (strpos($url,'mailto:') !== false) {
144 $uri = str_replace('mailto:', '', $url);
145 return self::mail($uri);
148 if ($network == NETWORK_MAIL)
149 return self::mail($uri);
151 // Remove "acct:" from the URI
152 $uri = str_replace('acct:', '', $uri);
154 $host = substr($uri,strpos($uri, '@') + 1);
155 $nick = substr($uri,0, strpos($uri, '@'));
157 $lrdd = self::xrd($host);
159 return self::mail($uri);
163 $parts = parse_url($uri);
164 if (!isset($parts["scheme"]) OR
165 !isset($parts["host"]) OR
166 !isset($parts["path"]))
170 $host = $parts["host"];
171 $lrdd = self::xrd($host);
173 $path_parts = explode("/", trim($parts["path"], "/"));
175 while (!$lrdd AND (sizeof($path_parts) > 1)) {
176 $host .= "/".array_shift($path_parts);
177 $lrdd = self::xrd($host);
180 return self::feed($uri);
182 $nick = array_pop($path_parts);
183 $addr = $nick."@".$host;
188 /// @todo Do we need the prefix "acct:" or "acct://"?
190 foreach ($lrdd AS $key => $link) {
194 if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json")))
197 $path = str_replace('{uri}', urlencode($addr), $link);
199 $webfinger = self::webfinger($path);
202 return self::feed($uri);
206 if (in_array($network, array("", NETWORK_DFRN)))
207 $result = self::dfrn($webfinger);
208 if ((!$result AND ($network == "")) OR ($network == NETWORK_DIASPORA))
209 $result = self::diaspora($webfinger);
210 if ((!$result AND ($network == "")) OR ($network == NETWORK_OSTATUS))
211 $result = self::ostatus($webfinger);
212 if ((!$result AND ($network == "")) OR ($network == NETWORK_PUMPIO))
213 $result = self::pumpio($webfinger);
214 if ((!$result AND ($network == "")) OR ($network == NETWORK_FEED))
215 $result = self::feed($uri);
217 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
218 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
219 if (!isset($result["nick"]) OR ($result["nick"] == "") OR (strstr($result["nick"], " ")))
220 $result["nick"] = $nick;
222 if (!isset($result["addr"]) OR ($result["addr"] == ""))
223 $result["addr"] = $addr;
226 if (!isset($result["baseurl"]) OR ($result["baseurl"] == "")) {
227 $pos = strpos($result["url"], $host);
229 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
235 private function webfinger($url) {
237 $xrd_timeout = Config::get('system','xrd_timeout', 20);
240 $data = fetch_url($url, false, $redirects, $xrd_timeout, "application/xrd+xml");
241 $xrd = parse_xml_string($data, false);
243 if (!is_object($xrd)) {
244 // If it is not XML, maybe it is JSON
245 $webfinger = json_decode($data, true);
247 if (!isset($webfinger["links"]))
253 $xrd_arr = xml::element_to_array($xrd);
254 if (!isset($xrd_arr["xrd"]["link"]))
257 $webfinger = array();
259 if (isset($xrd_arr["xrd"]["subject"]))
260 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
262 if (isset($xrd_arr["xrd"]["alias"]))
263 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
265 $webfinger["links"] = array();
267 foreach ($xrd_arr["xrd"]["link"] AS $value => $data) {
268 if (isset($data["@attributes"]))
269 $attributes = $data["@attributes"];
270 elseif ($value == "@attributes")
275 $webfinger["links"][] = $attributes;
280 private function poll_noscrape($noscrape, $data) {
281 $content = fetch_url($noscrape);
285 $json = json_decode($content, true);
286 if (!is_array($json))
289 if (isset($json["fn"]))
290 $data["name"] = $json["fn"];
292 if (isset($json["addr"]))
293 $data["addr"] = $json["addr"];
295 if (isset($json["nick"]))
296 $data["nick"] = $json["nick"];
298 if (isset($json["comm"]))
299 $data["community"] = $json["comm"];
301 if (isset($json["tags"])) {
302 $keywords = implode(" ", $json["tags"]);
304 $data["keywords"] = $keywords;
307 $location = formatted_location($json);
309 $data["location"] = $location;
311 if (isset($json["about"]))
312 $data["about"] = $json["about"];
314 if (isset($json["key"]))
315 $data["pubkey"] = $json["key"];
317 if (isset($json["photo"]))
318 $data["photo"] = $json["photo"];
320 if (isset($json["dfrn-request"]))
321 $data["request"] = $json["dfrn-request"];
323 if (isset($json["dfrn-confirm"]))
324 $data["confirm"] = $json["dfrn-confirm"];
326 if (isset($json["dfrn-notify"]))
327 $data["notify"] = $json["dfrn-notify"];
329 if (isset($json["dfrn-poll"]))
330 $data["poll"] = $json["dfrn-poll"];
335 private function dfrn($webfinger) {
339 foreach ($webfinger["links"] AS $link) {
340 if (($link["rel"] == NAMESPACE_DFRN) AND ($link["href"] != ""))
341 $data["network"] = NETWORK_DFRN;
342 elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
343 $data["poll"] = $link["href"];
344 elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
345 ($link["type"] == "text/html") AND ($link["href"] != ""))
346 $data["url"] = $link["href"];
347 elseif (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != ""))
348 $hcard = $link["href"];
349 elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != ""))
350 $data["poco"] = $link["href"];
351 elseif (($link["rel"] == "http://webfinger.net/rel/avatar") AND ($link["href"] != ""))
352 $data["photo"] = $link["href"];
354 elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != ""))
355 $data["baseurl"] = trim($link["href"], '/');
356 elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != ""))
357 $data["guid"] = $link["href"];
358 elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
359 $data["pubkey"] = base64_decode($link["href"]);
361 if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
362 $data["pubkey"] = rsatopem($data["pubkey"]);
366 if (!isset($data["network"]) OR ($hcard == ""))
369 // Fetch data via noscrape - this is faster
370 $noscrape = str_replace("/hcard/", "/noscrape/", $hcard);
371 $data = self::poll_noscrape($noscrape, $data);
373 if (isset($data["notify"]) AND isset($data["confirm"]) AND isset($data["request"]) AND
374 isset($data["poll"]) AND isset($data["name"]) AND isset($data["photo"]))
377 $data = self::poll_hcard($hcard, $data, true);
382 private function poll_hcard($hcard, $data, $dfrn = false) {
384 $doc = new DOMDocument();
385 if (!@$doc->loadHTMLFile($hcard))
388 $xpath = new DomXPath($doc);
390 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
391 if (!is_object($vcards))
394 if ($vcards->length == 0)
397 $vcard = $vcards->item(0);
399 // We have to discard the guid from the hcard in favour of the guid from lrdd
400 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
401 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
402 if (($search->length > 0) AND ($data["guid"] == ""))
403 $data["guid"] = $search->item(0)->nodeValue;
405 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
406 if ($search->length > 0)
407 $data["nick"] = $search->item(0)->nodeValue;
409 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
410 if ($search->length > 0)
411 $data["name"] = $search->item(0)->nodeValue;
413 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
414 if ($search->length > 0)
415 $data["searchable"] = $search->item(0)->nodeValue;
417 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
418 if ($search->length > 0) {
419 $data["pubkey"] = $search->item(0)->nodeValue;
420 if (strstr($data["pubkey"], 'RSA '))
421 $data["pubkey"] = rsatopem($data["pubkey"]);
424 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
425 if ($search->length > 0)
426 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
429 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
430 foreach ($photos AS $photo) {
432 foreach ($photo->attributes as $attribute)
433 $attr[$attribute->name] = trim($attribute->value);
435 if (isset($attr["src"]) AND isset($attr["width"]))
436 $avatar[$attr["width"]] = $attr["src"];
439 if (sizeof($avatar)) {
441 $data["photo"] = array_pop($avatar);
445 // Poll DFRN specific data
446 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
447 if ($search->length > 0) {
448 foreach ($search AS $link) {
449 //$data["request"] = $search->item(0)->nodeValue;
451 foreach ($link->attributes as $attribute)
452 $attr[$attribute->name] = trim($attribute->value);
454 $data[substr($attr["rel"], 5)] = $attr["href"];
458 // Older Friendica versions had used the "uid" field differently than newer versions
459 if ($data["nick"] == $data["guid"])
460 unset($data["guid"]);
467 private function diaspora($webfinger) {
471 foreach ($webfinger["links"] AS $link) {
472 if (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != ""))
473 $hcard = $link["href"];
474 elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != ""))
475 $data["baseurl"] = trim($link["href"], '/');
476 elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != ""))
477 $data["guid"] = $link["href"];
478 elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
479 ($link["type"] == "text/html") AND ($link["href"] != ""))
480 $data["url"] = $link["href"];
481 elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
482 $data["poll"] = $link["href"];
483 elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != ""))
484 $data["poco"] = $link["href"];
485 elseif (($link["rel"] == "salmon") AND ($link["href"] != ""))
486 $data["notify"] = $link["href"];
487 elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
488 $data["pubkey"] = base64_decode($link["href"]);
490 if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
491 $data["pubkey"] = rsatopem($data["pubkey"]);
495 if (!isset($data["url"]) OR ($hcard == ""))
498 if (isset($webfinger["aliases"]))
499 foreach ($webfinger["aliases"] AS $alias)
500 if (normalise_link($alias) != normalise_link($data["url"]) AND !strstr($alias, "@"))
501 $data["alias"] = $alias;
503 // Fetch further information from the hcard
504 $data = self::poll_hcard($hcard, $data);
509 if (isset($data["url"]) AND isset($data["guid"]) AND isset($data["baseurl"]) AND
510 isset($data["pubkey"]) AND ($hcard != "")) {
511 $data["network"] = NETWORK_DIASPORA;
513 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
514 $data["notify"] = $data["baseurl"]."/receive/users/".$data["guid"];
515 $data["batch"] = $data["baseurl"]."/receive/public";
522 private function ostatus($webfinger) {
526 foreach ($webfinger["links"] AS $link) {
527 if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
528 ($link["type"] == "text/html") AND ($link["href"] != ""))
529 $data["url"] = $link["href"];
530 elseif (($link["rel"] == "salmon") AND ($link["href"] != ""))
531 $data["notify"] = $link["href"];
532 elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
533 $data["poll"] = $link["href"];
534 elseif (($link["rel"] == "magic-public-key") AND ($link["href"] != "")) {
535 $pubkey = $link["href"];
537 if (substr($pubkey, 0, 5) === 'data:') {
538 if (strstr($pubkey, ','))
539 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
541 $pubkey = substr($pubkey, 5);
543 $pubkey = fetch_url($pubkey);
545 $key = explode(".", $pubkey);
547 if (sizeof($key) >= 3) {
548 $m = base64url_decode($key[1]);
549 $e = base64url_decode($key[2]);
550 $data["pubkey"] = metopem($m,$e);
556 if (isset($data["notify"]) AND isset($data["pubkey"]) AND
557 isset($data["poll"]) AND isset($data["url"])) {
558 $data["network"] = NETWORK_OSTATUS;
562 // Fetch all additional data from the feed
563 $feed = fetch_url($data["poll"]);
564 $feed_data = feed_import($feed,$dummy1,$dummy2, $dummy3, true);
568 if ($feed_data["header"]["author-name"] != "")
569 $data["name"] = $feed_data["header"]["author-name"];
571 if ($feed_data["header"]["author-nick"] != "")
572 $data["nick"] = $feed_data["header"]["author-nick"];
574 if ($feed_data["header"]["author-avatar"] != "")
575 $data["photo"] = $feed_data["header"]["author-avatar"];
577 if ($feed_data["header"]["author-id"] != "")
578 $data["alias"] = $feed_data["header"]["author-id"];
580 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
581 // So we take the value that we just fetched, although the other one worked as well
582 if ($feed_data["header"]["author-link"] != "")
583 $data["url"] = $feed_data["header"]["author-link"];
585 /// @todo Fetch location and "about" from the feed as well
589 private function pumpio_profile_data($profile) {
591 $doc = new DOMDocument();
592 if (!@$doc->loadHTMLFile($profile))
595 $xpath = new DomXPath($doc);
599 // This is ugly - but pump.io doesn't seem to know a better way for it
600 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
601 $pos = strpos($data["name"], chr(10));
603 $data["name"] = trim(substr($data["name"], 0, $pos));
605 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
607 foreach ($avatar->attributes as $attribute)
608 if ($attribute->name == "src")
609 $data["photo"] = trim($attribute->value);
611 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
612 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
617 private function pumpio($webfinger) {
619 foreach ($webfinger["links"] AS $link) {
620 if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
621 ($link["type"] == "text/html") AND ($link["href"] != ""))
622 $data["url"] = $link["href"];
623 elseif (($link["rel"] == "activity-inbox") AND ($link["href"] != ""))
624 $data["activity-inbox"] = $link["href"];
625 elseif (($link["rel"] == "activity-outbox") AND ($link["href"] != ""))
626 $data["activity-outbox"] = $link["href"];
627 elseif (($link["rel"] == "dialback") AND ($link["href"] != ""))
628 $data["dialback"] = $link["href"];
630 if (isset($data["activity-inbox"]) AND isset($data["activity-outbox"]) AND
631 isset($data["dialback"]) AND isset($data["url"])) {
633 // by now we use these fields only for the network type detection
634 // So we unset all data that isn't used at the moment
635 unset($data["activity-inbox"]);
636 unset($data["activity-outbox"]);
637 unset($data["dialback"]);
639 $data["network"] = NETWORK_PUMPIO;
643 $profile_data = self::pumpio_profile_data($data["url"]);
648 $data = array_merge($data, $profile_data);
653 private function feed($url) {
654 $feed = fetch_url($url);
655 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
660 if ($feed_data["header"]["author-name"] != "")
661 $data["name"] = $feed_data["header"]["author-name"];
663 if ($feed_data["header"]["author-nick"] != "")
664 $data["nick"] = $feed_data["header"]["author-nick"];
666 if ($feed_data["header"]["author-avatar"] != "")
667 $data["photo"] = $feed_data["header"]["author-avatar"];
669 if ($feed_data["header"]["author-id"] != "")
670 $data["alias"] = $feed_data["header"]["author-id"];
673 $data["poll"] = $url;
675 if ($feed_data["header"]["author-link"] != "")
676 $data["baseurl"] = $feed_data["header"]["author-link"];
678 $data["baseurl"] = $data["url"];
680 $data["network"] = NETWORK_FEED;
685 private function mail($uri) {
687 if (!validate_email($uri))
693 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
695 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
697 if(count($x) && count($r)) {
698 $mailbox = construct_mailbox_name($r[0]);
700 openssl_private_decrypt(hex2bin($r[0]['pass']), $password,$x[0]['prvkey']);
701 $mbox = email_connect($mailbox,$r[0]['user'], $password);
706 $msgs = email_poll($mbox, $uri);
707 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
714 $data["addr"] = $uri;
715 $data["network"] = NETWORK_MAIL;
716 $data["name"] = substr($uri, 0, strpos($uri,'@'));
717 $data["nick"] = $data["name"];
718 $data["photo"] = avatar_img($uri);
720 $phost = substr($uri, strpos($uri,'@') + 1);
721 $data["url"] = 'http://'.$phost."/".$data["nick"];
722 $data["notify"] = 'smtp '.random_string();
723 $data["poll"] = 'email '.random_string();
725 $x = email_msg_meta($mbox, $msgs[0]);
726 if(stristr($x[0]->from, $uri))
727 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
728 elseif(stristr($x[0]->to, $uri))
729 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
731 foreach($adr as $feadr) {
732 if((strcasecmp($feadr->mailbox, $data["name"]) == 0)
733 &&(strcasecmp($feadr->host, $phost) == 0)
734 && (strlen($feadr->personal))) {
736 $personal = imap_mime_header_decode($feadr->personal);
738 foreach($personal as $perspart)
739 if ($perspart->charset != "default")
740 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
742 $data["name"] .= $perspart->text;
744 $data["name"] = notags($data["name"]);