3 * @file src/Network/Probe.php
5 namespace Friendica\Network;
8 * @file src/Network/Probe.php
9 * @brief Functions for probing URL
13 use Friendica\Core\Cache;
14 use Friendica\Core\Config;
15 use Friendica\Core\Protocol;
16 use Friendica\Core\System;
17 use Friendica\Database\DBA;
18 use Friendica\Model\Contact;
19 use Friendica\Model\Profile;
20 use Friendica\Protocol\Email;
21 use Friendica\Protocol\Feed;
22 use Friendica\Util\Crypto;
23 use Friendica\Util\DateTimeFormat;
24 use Friendica\Util\Network;
25 use Friendica\Util\XML;
28 require_once 'include/dba.php';
31 * @brief This class contain functions for probing URL
36 private static $baseurl;
39 * @brief Rearrange the array so that it always has the same order
41 * @param array $data Unordered data
43 * @return array Ordered data
45 private static function rearrangeData($data)
47 $fields = ["name", "nick", "guid", "url", "addr", "alias",
48 "photo", "community", "keywords", "location", "about",
49 "batch", "notify", "poll", "request", "confirm", "poco",
50 "priority", "network", "pubkey", "baseurl"];
53 foreach ($fields as $field) {
54 if (isset($data[$field])) {
55 $newdata[$field] = $data[$field];
57 $newdata[$field] = "";
61 // We don't use the "priority" field anymore and replace it with a dummy.
62 $newdata["priority"] = 0;
68 * @brief Check if the hostname belongs to the own server
70 * @param string $host The hostname that is to be checked
72 * @return bool Does the testes hostname belongs to the own server?
74 private static function ownHost($host)
76 $own_host = get_app()->get_hostname();
78 $parts = parse_url($host);
80 if (!isset($parts['scheme'])) {
81 $parts = parse_url('http://'.$host);
84 if (!isset($parts['host'])) {
87 return $parts['host'] == $own_host;
91 * @brief Probes for webfinger path via "host-meta"
93 * We have to check if the servers in the future still will offer this.
94 * It seems as if it was dropped from the standard.
96 * @param string $host The host part of an url
98 * @return array with template and type of the webfinger template for JSON or XML
100 private static function hostMeta($host)
102 // Reset the static variable
105 $ssl_url = "https://".$host."/.well-known/host-meta";
106 $url = "http://".$host."/.well-known/host-meta";
108 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
111 logger("Probing for ".$host, LOGGER_DEBUG);
114 $ret = Network::curl($ssl_url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
115 if ($ret['success']) {
117 $xrd = XML::parseString($xml, false);
118 $host_url = 'https://'.$host;
121 if (!is_object($xrd)) {
122 $ret = Network::curl($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
123 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
124 logger("Probing timeout for ".$url, LOGGER_DEBUG);
128 $xrd = XML::parseString($xml, false);
129 $host_url = 'http://'.$host;
131 if (!is_object($xrd)) {
132 logger("No xrd object found for ".$host, LOGGER_DEBUG);
136 $links = XML::elementToArray($xrd);
137 if (!isset($links["xrd"]["link"])) {
138 logger("No xrd data found for ".$host, LOGGER_DEBUG);
143 // The following webfinger path is defined in RFC 7033 https://tools.ietf.org/html/rfc7033
144 // Problem is that Hubzilla currently doesn't provide all data in the JSON webfinger
145 // compared to the XML webfinger. So this is commented out by now.
146 // $lrdd = array("application/jrd+json" => $host_url.'/.well-known/webfinger?resource={uri}');
148 foreach ($links["xrd"]["link"] as $value => $link) {
149 if (!empty($link["@attributes"])) {
150 $attributes = $link["@attributes"];
151 } elseif ($value == "@attributes") {
157 if (($attributes["rel"] == "lrdd") && !empty($attributes["template"])) {
158 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
160 $lrdd[$type] = $attributes["template"];
164 self::$baseurl = "http://".$host;
166 logger("Probing successful for ".$host, LOGGER_DEBUG);
172 * @brief Perform Webfinger lookup and return DFRN data
174 * Given an email style address, perform webfinger lookup and
175 * return the resulting DFRN profile URL, or if no DFRN profile URL
176 * is located, returns an OStatus subscription template (prefixed
177 * with the string 'stat:' to identify it as on OStatus template).
178 * If this isn't an email style address just return $webbie.
179 * Return an empty string if email-style addresses but webfinger fails,
180 * or if the resultant personal XRD doesn't contain a supported
181 * subscription/friend-request attribute.
183 * amended 7/9/2011 to return an hcard which could save potentially loading
184 * a lengthy content page to scrape dfrn attributes
186 * @param string $webbie Address that should be probed
187 * @param string $hcard_url Link to the hcard - is returned by reference
189 * @return string profile link
191 public static function webfingerDfrn($webbie, &$hcard_url)
195 $links = self::lrdd($webbie);
196 logger('webfingerDfrn: '.$webbie.':'.print_r($links, true), LOGGER_DATA);
198 foreach ($links as $link) {
199 if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
200 $profile_link = $link['@attributes']['href'];
202 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) && ($profile_link == "")) {
203 $profile_link = 'stat:'.$link['@attributes']['template'];
205 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
206 $hcard_url = $link['@attributes']['href'];
210 return $profile_link;
214 * @brief Check an URI for LRDD data
216 * this is a replacement for the "lrdd" function.
217 * It isn't used in this class and has some redundancies in the code.
218 * When time comes we can check the existing calls for "lrdd" if we can rework them.
220 * @param string $uri Address that should be probed
222 * @return array uri data
224 public static function lrdd($uri)
226 $lrdd = self::hostMeta($uri);
229 if (is_bool($lrdd)) {
234 $parts = @parse_url($uri);
235 if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
239 $host = $parts["host"];
240 if (!empty($parts["port"])) {
241 $host .= ':'.$parts["port"];
244 $path_parts = explode("/", trim($parts["path"], "/"));
246 $nick = array_pop($path_parts);
249 $lrdd = self::hostMeta($host);
250 $host .= "/".array_shift($path_parts);
251 } while (!$lrdd && (sizeof($path_parts) > 0));
255 logger("No lrdd data found for ".$uri, LOGGER_DEBUG);
259 foreach ($lrdd as $type => $template) {
264 $path = str_replace('{uri}', urlencode($uri), $template);
265 $webfinger = self::webfinger($path, $type);
267 if (!$webfinger && (strstr($uri, "@"))) {
268 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
269 $webfinger = self::webfinger($path, $type);
272 // Special treatment for Mastodon
273 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
274 // But the webfinger for this format fails.
275 if (!$webfinger && !empty($nick)) {
276 // Mastodon uses a "@" as prefix for usernames in their url format
277 $nick = ltrim($nick, '@');
279 $addr = $nick."@".$host;
281 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
282 $webfinger = self::webfinger($path, $type);
286 if (!is_array($webfinger["links"])) {
287 logger("No webfinger links found for ".$uri, LOGGER_DEBUG);
293 foreach ($webfinger["links"] as $link) {
294 $data[] = ["@attributes" => $link];
297 if (is_array($webfinger["aliases"])) {
298 foreach ($webfinger["aliases"] as $alias) {
299 $data[] = ["@attributes" =>
309 * @brief Fetch information (protocol endpoints and user information) about a given uri
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)
314 * @param boolean $cache Use cached values?
316 * @return array uri data
318 public static function uri($uri, $network = "", $uid = -1, $cache = true)
321 $result = Cache::get("Probe::uri:".$network.":".$uri);
322 if (!is_null($result)) {
331 $data = self::detect($uri, $network, $uid);
333 if (!isset($data["url"])) {
337 if (x($data, "photo")) {
338 $data["baseurl"] = Network::getUrlMatch(normalise_link(defaults($data, "baseurl", "")), normalise_link($data["photo"]));
340 $data["photo"] = System::baseUrl().'/images/person-175.jpg';
343 if (empty($data["name"])) {
344 if (!empty($data["nick"])) {
345 $data["name"] = $data["nick"];
348 if (!x($data, "name")) {
349 $data["name"] = $data["url"];
353 if (empty($data["nick"])) {
354 $data["nick"] = strtolower($data["name"]);
356 if (strpos($data['nick'], ' ')) {
357 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
361 if (!empty(self::$baseurl)) {
362 $data["baseurl"] = self::$baseurl;
365 if (empty($data["network"])) {
366 $data["network"] = Protocol::PHANTOM;
369 $data = self::rearrangeData($data);
371 // Only store into the cache if the value seems to be valid
372 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
373 Cache::set("Probe::uri:".$network.":".$uri, $data, CACHE_DAY);
375 /// @todo temporary fix - we need a real contact update function that updates only changing fields
376 /// The biggest problem is the avatar picture that could have a reduced image size.
377 /// It should only be updated if the existing picture isn't existing anymore.
378 /// We only update the contact when it is no probing for a specific network.
379 if (($data['network'] != Protocol::FEED)
387 $fields = ['name' => $data['name'],
388 'nick' => $data['nick'],
389 'url' => $data['url'],
390 'addr' => $data['addr'],
391 'photo' => $data['photo'],
392 'keywords' => $data['keywords'],
393 'location' => $data['location'],
394 'about' => $data['about'],
395 'notify' => $data['notify'],
396 'network' => $data['network'],
397 'server_url' => $data['baseurl']];
399 // This doesn't cover the case when a community isn't a community anymore
400 if (!empty($data['community']) && $data['community']) {
401 $fields['community'] = $data['community'];
402 $fields['contact-type'] = Contact::ACCOUNT_TYPE_COMMUNITY;
407 foreach ($fields as $key => $val) {
409 unset($fields[$key]);
411 $fieldnames[] = $key;
415 $fields['updated'] = DateTimeFormat::utcNow();
417 $condition = ['nurl' => normalise_link($data["url"])];
419 $old_fields = DBA::selectFirst('gcontact', $fieldnames, $condition);
421 // When the gcontact doesn't exist, the value "true" will trigger an insert.
422 // In difference to the public contacts we want to have every contact
423 // in the world in our global contacts.
427 // These values have to be set only on insert
428 $fields['photo'] = $data['photo'];
429 $fields['created'] = DateTimeFormat::utcNow();
432 DBA::update('gcontact', $fields, $condition, $old_fields);
434 $fields = ['name' => $data['name'],
435 'nick' => $data['nick'],
436 'url' => $data['url'],
437 'addr' => $data['addr'],
438 'alias' => $data['alias'],
439 'keywords' => $data['keywords'],
440 'location' => $data['location'],
441 'about' => $data['about'],
442 'batch' => $data['batch'],
443 'notify' => $data['notify'],
444 'poll' => $data['poll'],
445 'request' => $data['request'],
446 'confirm' => $data['confirm'],
447 'poco' => $data['poco'],
448 'network' => $data['network'],
449 'pubkey' => $data['pubkey'],
450 'priority' => $data['priority'],
452 'rel' => Contact::SHARING];
456 foreach ($fields as $key => $val) {
458 unset($fields[$key]);
460 $fieldnames[] = $key;
464 $condition = ['nurl' => normalise_link($data["url"]), 'self' => false, 'uid' => 0];
466 // "$old_fields" will return a "false" when the contact doesn't exist.
467 // This won't trigger an insert. This is intended, since we only need
468 // public contacts for everyone we store items from.
469 // We don't need to store every contact on the planet.
470 $old_fields = DBA::selectFirst('contact', $fieldnames, $condition);
472 $fields['name-date'] = DateTimeFormat::utcNow();
473 $fields['uri-date'] = DateTimeFormat::utcNow();
474 $fields['success_update'] = DateTimeFormat::utcNow();
476 DBA::update('contact', $fields, $condition, $old_fields);
484 * @brief Switch the scheme of an url between http and https
486 * @param string $url URL
488 * @return string switched URL
490 private static function switchScheme($url)
492 $parts = parse_url($url);
494 if (!isset($parts['scheme'])) {
498 if ($parts['scheme'] == 'http') {
499 $url = str_replace('http://', 'https://', $url);
500 } elseif ($parts['scheme'] == 'https') {
501 $url = str_replace('https://', 'http://', $url);
508 * @brief Checks if a profile url should be OStatus but only provides partial information
510 * @param array $webfinger Webfinger data
511 * @param string $lrdd Path template for webfinger request
512 * @param string $type type
514 * @return array fixed webfinger data
516 private static function fixOStatus($webfinger, $lrdd, $type)
518 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
525 foreach ($webfinger['links'] as $link) {
526 if ($link['rel'] == NAMESPACE_OSTATUSSUB) {
529 if ($link['rel'] == 'magic-public-key') {
534 if (!$is_ostatus || $has_key) {
538 $url = self::switchScheme($webfinger['subject']);
539 $path = str_replace('{uri}', urlencode($url), $lrdd);
540 $webfinger2 = self::webfinger($path, $type);
542 // Is the new webfinger detectable as OStatus?
543 if (self::ostatus($webfinger2, true)) {
544 $webfinger = $webfinger2;
551 * @brief Fetch information (protocol endpoints and user information) about a given uri
553 * This function is only called by the "uri" function that adds caching and rearranging of data.
555 * @param string $uri Address that should be probed
556 * @param string $network Test for this specific network
557 * @param integer $uid User ID for the probe (only used for mails)
559 * @return array uri data
561 private static function detect($uri, $network, $uid)
563 $parts = parse_url($uri);
565 if (!empty($parts["scheme"]) && !empty($parts["host"]) && !empty($parts["path"])) {
566 $host = $parts["host"];
567 if (!empty($parts["port"])) {
568 $host .= ':'.$parts["port"];
571 if ($host == 'twitter.com') {
572 return ["network" => Protocol::TWITTER];
574 $lrdd = self::hostMeta($host);
576 if (is_bool($lrdd)) {
580 $path_parts = explode("/", trim($parts["path"], "/"));
582 while (!$lrdd && (sizeof($path_parts) > 1)) {
583 $host .= "/".array_shift($path_parts);
584 $lrdd = self::hostMeta($host);
587 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
588 return self::feed($uri);
590 $nick = array_pop($path_parts);
592 // Mastodon uses a "@" as prefix for usernames in their url format
593 $nick = ltrim($nick, '@');
595 $addr = $nick."@".$host;
596 } elseif (strstr($uri, '@')) {
597 // If the URI starts with "mailto:" then jump directly to the mail detection
598 if (strpos($uri, 'mailto:') !== false) {
599 $uri = str_replace('mailto:', '', $uri);
600 return self::mail($uri, $uid);
603 if ($network == Protocol::MAIL) {
604 return self::mail($uri, $uid);
606 // Remove "acct:" from the URI
607 $uri = str_replace('acct:', '', $uri);
609 $host = substr($uri, strpos($uri, '@') + 1);
610 $nick = substr($uri, 0, strpos($uri, '@'));
612 if (strpos($uri, '@twitter.com')) {
613 return ["network" => Protocol::TWITTER];
615 $lrdd = self::hostMeta($host);
617 if (is_bool($lrdd)) {
622 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
623 return self::mail($uri, $uid);
627 logger("Uri ".$uri." was not detectable", LOGGER_DEBUG);
633 /// @todo Do we need the prefix "acct:" or "acct://"?
635 foreach ($lrdd as $type => $template) {
640 // At first try it with the given uri
641 $path = str_replace('{uri}', urlencode($uri), $template);
642 $webfinger = self::webfinger($path, $type);
644 // Fix possible problems with GNU Social probing to wrong scheme
645 $webfinger = self::fixOStatus($webfinger, $template, $type);
647 // We cannot be sure that the detected address was correct, so we don't use the values
648 if ($webfinger && ($uri != $addr)) {
653 // Try webfinger with the address (user@domain.tld)
655 $path = str_replace('{uri}', urlencode($addr), $template);
656 $webfinger = self::webfinger($path, $type);
659 // Mastodon needs to have it with "acct:"
661 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
662 $webfinger = self::webfinger($path, $type);
667 return self::feed($uri);
672 logger("Probing ".$uri, LOGGER_DEBUG);
674 if (in_array($network, ["", Protocol::DFRN])) {
675 $result = self::dfrn($webfinger);
677 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
678 $result = self::diaspora($webfinger);
680 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
681 $result = self::ostatus($webfinger);
683 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
684 $result = self::pumpio($webfinger, $addr);
686 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
687 $result = self::feed($uri);
689 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
690 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
691 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
692 $result["nick"] = $nick;
695 if (empty($result["addr"]) && ($addr != "")) {
696 $result["addr"] = $addr;
700 if (empty($result["network"])) {
701 $result["network"] = Protocol::PHANTOM;
704 if (empty($result["url"])) {
705 $result["url"] = $uri;
708 logger($uri." is ".$result["network"], LOGGER_DEBUG);
710 if (empty($result["baseurl"])) {
711 $pos = strpos($result["url"], $host);
713 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
720 * @brief Perform a webfinger request.
722 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
724 * @param string $url Address that should be probed
725 * @param string $type type
727 * @return array webfinger data
729 private static function webfinger($url, $type)
731 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
734 $ret = Network::curl($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
735 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
738 $data = $ret['body'];
740 $webfinger = json_decode($data, true);
741 if (is_array($webfinger)) {
742 if (!isset($webfinger["links"])) {
743 logger("No json webfinger links for ".$url, LOGGER_DEBUG);
749 // If it is not JSON, maybe it is XML
750 $xrd = XML::parseString($data, false);
751 if (!is_object($xrd)) {
752 logger("No webfinger data retrievable for ".$url, LOGGER_DEBUG);
756 $xrd_arr = XML::elementToArray($xrd);
757 if (!isset($xrd_arr["xrd"]["link"])) {
758 logger("No XML webfinger links for ".$url, LOGGER_DEBUG);
764 if (!empty($xrd_arr["xrd"]["subject"])) {
765 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
768 if (!empty($xrd_arr["xrd"]["alias"])) {
769 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
772 $webfinger["links"] = [];
774 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
775 if (!empty($data["@attributes"])) {
776 $attributes = $data["@attributes"];
777 } elseif ($value == "@attributes") {
783 $webfinger["links"][] = $attributes;
789 * @brief Poll the Friendica specific noscrape page.
791 * "noscrape" is a faster alternative to fetch the data from the hcard.
792 * This functionality was originally created for the directory.
794 * @param string $noscrape_url Link to the noscrape page
795 * @param array $data The already fetched data
797 * @return array noscrape data
799 private static function pollNoscrape($noscrape_url, $data)
801 $ret = Network::curl($noscrape_url);
802 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
805 $content = $ret['body'];
807 logger("Empty body for ".$noscrape_url, LOGGER_DEBUG);
811 $json = json_decode($content, true);
812 if (!is_array($json)) {
813 logger("No json data for ".$noscrape_url, LOGGER_DEBUG);
817 if (!empty($json["fn"])) {
818 $data["name"] = $json["fn"];
821 if (!empty($json["addr"])) {
822 $data["addr"] = $json["addr"];
825 if (!empty($json["nick"])) {
826 $data["nick"] = $json["nick"];
829 if (!empty($json["guid"])) {
830 $data["guid"] = $json["guid"];
833 if (!empty($json["comm"])) {
834 $data["community"] = $json["comm"];
837 if (!empty($json["tags"])) {
838 $keywords = implode(" ", $json["tags"]);
839 if ($keywords != "") {
840 $data["keywords"] = $keywords;
844 $location = Profile::formatLocation($json);
846 $data["location"] = $location;
849 if (!empty($json["about"])) {
850 $data["about"] = $json["about"];
853 if (!empty($json["key"])) {
854 $data["pubkey"] = $json["key"];
857 if (!empty($json["photo"])) {
858 $data["photo"] = $json["photo"];
861 if (!empty($json["dfrn-request"])) {
862 $data["request"] = $json["dfrn-request"];
865 if (!empty($json["dfrn-confirm"])) {
866 $data["confirm"] = $json["dfrn-confirm"];
869 if (!empty($json["dfrn-notify"])) {
870 $data["notify"] = $json["dfrn-notify"];
873 if (!empty($json["dfrn-poll"])) {
874 $data["poll"] = $json["dfrn-poll"];
881 * @brief Check for valid DFRN data
883 * @param array $data DFRN data
885 * @return int Number of errors
887 public static function validDfrn($data)
890 if (!isset($data['key'])) {
893 if (!isset($data['dfrn-request'])) {
896 if (!isset($data['dfrn-confirm'])) {
899 if (!isset($data['dfrn-notify'])) {
902 if (!isset($data['dfrn-poll'])) {
909 * @brief Fetch data from a DFRN profile page and via "noscrape"
911 * @param string $profile_link Link to the profile page
913 * @return array profile data
915 public static function profile($profile_link)
919 logger("Check profile ".$profile_link, LOGGER_DEBUG);
921 // Fetch data via noscrape - this is faster
922 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
923 $data = self::pollNoscrape($noscrape_url, $data);
925 if (!isset($data["notify"])
926 || !isset($data["confirm"])
927 || !isset($data["request"])
928 || !isset($data["poll"])
929 || !isset($data["name"])
930 || !isset($data["photo"])
932 $data = self::pollHcard($profile_link, $data, true);
936 $prof_data["addr"] = $data["addr"];
937 $prof_data["nick"] = $data["nick"];
938 $prof_data["dfrn-request"] = $data["request"];
939 $prof_data["dfrn-confirm"] = $data["confirm"];
940 $prof_data["dfrn-notify"] = $data["notify"];
941 $prof_data["dfrn-poll"] = $data["poll"];
942 $prof_data["photo"] = $data["photo"];
943 $prof_data["fn"] = $data["name"];
944 $prof_data["key"] = $data["pubkey"];
946 logger("Result for profile ".$profile_link.": ".print_r($prof_data, true), LOGGER_DEBUG);
952 * @brief Check for DFRN contact
954 * @param array $webfinger Webfinger data
956 * @return array DFRN data
958 private static function dfrn($webfinger)
962 foreach ($webfinger["links"] as $link) {
963 if (($link["rel"] == NAMESPACE_DFRN) && ($link["href"] != "")) {
964 $data["network"] = Protocol::DFRN;
965 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
966 $data["poll"] = $link["href"];
967 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
968 $data["url"] = $link["href"];
969 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
970 $hcard_url = $link["href"];
971 } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
972 $data["poco"] = $link["href"];
973 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && ($link["href"] != "")) {
974 $data["photo"] = $link["href"];
975 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
976 $data["baseurl"] = trim($link["href"], '/');
977 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
978 $data["guid"] = $link["href"];
979 } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
980 $data["pubkey"] = base64_decode($link["href"]);
982 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
983 if (strstr($data["pubkey"], 'RSA ')) {
984 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
989 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
990 foreach ($webfinger["aliases"] as $alias) {
991 if (empty($data["url"]) && !strstr($alias, "@")) {
992 $data["url"] = $alias;
993 } elseif (!strstr($alias, "@") && normalise_link($alias) != normalise_link($data["url"])) {
994 $data["alias"] = $alias;
995 } elseif (substr($alias, 0, 5) == 'acct:') {
996 $data["addr"] = substr($alias, 5);
1001 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1002 $data["addr"] = substr($webfinger["subject"], 5);
1005 if (!isset($data["network"]) || ($hcard_url == "")) {
1009 // Fetch data via noscrape - this is faster
1010 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1011 $data = self::pollNoscrape($noscrape_url, $data);
1013 if (isset($data["notify"])
1014 && isset($data["confirm"])
1015 && isset($data["request"])
1016 && isset($data["poll"])
1017 && isset($data["name"])
1018 && isset($data["photo"])
1023 $data = self::pollHcard($hcard_url, $data, true);
1029 * @brief Poll the hcard page (Diaspora and Friendica specific)
1031 * @param string $hcard_url Link to the hcard page
1032 * @param array $data The already fetched data
1033 * @param boolean $dfrn Poll DFRN specific data
1035 * @return array hcard data
1037 private static function pollHcard($hcard_url, $data, $dfrn = false)
1039 $ret = Network::curl($hcard_url);
1040 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1043 $content = $ret['body'];
1048 $doc = new DOMDocument();
1049 if (!@$doc->loadHTML($content)) {
1053 $xpath = new DomXPath($doc);
1055 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1056 if (!is_object($vcards)) {
1060 if (!isset($data["baseurl"])) {
1061 $data["baseurl"] = "";
1064 if ($vcards->length > 0) {
1065 $vcard = $vcards->item(0);
1067 // We have to discard the guid from the hcard in favour of the guid from lrdd
1068 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1069 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1070 if (($search->length > 0) && empty($data["guid"])) {
1071 $data["guid"] = $search->item(0)->nodeValue;
1074 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1075 if ($search->length > 0) {
1076 $data["nick"] = $search->item(0)->nodeValue;
1079 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1080 if ($search->length > 0) {
1081 $data["name"] = $search->item(0)->nodeValue;
1084 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1085 if ($search->length > 0) {
1086 $data["searchable"] = $search->item(0)->nodeValue;
1089 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1090 if ($search->length > 0) {
1091 $data["pubkey"] = $search->item(0)->nodeValue;
1092 if (strstr($data["pubkey"], 'RSA ')) {
1093 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1097 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1098 if ($search->length > 0) {
1099 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1104 if (!empty($vcard)) {
1105 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1106 foreach ($photos as $photo) {
1108 foreach ($photo->attributes as $attribute) {
1109 $attr[$attribute->name] = trim($attribute->value);
1112 if (isset($attr["src"]) && isset($attr["width"])) {
1113 $avatar[$attr["width"]] = $attr["src"];
1116 // We don't have a width. So we just take everything that we got.
1117 // This is a Hubzilla workaround which doesn't send a width.
1118 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1119 $avatar[] = $attr["src"];
1124 if (sizeof($avatar)) {
1126 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1130 // Poll DFRN specific data
1131 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1132 if ($search->length > 0) {
1133 foreach ($search as $link) {
1134 //$data["request"] = $search->item(0)->nodeValue;
1136 foreach ($link->attributes as $attribute) {
1137 $attr[$attribute->name] = trim($attribute->value);
1140 $data[substr($attr["rel"], 5)] = $attr["href"];
1144 // Older Friendica versions had used the "uid" field differently than newer versions
1145 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1146 unset($data["guid"]);
1155 * @brief Check for Diaspora contact
1157 * @param array $webfinger Webfinger data
1159 * @return array Diaspora data
1161 private static function diaspora($webfinger)
1165 foreach ($webfinger["links"] as $link) {
1166 if (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
1167 $hcard_url = $link["href"];
1168 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
1169 $data["baseurl"] = trim($link["href"], '/');
1170 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
1171 $data["guid"] = $link["href"];
1172 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
1173 $data["url"] = $link["href"];
1174 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1175 $data["poll"] = $link["href"];
1176 } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
1177 $data["poco"] = $link["href"];
1178 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1179 $data["notify"] = $link["href"];
1180 } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
1181 $data["pubkey"] = base64_decode($link["href"]);
1183 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1184 if (strstr($data["pubkey"], 'RSA ')) {
1185 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1190 if (!isset($data["url"]) || ($hcard_url == "")) {
1194 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1195 foreach ($webfinger["aliases"] as $alias) {
1196 if (normalise_link($alias) != normalise_link($data["url"]) && ! strstr($alias, "@")) {
1197 $data["alias"] = $alias;
1198 } elseif (substr($alias, 0, 5) == 'acct:') {
1199 $data["addr"] = substr($alias, 5);
1204 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1205 $data["addr"] = substr($webfinger["subject"], 5);
1208 // Fetch further information from the hcard
1209 $data = self::pollHcard($hcard_url, $data);
1215 if (isset($data["url"])
1216 && isset($data["guid"])
1217 && isset($data["baseurl"])
1218 && isset($data["pubkey"])
1219 && ($hcard_url != "")
1221 $data["network"] = Protocol::DIASPORA;
1223 // The Diaspora handle must always be lowercase
1224 if (!empty($data["addr"])) {
1225 $data["addr"] = strtolower($data["addr"]);
1228 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1229 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1230 $data["batch"] = $data["baseurl"] . "/receive/public";
1239 * @brief Check for OStatus contact
1241 * @param array $webfinger Webfinger data
1242 * @param bool $short Short detection mode
1244 * @return array|bool OStatus data or "false" on error or "true" on short mode
1246 private static function ostatus($webfinger, $short = false)
1250 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1251 foreach ($webfinger["aliases"] as $alias) {
1252 if (strstr($alias, "@") && !strstr(normalise_link($alias), "http://")) {
1253 $data["addr"] = str_replace('acct:', '', $alias);
1258 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1259 && !strstr(normalise_link($webfinger["subject"]), "http://")
1261 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1265 if (is_array($webfinger["links"])) {
1266 foreach ($webfinger["links"] as $link) {
1267 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1268 && ($link["type"] == "text/html")
1269 && ($link["href"] != "")
1271 $data["url"] = $link["href"];
1272 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1273 $data["notify"] = $link["href"];
1274 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1275 $data["poll"] = $link["href"];
1276 } elseif (($link["rel"] == "magic-public-key") && ($link["href"] != "")) {
1277 $pubkey = $link["href"];
1279 if (substr($pubkey, 0, 5) === 'data:') {
1280 if (strstr($pubkey, ',')) {
1281 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1283 $pubkey = substr($pubkey, 5);
1285 } elseif (normalise_link($pubkey) == 'http://') {
1286 $ret = Network::curl($pubkey);
1287 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1290 $pubkey = $ret['body'];
1293 $key = explode(".", $pubkey);
1295 if (sizeof($key) >= 3) {
1296 $m = base64url_decode($key[1]);
1297 $e = base64url_decode($key[2]);
1298 $data["pubkey"] = Crypto::meToPem($m, $e);
1304 if (isset($data["notify"]) && isset($data["pubkey"])
1305 && isset($data["poll"])
1306 && isset($data["url"])
1308 $data["network"] = Protocol::OSTATUS;
1317 // Fetch all additional data from the feed
1318 $ret = Network::curl($data["poll"]);
1319 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1322 $feed = $ret['body'];
1326 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1331 if (!empty($feed_data["header"]["author-name"])) {
1332 $data["name"] = $feed_data["header"]["author-name"];
1334 if (!empty($feed_data["header"]["author-nick"])) {
1335 $data["nick"] = $feed_data["header"]["author-nick"];
1337 if (!empty($feed_data["header"]["author-avatar"])) {
1338 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1340 if (!empty($feed_data["header"]["author-id"])) {
1341 $data["alias"] = $feed_data["header"]["author-id"];
1343 if (!empty($feed_data["header"]["author-location"])) {
1344 $data["location"] = $feed_data["header"]["author-location"];
1346 if (!empty($feed_data["header"]["author-about"])) {
1347 $data["about"] = $feed_data["header"]["author-about"];
1349 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1350 // So we take the value that we just fetched, although the other one worked as well
1351 if (!empty($feed_data["header"]["author-link"])) {
1352 $data["url"] = $feed_data["header"]["author-link"];
1355 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1356 $data['url'] = $data["alias"];
1357 $data["alias"] = '';
1360 /// @todo Fetch location and "about" from the feed as well
1365 * @brief Fetch data from a pump.io profile page
1367 * @param string $profile_link Link to the profile page
1369 * @return array profile data
1371 private static function pumpioProfileData($profile_link)
1373 $doc = new DOMDocument();
1374 if (!@$doc->loadHTMLFile($profile_link)) {
1378 $xpath = new DomXPath($doc);
1382 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1384 if ($data["name"] == '') {
1385 // This is ugly - but pump.io doesn't seem to know a better way for it
1386 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1387 $pos = strpos($data["name"], chr(10));
1389 $data["name"] = trim(substr($data["name"], 0, $pos));
1393 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1395 if ($data["location"] == '') {
1396 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1399 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1401 if ($data["about"] == '') {
1402 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1405 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1407 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1410 foreach ($avatar->attributes as $attribute) {
1411 if ($attribute->name == "src") {
1412 $data["photo"] = trim($attribute->value);
1421 * @brief Check for pump.io contact
1423 * @param array $webfinger Webfinger data
1425 * @return array pump.io data
1427 private static function pumpio($webfinger, $addr)
1430 foreach ($webfinger["links"] as $link) {
1431 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1432 && ($link["type"] == "text/html")
1433 && ($link["href"] != "")
1435 $data["url"] = $link["href"];
1436 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1437 $data["notify"] = $link["href"];
1438 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1439 $data["poll"] = $link["href"];
1440 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1441 $data["dialback"] = $link["href"];
1444 if (isset($data["poll"]) && isset($data["notify"])
1445 && isset($data["dialback"])
1446 && isset($data["url"])
1448 // by now we use these fields only for the network type detection
1449 // So we unset all data that isn't used at the moment
1450 unset($data["dialback"]);
1452 $data["network"] = Protocol::PUMPIO;
1457 $profile_data = self::pumpioProfileData($data["url"]);
1459 if (!$profile_data) {
1463 $data = array_merge($data, $profile_data);
1465 if (($addr != '') && ($data['name'] != '')) {
1466 $name = trim(str_replace($addr, '', $data['name']));
1468 $data['name'] = $name;
1476 * @brief Check page for feed link
1478 * @param string $url Page link
1480 * @return string feed link
1482 private static function getFeedLink($url)
1484 $doc = new DOMDocument();
1486 if (!@$doc->loadHTMLFile($url)) {
1490 $xpath = new DomXPath($doc);
1492 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1493 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1494 if (!is_object($feeds)) {
1498 if ($feeds->length == 0) {
1504 foreach ($feeds as $feed) {
1506 foreach ($feed->attributes as $attribute) {
1507 $attr[$attribute->name] = trim($attribute->value);
1510 if ($feed_url == "") {
1511 $feed_url = $attr["href"];
1519 * @brief Check for feed contact
1521 * @param string $url Profile link
1522 * @param boolean $probe Do a probe if the page contains a feed link
1524 * @return array feed data
1526 private static function feed($url, $probe = true)
1528 $ret = Network::curl($url);
1529 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1532 $feed = $ret['body'];
1533 $dummy1 = $dummy2 = $dummy3 = null;
1534 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1541 $feed_url = self::getFeedLink($url);
1547 return self::feed($feed_url, false);
1550 if (!empty($feed_data["header"]["author-name"])) {
1551 $data["name"] = $feed_data["header"]["author-name"];
1554 if (!empty($feed_data["header"]["author-nick"])) {
1555 $data["nick"] = $feed_data["header"]["author-nick"];
1558 if (!empty($feed_data["header"]["author-avatar"])) {
1559 $data["photo"] = $feed_data["header"]["author-avatar"];
1562 if (!empty($feed_data["header"]["author-id"])) {
1563 $data["alias"] = $feed_data["header"]["author-id"];
1566 $data["url"] = $url;
1567 $data["poll"] = $url;
1569 if (!empty($feed_data["header"]["author-link"])) {
1570 $data["baseurl"] = $feed_data["header"]["author-link"];
1572 $data["baseurl"] = $data["url"];
1575 $data["network"] = Protocol::FEED;
1581 * @brief Check for mail contact
1583 * @param string $uri Profile link
1584 * @param integer $uid User ID
1586 * @return array mail data
1588 private static function mail($uri, $uid)
1590 if (!Network::isEmailDomainValid($uri)) {
1598 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1600 $condition = ["`uid` = ? AND `server` != ''", $uid];
1601 $mailacct = DBA::selectFirst('mailacct', ['pass', 'user'], $condition);
1603 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1607 $mailbox = Email::constructMailboxName($mailacct);
1609 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1610 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1615 $msgs = Email::poll($mbox, $uri);
1616 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1618 if (!count($msgs)) {
1622 $phost = substr($uri, strpos($uri, '@') + 1);
1625 $data["addr"] = $uri;
1626 $data["network"] = Protocol::MAIL;
1627 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1628 $data["nick"] = $data["name"];
1629 $data["photo"] = Network::lookupAvatarByEmail($uri);
1630 $data["url"] = 'mailto:'.$uri;
1631 $data["notify"] = 'smtp '.random_string();
1632 $data["poll"] = 'email '.random_string();
1634 $x = Email::messageMeta($mbox, $msgs[0]);
1635 if (stristr($x[0]->from, $uri)) {
1636 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1637 } elseif (stristr($x[0]->to, $uri)) {
1638 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1641 foreach ($adr as $feadr) {
1642 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1643 &&(strcasecmp($feadr->host, $phost) == 0)
1644 && (strlen($feadr->personal))
1646 $personal = imap_mime_header_decode($feadr->personal);
1648 foreach ($personal as $perspart) {
1649 if ($perspart->charset != "default") {
1650 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1652 $data["name"] .= $perspart->text;
1656 $data["name"] = notags($data["name"]);
1660 if (!empty($mbox)) {
1667 * @brief Mix two paths together to possibly fix missing parts
1669 * @param string $avatar Path to the avatar
1670 * @param string $base Another path that is hopefully complete
1672 * @return string fixed avatar path
1674 public static function fixAvatar($avatar, $base)
1676 $base_parts = parse_url($base);
1678 // Remove all parts that could create a problem
1679 unset($base_parts['path']);
1680 unset($base_parts['query']);
1681 unset($base_parts['fragment']);
1683 $avatar_parts = parse_url($avatar);
1686 $parts = array_merge($base_parts, $avatar_parts);
1688 // And put them together again
1689 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1690 $host = isset($parts['host']) ? $parts['host'] : '';
1691 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1692 $path = isset($parts['path']) ? $parts['path'] : '';
1693 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1694 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1696 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1698 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);