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\Protocol\ActivityPub;
23 use Friendica\Util\Crypto;
24 use Friendica\Util\DateTimeFormat;
25 use Friendica\Util\Network;
26 use Friendica\Util\XML;
29 require_once 'include/dba.php';
32 * @brief This class contain functions for probing URL
37 private static $baseurl;
40 * @brief Rearrange the array so that it always has the same order
42 * @param array $data Unordered data
44 * @return array Ordered data
46 private static function rearrangeData($data)
48 $fields = ["name", "nick", "guid", "url", "addr", "alias",
49 "photo", "community", "keywords", "location", "about",
50 "batch", "notify", "poll", "request", "confirm", "poco",
51 "priority", "network", "pubkey", "baseurl"];
54 foreach ($fields as $field) {
55 if (isset($data[$field])) {
56 $newdata[$field] = $data[$field];
58 $newdata[$field] = "";
62 // We don't use the "priority" field anymore and replace it with a dummy.
63 $newdata["priority"] = 0;
69 * @brief Check if the hostname belongs to the own server
71 * @param string $host The hostname that is to be checked
73 * @return bool Does the testes hostname belongs to the own server?
75 private static function ownHost($host)
77 $own_host = get_app()->get_hostname();
79 $parts = parse_url($host);
81 if (!isset($parts['scheme'])) {
82 $parts = parse_url('http://'.$host);
85 if (!isset($parts['host'])) {
88 return $parts['host'] == $own_host;
92 * @brief Probes for webfinger path via "host-meta"
94 * We have to check if the servers in the future still will offer this.
95 * It seems as if it was dropped from the standard.
97 * @param string $host The host part of an url
99 * @return array with template and type of the webfinger template for JSON or XML
101 private static function hostMeta($host)
103 // Reset the static variable
106 $ssl_url = "https://".$host."/.well-known/host-meta";
107 $url = "http://".$host."/.well-known/host-meta";
109 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
112 logger("Probing for ".$host, LOGGER_DEBUG);
115 $ret = Network::curl($ssl_url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
116 if ($ret['success']) {
118 $xrd = XML::parseString($xml, false);
119 $host_url = 'https://'.$host;
122 if (!is_object($xrd)) {
123 $ret = Network::curl($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
124 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
125 logger("Probing timeout for ".$url, LOGGER_DEBUG);
129 $xrd = XML::parseString($xml, false);
130 $host_url = 'http://'.$host;
132 if (!is_object($xrd)) {
133 logger("No xrd object found for ".$host, LOGGER_DEBUG);
137 $links = XML::elementToArray($xrd);
138 if (!isset($links["xrd"]["link"])) {
139 logger("No xrd data found for ".$host, LOGGER_DEBUG);
144 // The following webfinger path is defined in RFC 7033 https://tools.ietf.org/html/rfc7033
145 // Problem is that Hubzilla currently doesn't provide all data in the JSON webfinger
146 // compared to the XML webfinger. So this is commented out by now.
147 // $lrdd = array("application/jrd+json" => $host_url.'/.well-known/webfinger?resource={uri}');
149 foreach ($links["xrd"]["link"] as $value => $link) {
150 if (!empty($link["@attributes"])) {
151 $attributes = $link["@attributes"];
152 } elseif ($value == "@attributes") {
158 if (($attributes["rel"] == "lrdd") && !empty($attributes["template"])) {
159 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
161 $lrdd[$type] = $attributes["template"];
165 self::$baseurl = "http://".$host;
167 logger("Probing successful for ".$host, LOGGER_DEBUG);
173 * @brief Perform Webfinger lookup and return DFRN data
175 * Given an email style address, perform webfinger lookup and
176 * return the resulting DFRN profile URL, or if no DFRN profile URL
177 * is located, returns an OStatus subscription template (prefixed
178 * with the string 'stat:' to identify it as on OStatus template).
179 * If this isn't an email style address just return $webbie.
180 * Return an empty string if email-style addresses but webfinger fails,
181 * or if the resultant personal XRD doesn't contain a supported
182 * subscription/friend-request attribute.
184 * amended 7/9/2011 to return an hcard which could save potentially loading
185 * a lengthy content page to scrape dfrn attributes
187 * @param string $webbie Address that should be probed
188 * @param string $hcard_url Link to the hcard - is returned by reference
190 * @return string profile link
192 public static function webfingerDfrn($webbie, &$hcard_url)
196 $links = self::lrdd($webbie);
197 logger('webfingerDfrn: '.$webbie.':'.print_r($links, true), LOGGER_DATA);
199 foreach ($links as $link) {
200 if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
201 $profile_link = $link['@attributes']['href'];
203 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) && ($profile_link == "")) {
204 $profile_link = 'stat:'.$link['@attributes']['template'];
206 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
207 $hcard_url = $link['@attributes']['href'];
211 return $profile_link;
215 * @brief Check an URI for LRDD data
217 * this is a replacement for the "lrdd" function.
218 * It isn't used in this class and has some redundancies in the code.
219 * When time comes we can check the existing calls for "lrdd" if we can rework them.
221 * @param string $uri Address that should be probed
223 * @return array uri data
225 public static function lrdd($uri)
227 $lrdd = self::hostMeta($uri);
230 if (is_bool($lrdd)) {
235 $parts = @parse_url($uri);
236 if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
240 $host = $parts["host"];
241 if (!empty($parts["port"])) {
242 $host .= ':'.$parts["port"];
245 $path_parts = explode("/", trim($parts["path"], "/"));
247 $nick = array_pop($path_parts);
250 $lrdd = self::hostMeta($host);
251 $host .= "/".array_shift($path_parts);
252 } while (!$lrdd && (sizeof($path_parts) > 0));
256 logger("No lrdd data found for ".$uri, LOGGER_DEBUG);
260 foreach ($lrdd as $type => $template) {
265 $path = str_replace('{uri}', urlencode($uri), $template);
266 $webfinger = self::webfinger($path, $type);
268 if (!$webfinger && (strstr($uri, "@"))) {
269 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
270 $webfinger = self::webfinger($path, $type);
273 // Special treatment for Mastodon
274 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
275 // But the webfinger for this format fails.
276 if (!$webfinger && !empty($nick)) {
277 // Mastodon uses a "@" as prefix for usernames in their url format
278 $nick = ltrim($nick, '@');
280 $addr = $nick."@".$host;
282 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
283 $webfinger = self::webfinger($path, $type);
287 if (!is_array($webfinger["links"])) {
288 logger("No webfinger links found for ".$uri, LOGGER_DEBUG);
294 foreach ($webfinger["links"] as $link) {
295 $data[] = ["@attributes" => $link];
298 if (is_array($webfinger["aliases"])) {
299 foreach ($webfinger["aliases"] as $alias) {
300 $data[] = ["@attributes" =>
310 * @brief Fetch information (protocol endpoints and user information) about a given uri
312 * @param string $uri Address that should be probed
313 * @param string $network Test for this specific network
314 * @param integer $uid User ID for the probe (only used for mails)
315 * @param boolean $cache Use cached values?
317 * @return array uri data
319 public static function uri($uri, $network = "", $uid = -1, $cache = true)
322 $result = Cache::get("Probe::uri:".$network.":".$uri);
323 if (!is_null($result)) {
332 if ($network != Protocol::ACTIVITYPUB) {
333 $data = self::detect($uri, $network, $uid);
338 if (in_array(defaults($data, 'network', ''), ['', Protocol::PHANTOM])) {
339 $ap_profile = ActivityPub::fetchProfile($uri);
340 if (!empty($ap_profile) && ($ap_profile['network'] == Protocol::ACTIVITYPUB)) {
345 if (!isset($data["url"])) {
349 if (x($data, "photo")) {
350 $data["baseurl"] = Network::getUrlMatch(normalise_link(defaults($data, "baseurl", "")), normalise_link($data["photo"]));
352 $data["photo"] = System::baseUrl().'/images/person-175.jpg';
355 if (empty($data["name"])) {
356 if (!empty($data["nick"])) {
357 $data["name"] = $data["nick"];
360 if (!x($data, "name")) {
361 $data["name"] = $data["url"];
365 if (empty($data["nick"])) {
366 $data["nick"] = strtolower($data["name"]);
368 if (strpos($data['nick'], ' ')) {
369 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
373 if (!empty(self::$baseurl)) {
374 $data["baseurl"] = self::$baseurl;
377 if (empty($data["network"])) {
378 $data["network"] = Protocol::PHANTOM;
381 $data = self::rearrangeData($data);
383 // Only store into the cache if the value seems to be valid
384 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
385 Cache::set("Probe::uri:".$network.":".$uri, $data, CACHE_DAY);
387 /// @todo temporary fix - we need a real contact update function that updates only changing fields
388 /// The biggest problem is the avatar picture that could have a reduced image size.
389 /// It should only be updated if the existing picture isn't existing anymore.
390 /// We only update the contact when it is no probing for a specific network.
391 if (($data['network'] != Protocol::FEED)
399 $fields = ['name' => $data['name'],
400 'nick' => $data['nick'],
401 'url' => $data['url'],
402 'addr' => $data['addr'],
403 'photo' => $data['photo'],
404 'keywords' => $data['keywords'],
405 'location' => $data['location'],
406 'about' => $data['about'],
407 'notify' => $data['notify'],
408 'network' => $data['network'],
409 'server_url' => $data['baseurl']];
411 // This doesn't cover the case when a community isn't a community anymore
412 if (!empty($data['community']) && $data['community']) {
413 $fields['community'] = $data['community'];
414 $fields['contact-type'] = Contact::ACCOUNT_TYPE_COMMUNITY;
419 foreach ($fields as $key => $val) {
421 unset($fields[$key]);
423 $fieldnames[] = $key;
427 $fields['updated'] = DateTimeFormat::utcNow();
429 $condition = ['nurl' => normalise_link($data["url"])];
431 $old_fields = DBA::selectFirst('gcontact', $fieldnames, $condition);
433 // When the gcontact doesn't exist, the value "true" will trigger an insert.
434 // In difference to the public contacts we want to have every contact
435 // in the world in our global contacts.
439 // These values have to be set only on insert
440 $fields['photo'] = $data['photo'];
441 $fields['created'] = DateTimeFormat::utcNow();
444 DBA::update('gcontact', $fields, $condition, $old_fields);
446 $fields = ['name' => $data['name'],
447 'nick' => $data['nick'],
448 'url' => $data['url'],
449 'addr' => $data['addr'],
450 'alias' => $data['alias'],
451 'keywords' => $data['keywords'],
452 'location' => $data['location'],
453 'about' => $data['about'],
454 'batch' => $data['batch'],
455 'notify' => $data['notify'],
456 'poll' => $data['poll'],
457 'request' => $data['request'],
458 'confirm' => $data['confirm'],
459 'poco' => $data['poco'],
460 'network' => $data['network'],
461 'pubkey' => $data['pubkey'],
462 'priority' => $data['priority'],
464 'rel' => Contact::SHARING];
468 foreach ($fields as $key => $val) {
470 unset($fields[$key]);
472 $fieldnames[] = $key;
476 $condition = ['nurl' => normalise_link($data["url"]), 'self' => false, 'uid' => 0];
478 // "$old_fields" will return a "false" when the contact doesn't exist.
479 // This won't trigger an insert. This is intended, since we only need
480 // public contacts for everyone we store items from.
481 // We don't need to store every contact on the planet.
482 $old_fields = DBA::selectFirst('contact', $fieldnames, $condition);
484 $fields['name-date'] = DateTimeFormat::utcNow();
485 $fields['uri-date'] = DateTimeFormat::utcNow();
486 $fields['success_update'] = DateTimeFormat::utcNow();
488 DBA::update('contact', $fields, $condition, $old_fields);
496 * @brief Switch the scheme of an url between http and https
498 * @param string $url URL
500 * @return string switched URL
502 private static function switchScheme($url)
504 $parts = parse_url($url);
506 if (!isset($parts['scheme'])) {
510 if ($parts['scheme'] == 'http') {
511 $url = str_replace('http://', 'https://', $url);
512 } elseif ($parts['scheme'] == 'https') {
513 $url = str_replace('https://', 'http://', $url);
520 * @brief Checks if a profile url should be OStatus but only provides partial information
522 * @param array $webfinger Webfinger data
523 * @param string $lrdd Path template for webfinger request
524 * @param string $type type
526 * @return array fixed webfinger data
528 private static function fixOStatus($webfinger, $lrdd, $type)
530 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
537 foreach ($webfinger['links'] as $link) {
538 if ($link['rel'] == NAMESPACE_OSTATUSSUB) {
541 if ($link['rel'] == 'magic-public-key') {
546 if (!$is_ostatus || $has_key) {
550 $url = self::switchScheme($webfinger['subject']);
551 $path = str_replace('{uri}', urlencode($url), $lrdd);
552 $webfinger2 = self::webfinger($path, $type);
554 // Is the new webfinger detectable as OStatus?
555 if (self::ostatus($webfinger2, true)) {
556 $webfinger = $webfinger2;
563 * @brief Fetch information (protocol endpoints and user information) about a given uri
565 * This function is only called by the "uri" function that adds caching and rearranging of data.
567 * @param string $uri Address that should be probed
568 * @param string $network Test for this specific network
569 * @param integer $uid User ID for the probe (only used for mails)
571 * @return array uri data
573 private static function detect($uri, $network, $uid)
575 $parts = parse_url($uri);
577 if (!empty($parts["scheme"]) && !empty($parts["host"]) && !empty($parts["path"])) {
578 $host = $parts["host"];
579 if (!empty($parts["port"])) {
580 $host .= ':'.$parts["port"];
583 if ($host == 'twitter.com') {
584 return ["network" => Protocol::TWITTER];
586 $lrdd = self::hostMeta($host);
588 if (is_bool($lrdd)) {
592 $path_parts = explode("/", trim($parts["path"], "/"));
594 while (!$lrdd && (sizeof($path_parts) > 1)) {
595 $host .= "/".array_shift($path_parts);
596 $lrdd = self::hostMeta($host);
599 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
600 return self::feed($uri);
602 $nick = array_pop($path_parts);
604 // Mastodon uses a "@" as prefix for usernames in their url format
605 $nick = ltrim($nick, '@');
607 $addr = $nick."@".$host;
608 } elseif (strstr($uri, '@')) {
609 // If the URI starts with "mailto:" then jump directly to the mail detection
610 if (strpos($uri, 'mailto:') !== false) {
611 $uri = str_replace('mailto:', '', $uri);
612 return self::mail($uri, $uid);
615 if ($network == Protocol::MAIL) {
616 return self::mail($uri, $uid);
618 // Remove "acct:" from the URI
619 $uri = str_replace('acct:', '', $uri);
621 $host = substr($uri, strpos($uri, '@') + 1);
622 $nick = substr($uri, 0, strpos($uri, '@'));
624 if (strpos($uri, '@twitter.com')) {
625 return ["network" => Protocol::TWITTER];
627 $lrdd = self::hostMeta($host);
629 if (is_bool($lrdd)) {
634 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
635 return self::mail($uri, $uid);
639 logger("Uri ".$uri." was not detectable", LOGGER_DEBUG);
645 /// @todo Do we need the prefix "acct:" or "acct://"?
647 foreach ($lrdd as $type => $template) {
652 // At first try it with the given uri
653 $path = str_replace('{uri}', urlencode($uri), $template);
654 $webfinger = self::webfinger($path, $type);
656 // Fix possible problems with GNU Social probing to wrong scheme
657 $webfinger = self::fixOStatus($webfinger, $template, $type);
659 // We cannot be sure that the detected address was correct, so we don't use the values
660 if ($webfinger && ($uri != $addr)) {
665 // Try webfinger with the address (user@domain.tld)
667 $path = str_replace('{uri}', urlencode($addr), $template);
668 $webfinger = self::webfinger($path, $type);
671 // Mastodon needs to have it with "acct:"
673 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
674 $webfinger = self::webfinger($path, $type);
679 return self::feed($uri);
684 logger("Probing ".$uri, LOGGER_DEBUG);
686 if (in_array($network, ["", Protocol::DFRN])) {
687 $result = self::dfrn($webfinger);
689 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
690 $result = self::diaspora($webfinger);
692 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
693 $result = self::ostatus($webfinger);
695 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
696 $result = self::pumpio($webfinger, $addr);
698 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
699 $result = self::feed($uri);
701 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
702 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
703 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
704 $result["nick"] = $nick;
707 if (empty($result["addr"]) && ($addr != "")) {
708 $result["addr"] = $addr;
712 if (empty($result["network"])) {
713 $result["network"] = Protocol::PHANTOM;
716 if (empty($result["url"])) {
717 $result["url"] = $uri;
720 logger($uri." is ".$result["network"], LOGGER_DEBUG);
722 if (empty($result["baseurl"])) {
723 $pos = strpos($result["url"], $host);
725 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
732 * @brief Perform a webfinger request.
734 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
736 * @param string $url Address that should be probed
737 * @param string $type type
739 * @return array webfinger data
741 private static function webfinger($url, $type)
743 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
746 $ret = Network::curl($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
747 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
750 $data = $ret['body'];
752 $webfinger = json_decode($data, true);
753 if (is_array($webfinger)) {
754 if (!isset($webfinger["links"])) {
755 logger("No json webfinger links for ".$url, LOGGER_DEBUG);
761 // If it is not JSON, maybe it is XML
762 $xrd = XML::parseString($data, false);
763 if (!is_object($xrd)) {
764 logger("No webfinger data retrievable for ".$url, LOGGER_DEBUG);
768 $xrd_arr = XML::elementToArray($xrd);
769 if (!isset($xrd_arr["xrd"]["link"])) {
770 logger("No XML webfinger links for ".$url, LOGGER_DEBUG);
776 if (!empty($xrd_arr["xrd"]["subject"])) {
777 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
780 if (!empty($xrd_arr["xrd"]["alias"])) {
781 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
784 $webfinger["links"] = [];
786 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
787 if (!empty($data["@attributes"])) {
788 $attributes = $data["@attributes"];
789 } elseif ($value == "@attributes") {
795 $webfinger["links"][] = $attributes;
801 * @brief Poll the Friendica specific noscrape page.
803 * "noscrape" is a faster alternative to fetch the data from the hcard.
804 * This functionality was originally created for the directory.
806 * @param string $noscrape_url Link to the noscrape page
807 * @param array $data The already fetched data
809 * @return array noscrape data
811 private static function pollNoscrape($noscrape_url, $data)
813 $ret = Network::curl($noscrape_url);
814 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
817 $content = $ret['body'];
819 logger("Empty body for ".$noscrape_url, LOGGER_DEBUG);
823 $json = json_decode($content, true);
824 if (!is_array($json)) {
825 logger("No json data for ".$noscrape_url, LOGGER_DEBUG);
829 if (!empty($json["fn"])) {
830 $data["name"] = $json["fn"];
833 if (!empty($json["addr"])) {
834 $data["addr"] = $json["addr"];
837 if (!empty($json["nick"])) {
838 $data["nick"] = $json["nick"];
841 if (!empty($json["guid"])) {
842 $data["guid"] = $json["guid"];
845 if (!empty($json["comm"])) {
846 $data["community"] = $json["comm"];
849 if (!empty($json["tags"])) {
850 $keywords = implode(" ", $json["tags"]);
851 if ($keywords != "") {
852 $data["keywords"] = $keywords;
856 $location = Profile::formatLocation($json);
858 $data["location"] = $location;
861 if (!empty($json["about"])) {
862 $data["about"] = $json["about"];
865 if (!empty($json["key"])) {
866 $data["pubkey"] = $json["key"];
869 if (!empty($json["photo"])) {
870 $data["photo"] = $json["photo"];
873 if (!empty($json["dfrn-request"])) {
874 $data["request"] = $json["dfrn-request"];
877 if (!empty($json["dfrn-confirm"])) {
878 $data["confirm"] = $json["dfrn-confirm"];
881 if (!empty($json["dfrn-notify"])) {
882 $data["notify"] = $json["dfrn-notify"];
885 if (!empty($json["dfrn-poll"])) {
886 $data["poll"] = $json["dfrn-poll"];
893 * @brief Check for valid DFRN data
895 * @param array $data DFRN data
897 * @return int Number of errors
899 public static function validDfrn($data)
902 if (!isset($data['key'])) {
905 if (!isset($data['dfrn-request'])) {
908 if (!isset($data['dfrn-confirm'])) {
911 if (!isset($data['dfrn-notify'])) {
914 if (!isset($data['dfrn-poll'])) {
921 * @brief Fetch data from a DFRN profile page and via "noscrape"
923 * @param string $profile_link Link to the profile page
925 * @return array profile data
927 public static function profile($profile_link)
931 logger("Check profile ".$profile_link, LOGGER_DEBUG);
933 // Fetch data via noscrape - this is faster
934 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
935 $data = self::pollNoscrape($noscrape_url, $data);
937 if (!isset($data["notify"])
938 || !isset($data["confirm"])
939 || !isset($data["request"])
940 || !isset($data["poll"])
941 || !isset($data["name"])
942 || !isset($data["photo"])
944 $data = self::pollHcard($profile_link, $data, true);
949 if (empty($data["addr"]) || empty($data["nick"])) {
950 $probe_data = self::uri($profile_link);
951 $data["addr"] = defaults($data, "addr", $probe_data["addr"]);
952 $data["nick"] = defaults($data, "nick", $probe_data["nick"]);
955 $prof_data["addr"] = $data["addr"];
956 $prof_data["nick"] = $data["nick"];
957 $prof_data["dfrn-request"] = $data["request"];
958 $prof_data["dfrn-confirm"] = $data["confirm"];
959 $prof_data["dfrn-notify"] = $data["notify"];
960 $prof_data["dfrn-poll"] = $data["poll"];
961 $prof_data["photo"] = $data["photo"];
962 $prof_data["fn"] = $data["name"];
963 $prof_data["key"] = $data["pubkey"];
965 logger("Result for profile ".$profile_link.": ".print_r($prof_data, true), LOGGER_DEBUG);
971 * @brief Check for DFRN contact
973 * @param array $webfinger Webfinger data
975 * @return array DFRN data
977 private static function dfrn($webfinger)
981 foreach ($webfinger["links"] as $link) {
982 if (($link["rel"] == NAMESPACE_DFRN) && !empty($link["href"])) {
983 $data["network"] = Protocol::DFRN;
984 } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
985 $data["poll"] = $link["href"];
986 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (defaults($link, "type", "") == "text/html") && !empty($link["href"])) {
987 $data["url"] = $link["href"];
988 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
989 $hcard_url = $link["href"];
990 } elseif (($link["rel"] == NAMESPACE_POCO) && !empty($link["href"])) {
991 $data["poco"] = $link["href"];
992 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
993 $data["photo"] = $link["href"];
994 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
995 $data["baseurl"] = trim($link["href"], '/');
996 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
997 $data["guid"] = $link["href"];
998 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
999 $data["pubkey"] = base64_decode($link["href"]);
1001 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1002 if (strstr($data["pubkey"], 'RSA ')) {
1003 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1008 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1009 foreach ($webfinger["aliases"] as $alias) {
1010 if (empty($data["url"]) && !strstr($alias, "@")) {
1011 $data["url"] = $alias;
1012 } elseif (!strstr($alias, "@") && normalise_link($alias) != normalise_link($data["url"])) {
1013 $data["alias"] = $alias;
1014 } elseif (substr($alias, 0, 5) == 'acct:') {
1015 $data["addr"] = substr($alias, 5);
1020 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1021 $data["addr"] = substr($webfinger["subject"], 5);
1024 if (!isset($data["network"]) || ($hcard_url == "")) {
1028 // Fetch data via noscrape - this is faster
1029 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1030 $data = self::pollNoscrape($noscrape_url, $data);
1032 if (isset($data["notify"])
1033 && isset($data["confirm"])
1034 && isset($data["request"])
1035 && isset($data["poll"])
1036 && isset($data["name"])
1037 && isset($data["photo"])
1042 $data = self::pollHcard($hcard_url, $data, true);
1048 * @brief Poll the hcard page (Diaspora and Friendica specific)
1050 * @param string $hcard_url Link to the hcard page
1051 * @param array $data The already fetched data
1052 * @param boolean $dfrn Poll DFRN specific data
1054 * @return array hcard data
1056 private static function pollHcard($hcard_url, $data, $dfrn = false)
1058 $ret = Network::curl($hcard_url);
1059 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1062 $content = $ret['body'];
1067 $doc = new DOMDocument();
1068 if (!@$doc->loadHTML($content)) {
1072 $xpath = new DomXPath($doc);
1074 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1075 if (!is_object($vcards)) {
1079 if (!isset($data["baseurl"])) {
1080 $data["baseurl"] = "";
1083 if ($vcards->length > 0) {
1084 $vcard = $vcards->item(0);
1086 // We have to discard the guid from the hcard in favour of the guid from lrdd
1087 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1088 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1089 if (($search->length > 0) && empty($data["guid"])) {
1090 $data["guid"] = $search->item(0)->nodeValue;
1093 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1094 if ($search->length > 0) {
1095 $data["nick"] = $search->item(0)->nodeValue;
1098 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1099 if ($search->length > 0) {
1100 $data["name"] = $search->item(0)->nodeValue;
1103 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1104 if ($search->length > 0) {
1105 $data["searchable"] = $search->item(0)->nodeValue;
1108 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1109 if ($search->length > 0) {
1110 $data["pubkey"] = $search->item(0)->nodeValue;
1111 if (strstr($data["pubkey"], 'RSA ')) {
1112 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1116 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1117 if ($search->length > 0) {
1118 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1123 if (!empty($vcard)) {
1124 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1125 foreach ($photos as $photo) {
1127 foreach ($photo->attributes as $attribute) {
1128 $attr[$attribute->name] = trim($attribute->value);
1131 if (isset($attr["src"]) && isset($attr["width"])) {
1132 $avatar[$attr["width"]] = $attr["src"];
1135 // We don't have a width. So we just take everything that we got.
1136 // This is a Hubzilla workaround which doesn't send a width.
1137 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1138 $avatar[] = $attr["src"];
1143 if (sizeof($avatar)) {
1145 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1149 // Poll DFRN specific data
1150 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1151 if ($search->length > 0) {
1152 foreach ($search as $link) {
1153 //$data["request"] = $search->item(0)->nodeValue;
1155 foreach ($link->attributes as $attribute) {
1156 $attr[$attribute->name] = trim($attribute->value);
1159 $data[substr($attr["rel"], 5)] = $attr["href"];
1163 // Older Friendica versions had used the "uid" field differently than newer versions
1164 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1165 unset($data["guid"]);
1174 * @brief Check for Diaspora contact
1176 * @param array $webfinger Webfinger data
1178 * @return array Diaspora data
1180 private static function diaspora($webfinger)
1184 foreach ($webfinger["links"] as $link) {
1185 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1186 $hcard_url = $link["href"];
1187 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1188 $data["baseurl"] = trim($link["href"], '/');
1189 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1190 $data["guid"] = $link["href"];
1191 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (defaults($link, "type", "") == "text/html") && !empty($link["href"])) {
1192 $data["url"] = $link["href"];
1193 } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
1194 $data["poll"] = $link["href"];
1195 } elseif (($link["rel"] == NAMESPACE_POCO) && !empty($link["href"])) {
1196 $data["poco"] = $link["href"];
1197 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1198 $data["notify"] = $link["href"];
1199 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1200 $data["pubkey"] = base64_decode($link["href"]);
1202 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1203 if (strstr($data["pubkey"], 'RSA ')) {
1204 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1209 if (!isset($data["url"]) || ($hcard_url == "")) {
1213 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1214 foreach ($webfinger["aliases"] as $alias) {
1215 if (normalise_link($alias) != normalise_link($data["url"]) && ! strstr($alias, "@")) {
1216 $data["alias"] = $alias;
1217 } elseif (substr($alias, 0, 5) == 'acct:') {
1218 $data["addr"] = substr($alias, 5);
1223 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1224 $data["addr"] = substr($webfinger["subject"], 5);
1227 // Fetch further information from the hcard
1228 $data = self::pollHcard($hcard_url, $data);
1234 if (isset($data["url"])
1235 && isset($data["guid"])
1236 && isset($data["baseurl"])
1237 && isset($data["pubkey"])
1238 && ($hcard_url != "")
1240 $data["network"] = Protocol::DIASPORA;
1242 // The Diaspora handle must always be lowercase
1243 if (!empty($data["addr"])) {
1244 $data["addr"] = strtolower($data["addr"]);
1247 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1248 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1249 $data["batch"] = $data["baseurl"] . "/receive/public";
1258 * @brief Check for OStatus contact
1260 * @param array $webfinger Webfinger data
1261 * @param bool $short Short detection mode
1263 * @return array|bool OStatus data or "false" on error or "true" on short mode
1265 private static function ostatus($webfinger, $short = false)
1269 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1270 foreach ($webfinger["aliases"] as $alias) {
1271 if (strstr($alias, "@") && !strstr(normalise_link($alias), "http://")) {
1272 $data["addr"] = str_replace('acct:', '', $alias);
1277 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1278 && !strstr(normalise_link($webfinger["subject"]), "http://")
1280 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1284 if (is_array($webfinger["links"])) {
1285 foreach ($webfinger["links"] as $link) {
1286 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1287 && (defaults($link, "type", "") == "text/html")
1288 && ($link["href"] != "")
1290 $data["url"] = $link["href"];
1291 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1292 $data["notify"] = $link["href"];
1293 } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
1294 $data["poll"] = $link["href"];
1295 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1296 $pubkey = $link["href"];
1298 if (substr($pubkey, 0, 5) === 'data:') {
1299 if (strstr($pubkey, ',')) {
1300 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1302 $pubkey = substr($pubkey, 5);
1304 } elseif (normalise_link($pubkey) == 'http://') {
1305 $ret = Network::curl($pubkey);
1306 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1309 $pubkey = $ret['body'];
1312 $key = explode(".", $pubkey);
1314 if (sizeof($key) >= 3) {
1315 $m = base64url_decode($key[1]);
1316 $e = base64url_decode($key[2]);
1317 $data["pubkey"] = Crypto::meToPem($m, $e);
1323 if (isset($data["notify"]) && isset($data["pubkey"])
1324 && isset($data["poll"])
1325 && isset($data["url"])
1327 $data["network"] = Protocol::OSTATUS;
1336 // Fetch all additional data from the feed
1337 $ret = Network::curl($data["poll"]);
1338 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1341 $feed = $ret['body'];
1345 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1350 if (!empty($feed_data["header"]["author-name"])) {
1351 $data["name"] = $feed_data["header"]["author-name"];
1353 if (!empty($feed_data["header"]["author-nick"])) {
1354 $data["nick"] = $feed_data["header"]["author-nick"];
1356 if (!empty($feed_data["header"]["author-avatar"])) {
1357 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1359 if (!empty($feed_data["header"]["author-id"])) {
1360 $data["alias"] = $feed_data["header"]["author-id"];
1362 if (!empty($feed_data["header"]["author-location"])) {
1363 $data["location"] = $feed_data["header"]["author-location"];
1365 if (!empty($feed_data["header"]["author-about"])) {
1366 $data["about"] = $feed_data["header"]["author-about"];
1368 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1369 // So we take the value that we just fetched, although the other one worked as well
1370 if (!empty($feed_data["header"]["author-link"])) {
1371 $data["url"] = $feed_data["header"]["author-link"];
1374 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1375 $data['url'] = $data["alias"];
1376 $data["alias"] = '';
1379 /// @todo Fetch location and "about" from the feed as well
1384 * @brief Fetch data from a pump.io profile page
1386 * @param string $profile_link Link to the profile page
1388 * @return array profile data
1390 private static function pumpioProfileData($profile_link)
1392 $doc = new DOMDocument();
1393 if (!@$doc->loadHTMLFile($profile_link)) {
1397 $xpath = new DomXPath($doc);
1401 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1403 if ($data["name"] == '') {
1404 // This is ugly - but pump.io doesn't seem to know a better way for it
1405 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1406 $pos = strpos($data["name"], chr(10));
1408 $data["name"] = trim(substr($data["name"], 0, $pos));
1412 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1414 if ($data["location"] == '') {
1415 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1418 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1420 if ($data["about"] == '') {
1421 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1424 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1426 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1429 foreach ($avatar->attributes as $attribute) {
1430 if ($attribute->name == "src") {
1431 $data["photo"] = trim($attribute->value);
1440 * @brief Check for pump.io contact
1442 * @param array $webfinger Webfinger data
1444 * @return array pump.io data
1446 private static function pumpio($webfinger, $addr)
1449 foreach ($webfinger["links"] as $link) {
1450 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1451 && (defaults($link, "type", "") == "text/html")
1452 && ($link["href"] != "")
1454 $data["url"] = $link["href"];
1455 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1456 $data["notify"] = $link["href"];
1457 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1458 $data["poll"] = $link["href"];
1459 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1460 $data["dialback"] = $link["href"];
1463 if (isset($data["poll"]) && isset($data["notify"])
1464 && isset($data["dialback"])
1465 && isset($data["url"])
1467 // by now we use these fields only for the network type detection
1468 // So we unset all data that isn't used at the moment
1469 unset($data["dialback"]);
1471 $data["network"] = Protocol::PUMPIO;
1476 $profile_data = self::pumpioProfileData($data["url"]);
1478 if (!$profile_data) {
1482 $data = array_merge($data, $profile_data);
1484 if (($addr != '') && ($data['name'] != '')) {
1485 $name = trim(str_replace($addr, '', $data['name']));
1487 $data['name'] = $name;
1495 * @brief Check page for feed link
1497 * @param string $url Page link
1499 * @return string feed link
1501 private static function getFeedLink($url)
1503 $doc = new DOMDocument();
1505 if (!@$doc->loadHTMLFile($url)) {
1509 $xpath = new DomXPath($doc);
1511 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1512 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1513 if (!is_object($feeds)) {
1517 if ($feeds->length == 0) {
1523 foreach ($feeds as $feed) {
1525 foreach ($feed->attributes as $attribute) {
1526 $attr[$attribute->name] = trim($attribute->value);
1529 if ($feed_url == "") {
1530 $feed_url = $attr["href"];
1538 * @brief Check for feed contact
1540 * @param string $url Profile link
1541 * @param boolean $probe Do a probe if the page contains a feed link
1543 * @return array feed data
1545 private static function feed($url, $probe = true)
1547 $ret = Network::curl($url);
1548 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1551 $feed = $ret['body'];
1552 $dummy1 = $dummy2 = $dummy3 = null;
1553 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1560 $feed_url = self::getFeedLink($url);
1566 return self::feed($feed_url, false);
1569 if (!empty($feed_data["header"]["author-name"])) {
1570 $data["name"] = $feed_data["header"]["author-name"];
1573 if (!empty($feed_data["header"]["author-nick"])) {
1574 $data["nick"] = $feed_data["header"]["author-nick"];
1577 if (!empty($feed_data["header"]["author-avatar"])) {
1578 $data["photo"] = $feed_data["header"]["author-avatar"];
1581 if (!empty($feed_data["header"]["author-id"])) {
1582 $data["alias"] = $feed_data["header"]["author-id"];
1585 $data["url"] = $url;
1586 $data["poll"] = $url;
1588 if (!empty($feed_data["header"]["author-link"])) {
1589 $data["baseurl"] = $feed_data["header"]["author-link"];
1591 $data["baseurl"] = $data["url"];
1594 $data["network"] = Protocol::FEED;
1600 * @brief Check for mail contact
1602 * @param string $uri Profile link
1603 * @param integer $uid User ID
1605 * @return array mail data
1607 private static function mail($uri, $uid)
1609 if (!Network::isEmailDomainValid($uri)) {
1617 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1619 $condition = ["`uid` = ? AND `server` != ''", $uid];
1620 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1621 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1623 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1627 $mailbox = Email::constructMailboxName($mailacct);
1629 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1630 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1635 $msgs = Email::poll($mbox, $uri);
1636 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1638 if (!count($msgs)) {
1642 $phost = substr($uri, strpos($uri, '@') + 1);
1645 $data["addr"] = $uri;
1646 $data["network"] = Protocol::MAIL;
1647 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1648 $data["nick"] = $data["name"];
1649 $data["photo"] = Network::lookupAvatarByEmail($uri);
1650 $data["url"] = 'mailto:'.$uri;
1651 $data["notify"] = 'smtp '.random_string();
1652 $data["poll"] = 'email '.random_string();
1654 $x = Email::messageMeta($mbox, $msgs[0]);
1655 if (stristr($x[0]->from, $uri)) {
1656 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1657 } elseif (stristr($x[0]->to, $uri)) {
1658 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1661 foreach ($adr as $feadr) {
1662 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1663 &&(strcasecmp($feadr->host, $phost) == 0)
1664 && (strlen($feadr->personal))
1666 $personal = imap_mime_header_decode($feadr->personal);
1668 foreach ($personal as $perspart) {
1669 if ($perspart->charset != "default") {
1670 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1672 $data["name"] .= $perspart->text;
1676 $data["name"] = notags($data["name"]);
1680 if (!empty($mbox)) {
1687 * @brief Mix two paths together to possibly fix missing parts
1689 * @param string $avatar Path to the avatar
1690 * @param string $base Another path that is hopefully complete
1692 * @return string fixed avatar path
1694 public static function fixAvatar($avatar, $base)
1696 $base_parts = parse_url($base);
1698 // Remove all parts that could create a problem
1699 unset($base_parts['path']);
1700 unset($base_parts['query']);
1701 unset($base_parts['fragment']);
1703 $avatar_parts = parse_url($avatar);
1706 $parts = array_merge($base_parts, $avatar_parts);
1708 // And put them together again
1709 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1710 $host = isset($parts['host']) ? $parts['host'] : '';
1711 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1712 $path = isset($parts['path']) ? $parts['path'] : '';
1713 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1714 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1716 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1718 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);