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 $ap_profile = ActivityPub::probeProfile($uri);
340 if (!empty($ap_profile) && (defaults($data, 'network', '') != Protocol::DFRN)) {
341 if (!empty($ap_profile) && ($ap_profile['network'] == Protocol::ACTIVITYPUB)) {
346 if (!isset($data["url"])) {
350 if (x($data, "photo")) {
351 $data["baseurl"] = Network::getUrlMatch(normalise_link(defaults($data, "baseurl", "")), normalise_link($data["photo"]));
353 $data["photo"] = System::baseUrl().'/images/person-175.jpg';
356 if (empty($data["name"])) {
357 if (!empty($data["nick"])) {
358 $data["name"] = $data["nick"];
361 if (!x($data, "name")) {
362 $data["name"] = $data["url"];
366 if (empty($data["nick"])) {
367 $data["nick"] = strtolower($data["name"]);
369 if (strpos($data['nick'], ' ')) {
370 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
374 if (!empty(self::$baseurl)) {
375 $data["baseurl"] = self::$baseurl;
378 if (empty($data["network"])) {
379 $data["network"] = Protocol::PHANTOM;
382 $data = self::rearrangeData($data);
384 // Only store into the cache if the value seems to be valid
385 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
386 Cache::set("Probe::uri:".$network.":".$uri, $data, CACHE_DAY);
388 /// @todo temporary fix - we need a real contact update function that updates only changing fields
389 /// The biggest problem is the avatar picture that could have a reduced image size.
390 /// It should only be updated if the existing picture isn't existing anymore.
391 /// We only update the contact when it is no probing for a specific network.
392 if (($data['network'] != Protocol::FEED)
400 $fields = ['name' => $data['name'],
401 'nick' => $data['nick'],
402 'url' => $data['url'],
403 'addr' => $data['addr'],
404 'photo' => $data['photo'],
405 'keywords' => $data['keywords'],
406 'location' => $data['location'],
407 'about' => $data['about'],
408 'notify' => $data['notify'],
409 'network' => $data['network'],
410 'server_url' => $data['baseurl']];
412 // This doesn't cover the case when a community isn't a community anymore
413 if (!empty($data['community']) && $data['community']) {
414 $fields['community'] = $data['community'];
415 $fields['contact-type'] = Contact::ACCOUNT_TYPE_COMMUNITY;
420 foreach ($fields as $key => $val) {
422 unset($fields[$key]);
424 $fieldnames[] = $key;
428 $fields['updated'] = DateTimeFormat::utcNow();
430 $condition = ['nurl' => normalise_link($data["url"])];
432 $old_fields = DBA::selectFirst('gcontact', $fieldnames, $condition);
434 // When the gcontact doesn't exist, the value "true" will trigger an insert.
435 // In difference to the public contacts we want to have every contact
436 // in the world in our global contacts.
440 // These values have to be set only on insert
441 $fields['photo'] = $data['photo'];
442 $fields['created'] = DateTimeFormat::utcNow();
445 DBA::update('gcontact', $fields, $condition, $old_fields);
447 $fields = ['name' => $data['name'],
448 'nick' => $data['nick'],
449 'url' => $data['url'],
450 'addr' => $data['addr'],
451 'alias' => $data['alias'],
452 'keywords' => $data['keywords'],
453 'location' => $data['location'],
454 'about' => $data['about'],
455 'batch' => $data['batch'],
456 'notify' => $data['notify'],
457 'poll' => $data['poll'],
458 'request' => $data['request'],
459 'confirm' => $data['confirm'],
460 'poco' => $data['poco'],
461 'network' => $data['network'],
462 'pubkey' => $data['pubkey'],
463 'priority' => $data['priority'],
465 'rel' => Contact::SHARING];
469 foreach ($fields as $key => $val) {
471 unset($fields[$key]);
473 $fieldnames[] = $key;
477 $condition = ['nurl' => normalise_link($data["url"]), 'self' => false, 'uid' => 0];
479 // "$old_fields" will return a "false" when the contact doesn't exist.
480 // This won't trigger an insert. This is intended, since we only need
481 // public contacts for everyone we store items from.
482 // We don't need to store every contact on the planet.
483 $old_fields = DBA::selectFirst('contact', $fieldnames, $condition);
485 $fields['name-date'] = DateTimeFormat::utcNow();
486 $fields['uri-date'] = DateTimeFormat::utcNow();
487 $fields['success_update'] = DateTimeFormat::utcNow();
489 DBA::update('contact', $fields, $condition, $old_fields);
497 * @brief Switch the scheme of an url between http and https
499 * @param string $url URL
501 * @return string switched URL
503 private static function switchScheme($url)
505 $parts = parse_url($url);
507 if (!isset($parts['scheme'])) {
511 if ($parts['scheme'] == 'http') {
512 $url = str_replace('http://', 'https://', $url);
513 } elseif ($parts['scheme'] == 'https') {
514 $url = str_replace('https://', 'http://', $url);
521 * @brief Checks if a profile url should be OStatus but only provides partial information
523 * @param array $webfinger Webfinger data
524 * @param string $lrdd Path template for webfinger request
525 * @param string $type type
527 * @return array fixed webfinger data
529 private static function fixOStatus($webfinger, $lrdd, $type)
531 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
538 foreach ($webfinger['links'] as $link) {
539 if ($link['rel'] == NAMESPACE_OSTATUSSUB) {
542 if ($link['rel'] == 'magic-public-key') {
547 if (!$is_ostatus || $has_key) {
551 $url = self::switchScheme($webfinger['subject']);
552 $path = str_replace('{uri}', urlencode($url), $lrdd);
553 $webfinger2 = self::webfinger($path, $type);
555 // Is the new webfinger detectable as OStatus?
556 if (self::ostatus($webfinger2, true)) {
557 $webfinger = $webfinger2;
564 * @brief Fetch information (protocol endpoints and user information) about a given uri
566 * This function is only called by the "uri" function that adds caching and rearranging of data.
568 * @param string $uri Address that should be probed
569 * @param string $network Test for this specific network
570 * @param integer $uid User ID for the probe (only used for mails)
572 * @return array uri data
574 private static function detect($uri, $network, $uid)
576 $parts = parse_url($uri);
578 if (!empty($parts["scheme"]) && !empty($parts["host"]) && !empty($parts["path"])) {
579 $host = $parts["host"];
580 if (!empty($parts["port"])) {
581 $host .= ':'.$parts["port"];
584 if ($host == 'twitter.com') {
585 return ["network" => Protocol::TWITTER];
587 $lrdd = self::hostMeta($host);
589 if (is_bool($lrdd)) {
593 $path_parts = explode("/", trim($parts["path"], "/"));
595 while (!$lrdd && (sizeof($path_parts) > 1)) {
596 $host .= "/".array_shift($path_parts);
597 $lrdd = self::hostMeta($host);
600 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
601 return self::feed($uri);
603 $nick = array_pop($path_parts);
605 // Mastodon uses a "@" as prefix for usernames in their url format
606 $nick = ltrim($nick, '@');
608 $addr = $nick."@".$host;
609 } elseif (strstr($uri, '@')) {
610 // If the URI starts with "mailto:" then jump directly to the mail detection
611 if (strpos($uri, 'mailto:') !== false) {
612 $uri = str_replace('mailto:', '', $uri);
613 return self::mail($uri, $uid);
616 if ($network == Protocol::MAIL) {
617 return self::mail($uri, $uid);
619 // Remove "acct:" from the URI
620 $uri = str_replace('acct:', '', $uri);
622 $host = substr($uri, strpos($uri, '@') + 1);
623 $nick = substr($uri, 0, strpos($uri, '@'));
625 if (strpos($uri, '@twitter.com')) {
626 return ["network" => Protocol::TWITTER];
628 $lrdd = self::hostMeta($host);
630 if (is_bool($lrdd)) {
635 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
636 return self::mail($uri, $uid);
640 logger("Uri ".$uri." was not detectable", LOGGER_DEBUG);
646 /// @todo Do we need the prefix "acct:" or "acct://"?
648 foreach ($lrdd as $type => $template) {
653 // At first try it with the given uri
654 $path = str_replace('{uri}', urlencode($uri), $template);
655 $webfinger = self::webfinger($path, $type);
657 // Fix possible problems with GNU Social probing to wrong scheme
658 $webfinger = self::fixOStatus($webfinger, $template, $type);
660 // We cannot be sure that the detected address was correct, so we don't use the values
661 if ($webfinger && ($uri != $addr)) {
666 // Try webfinger with the address (user@domain.tld)
668 $path = str_replace('{uri}', urlencode($addr), $template);
669 $webfinger = self::webfinger($path, $type);
672 // Mastodon needs to have it with "acct:"
674 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
675 $webfinger = self::webfinger($path, $type);
680 return self::feed($uri);
685 logger("Probing ".$uri, LOGGER_DEBUG);
687 if (in_array($network, ["", Protocol::DFRN])) {
688 $result = self::dfrn($webfinger);
690 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
691 $result = self::diaspora($webfinger);
693 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
694 $result = self::ostatus($webfinger);
696 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
697 $result = self::pumpio($webfinger, $addr);
699 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
700 $result = self::feed($uri);
702 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
703 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
704 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
705 $result["nick"] = $nick;
708 if (empty($result["addr"]) && ($addr != "")) {
709 $result["addr"] = $addr;
713 if (empty($result["network"])) {
714 $result["network"] = Protocol::PHANTOM;
717 if (empty($result["url"])) {
718 $result["url"] = $uri;
721 logger($uri." is ".$result["network"], LOGGER_DEBUG);
723 if (empty($result["baseurl"])) {
724 $pos = strpos($result["url"], $host);
726 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
733 * @brief Perform a webfinger request.
735 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
737 * @param string $url Address that should be probed
738 * @param string $type type
740 * @return array webfinger data
742 private static function webfinger($url, $type)
744 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
747 $ret = Network::curl($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
748 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
751 $data = $ret['body'];
753 $webfinger = json_decode($data, true);
754 if (is_array($webfinger)) {
755 if (!isset($webfinger["links"])) {
756 logger("No json webfinger links for ".$url, LOGGER_DEBUG);
762 // If it is not JSON, maybe it is XML
763 $xrd = XML::parseString($data, false);
764 if (!is_object($xrd)) {
765 logger("No webfinger data retrievable for ".$url, LOGGER_DEBUG);
769 $xrd_arr = XML::elementToArray($xrd);
770 if (!isset($xrd_arr["xrd"]["link"])) {
771 logger("No XML webfinger links for ".$url, LOGGER_DEBUG);
777 if (!empty($xrd_arr["xrd"]["subject"])) {
778 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
781 if (!empty($xrd_arr["xrd"]["alias"])) {
782 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
785 $webfinger["links"] = [];
787 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
788 if (!empty($data["@attributes"])) {
789 $attributes = $data["@attributes"];
790 } elseif ($value == "@attributes") {
796 $webfinger["links"][] = $attributes;
802 * @brief Poll the Friendica specific noscrape page.
804 * "noscrape" is a faster alternative to fetch the data from the hcard.
805 * This functionality was originally created for the directory.
807 * @param string $noscrape_url Link to the noscrape page
808 * @param array $data The already fetched data
810 * @return array noscrape data
812 private static function pollNoscrape($noscrape_url, $data)
814 $ret = Network::curl($noscrape_url);
815 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
818 $content = $ret['body'];
820 logger("Empty body for ".$noscrape_url, LOGGER_DEBUG);
824 $json = json_decode($content, true);
825 if (!is_array($json)) {
826 logger("No json data for ".$noscrape_url, LOGGER_DEBUG);
830 if (!empty($json["fn"])) {
831 $data["name"] = $json["fn"];
834 if (!empty($json["addr"])) {
835 $data["addr"] = $json["addr"];
838 if (!empty($json["nick"])) {
839 $data["nick"] = $json["nick"];
842 if (!empty($json["guid"])) {
843 $data["guid"] = $json["guid"];
846 if (!empty($json["comm"])) {
847 $data["community"] = $json["comm"];
850 if (!empty($json["tags"])) {
851 $keywords = implode(" ", $json["tags"]);
852 if ($keywords != "") {
853 $data["keywords"] = $keywords;
857 $location = Profile::formatLocation($json);
859 $data["location"] = $location;
862 if (!empty($json["about"])) {
863 $data["about"] = $json["about"];
866 if (!empty($json["key"])) {
867 $data["pubkey"] = $json["key"];
870 if (!empty($json["photo"])) {
871 $data["photo"] = $json["photo"];
874 if (!empty($json["dfrn-request"])) {
875 $data["request"] = $json["dfrn-request"];
878 if (!empty($json["dfrn-confirm"])) {
879 $data["confirm"] = $json["dfrn-confirm"];
882 if (!empty($json["dfrn-notify"])) {
883 $data["notify"] = $json["dfrn-notify"];
886 if (!empty($json["dfrn-poll"])) {
887 $data["poll"] = $json["dfrn-poll"];
894 * @brief Check for valid DFRN data
896 * @param array $data DFRN data
898 * @return int Number of errors
900 public static function validDfrn($data)
903 if (!isset($data['key'])) {
906 if (!isset($data['dfrn-request'])) {
909 if (!isset($data['dfrn-confirm'])) {
912 if (!isset($data['dfrn-notify'])) {
915 if (!isset($data['dfrn-poll'])) {
922 * @brief Fetch data from a DFRN profile page and via "noscrape"
924 * @param string $profile_link Link to the profile page
926 * @return array profile data
928 public static function profile($profile_link)
932 logger("Check profile ".$profile_link, LOGGER_DEBUG);
934 // Fetch data via noscrape - this is faster
935 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
936 $data = self::pollNoscrape($noscrape_url, $data);
938 if (!isset($data["notify"])
939 || !isset($data["confirm"])
940 || !isset($data["request"])
941 || !isset($data["poll"])
942 || !isset($data["name"])
943 || !isset($data["photo"])
945 $data = self::pollHcard($profile_link, $data, true);
950 if (empty($data["addr"]) || empty($data["nick"])) {
951 $probe_data = self::uri($profile_link);
952 $data["addr"] = defaults($data, "addr", $probe_data["addr"]);
953 $data["nick"] = defaults($data, "nick", $probe_data["nick"]);
956 $prof_data["addr"] = $data["addr"];
957 $prof_data["nick"] = $data["nick"];
958 $prof_data["dfrn-request"] = $data["request"];
959 $prof_data["dfrn-confirm"] = $data["confirm"];
960 $prof_data["dfrn-notify"] = $data["notify"];
961 $prof_data["dfrn-poll"] = $data["poll"];
962 $prof_data["photo"] = $data["photo"];
963 $prof_data["fn"] = $data["name"];
964 $prof_data["key"] = $data["pubkey"];
966 logger("Result for profile ".$profile_link.": ".print_r($prof_data, true), LOGGER_DEBUG);
972 * @brief Check for DFRN contact
974 * @param array $webfinger Webfinger data
976 * @return array DFRN data
978 private static function dfrn($webfinger)
982 foreach ($webfinger["links"] as $link) {
983 if (($link["rel"] == NAMESPACE_DFRN) && !empty($link["href"])) {
984 $data["network"] = Protocol::DFRN;
985 } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
986 $data["poll"] = $link["href"];
987 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (defaults($link, "type", "") == "text/html") && !empty($link["href"])) {
988 $data["url"] = $link["href"];
989 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
990 $hcard_url = $link["href"];
991 } elseif (($link["rel"] == NAMESPACE_POCO) && !empty($link["href"])) {
992 $data["poco"] = $link["href"];
993 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
994 $data["photo"] = $link["href"];
995 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
996 $data["baseurl"] = trim($link["href"], '/');
997 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
998 $data["guid"] = $link["href"];
999 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1000 $data["pubkey"] = base64_decode($link["href"]);
1002 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1003 if (strstr($data["pubkey"], 'RSA ')) {
1004 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1009 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1010 foreach ($webfinger["aliases"] as $alias) {
1011 if (empty($data["url"]) && !strstr($alias, "@")) {
1012 $data["url"] = $alias;
1013 } elseif (!strstr($alias, "@") && normalise_link($alias) != normalise_link($data["url"])) {
1014 $data["alias"] = $alias;
1015 } elseif (substr($alias, 0, 5) == 'acct:') {
1016 $data["addr"] = substr($alias, 5);
1021 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1022 $data["addr"] = substr($webfinger["subject"], 5);
1025 if (!isset($data["network"]) || ($hcard_url == "")) {
1029 // Fetch data via noscrape - this is faster
1030 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1031 $data = self::pollNoscrape($noscrape_url, $data);
1033 if (isset($data["notify"])
1034 && isset($data["confirm"])
1035 && isset($data["request"])
1036 && isset($data["poll"])
1037 && isset($data["name"])
1038 && isset($data["photo"])
1043 $data = self::pollHcard($hcard_url, $data, true);
1049 * @brief Poll the hcard page (Diaspora and Friendica specific)
1051 * @param string $hcard_url Link to the hcard page
1052 * @param array $data The already fetched data
1053 * @param boolean $dfrn Poll DFRN specific data
1055 * @return array hcard data
1057 private static function pollHcard($hcard_url, $data, $dfrn = false)
1059 $ret = Network::curl($hcard_url);
1060 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1063 $content = $ret['body'];
1068 $doc = new DOMDocument();
1069 if (!@$doc->loadHTML($content)) {
1073 $xpath = new DomXPath($doc);
1075 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1076 if (!is_object($vcards)) {
1080 if (!isset($data["baseurl"])) {
1081 $data["baseurl"] = "";
1084 if ($vcards->length > 0) {
1085 $vcard = $vcards->item(0);
1087 // We have to discard the guid from the hcard in favour of the guid from lrdd
1088 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1089 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1090 if (($search->length > 0) && empty($data["guid"])) {
1091 $data["guid"] = $search->item(0)->nodeValue;
1094 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1095 if ($search->length > 0) {
1096 $data["nick"] = $search->item(0)->nodeValue;
1099 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1100 if ($search->length > 0) {
1101 $data["name"] = $search->item(0)->nodeValue;
1104 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1105 if ($search->length > 0) {
1106 $data["searchable"] = $search->item(0)->nodeValue;
1109 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1110 if ($search->length > 0) {
1111 $data["pubkey"] = $search->item(0)->nodeValue;
1112 if (strstr($data["pubkey"], 'RSA ')) {
1113 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1117 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1118 if ($search->length > 0) {
1119 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1124 if (!empty($vcard)) {
1125 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1126 foreach ($photos as $photo) {
1128 foreach ($photo->attributes as $attribute) {
1129 $attr[$attribute->name] = trim($attribute->value);
1132 if (isset($attr["src"]) && isset($attr["width"])) {
1133 $avatar[$attr["width"]] = $attr["src"];
1136 // We don't have a width. So we just take everything that we got.
1137 // This is a Hubzilla workaround which doesn't send a width.
1138 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1139 $avatar[] = $attr["src"];
1144 if (sizeof($avatar)) {
1146 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1150 // Poll DFRN specific data
1151 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1152 if ($search->length > 0) {
1153 foreach ($search as $link) {
1154 //$data["request"] = $search->item(0)->nodeValue;
1156 foreach ($link->attributes as $attribute) {
1157 $attr[$attribute->name] = trim($attribute->value);
1160 $data[substr($attr["rel"], 5)] = $attr["href"];
1164 // Older Friendica versions had used the "uid" field differently than newer versions
1165 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1166 unset($data["guid"]);
1175 * @brief Check for Diaspora contact
1177 * @param array $webfinger Webfinger data
1179 * @return array Diaspora data
1181 private static function diaspora($webfinger)
1185 foreach ($webfinger["links"] as $link) {
1186 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1187 $hcard_url = $link["href"];
1188 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1189 $data["baseurl"] = trim($link["href"], '/');
1190 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1191 $data["guid"] = $link["href"];
1192 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (defaults($link, "type", "") == "text/html") && !empty($link["href"])) {
1193 $data["url"] = $link["href"];
1194 } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
1195 $data["poll"] = $link["href"];
1196 } elseif (($link["rel"] == NAMESPACE_POCO) && !empty($link["href"])) {
1197 $data["poco"] = $link["href"];
1198 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1199 $data["notify"] = $link["href"];
1200 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1201 $data["pubkey"] = base64_decode($link["href"]);
1203 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1204 if (strstr($data["pubkey"], 'RSA ')) {
1205 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1210 if (!isset($data["url"]) || ($hcard_url == "")) {
1214 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1215 foreach ($webfinger["aliases"] as $alias) {
1216 if (normalise_link($alias) != normalise_link($data["url"]) && ! strstr($alias, "@")) {
1217 $data["alias"] = $alias;
1218 } elseif (substr($alias, 0, 5) == 'acct:') {
1219 $data["addr"] = substr($alias, 5);
1224 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1225 $data["addr"] = substr($webfinger["subject"], 5);
1228 // Fetch further information from the hcard
1229 $data = self::pollHcard($hcard_url, $data);
1235 if (isset($data["url"])
1236 && isset($data["guid"])
1237 && isset($data["baseurl"])
1238 && isset($data["pubkey"])
1239 && ($hcard_url != "")
1241 $data["network"] = Protocol::DIASPORA;
1243 // The Diaspora handle must always be lowercase
1244 if (!empty($data["addr"])) {
1245 $data["addr"] = strtolower($data["addr"]);
1248 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1249 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1250 $data["batch"] = $data["baseurl"] . "/receive/public";
1259 * @brief Check for OStatus contact
1261 * @param array $webfinger Webfinger data
1262 * @param bool $short Short detection mode
1264 * @return array|bool OStatus data or "false" on error or "true" on short mode
1266 private static function ostatus($webfinger, $short = false)
1270 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1271 foreach ($webfinger["aliases"] as $alias) {
1272 if (strstr($alias, "@") && !strstr(normalise_link($alias), "http://")) {
1273 $data["addr"] = str_replace('acct:', '', $alias);
1278 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1279 && !strstr(normalise_link($webfinger["subject"]), "http://")
1281 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1285 if (is_array($webfinger["links"])) {
1286 foreach ($webfinger["links"] as $link) {
1287 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1288 && (defaults($link, "type", "") == "text/html")
1289 && ($link["href"] != "")
1291 $data["url"] = $link["href"];
1292 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1293 $data["notify"] = $link["href"];
1294 } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
1295 $data["poll"] = $link["href"];
1296 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1297 $pubkey = $link["href"];
1299 if (substr($pubkey, 0, 5) === 'data:') {
1300 if (strstr($pubkey, ',')) {
1301 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1303 $pubkey = substr($pubkey, 5);
1305 } elseif (normalise_link($pubkey) == 'http://') {
1306 $ret = Network::curl($pubkey);
1307 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1310 $pubkey = $ret['body'];
1313 $key = explode(".", $pubkey);
1315 if (sizeof($key) >= 3) {
1316 $m = base64url_decode($key[1]);
1317 $e = base64url_decode($key[2]);
1318 $data["pubkey"] = Crypto::meToPem($m, $e);
1324 if (isset($data["notify"]) && isset($data["pubkey"])
1325 && isset($data["poll"])
1326 && isset($data["url"])
1328 $data["network"] = Protocol::OSTATUS;
1337 // Fetch all additional data from the feed
1338 $ret = Network::curl($data["poll"]);
1339 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1342 $feed = $ret['body'];
1346 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1351 if (!empty($feed_data["header"]["author-name"])) {
1352 $data["name"] = $feed_data["header"]["author-name"];
1354 if (!empty($feed_data["header"]["author-nick"])) {
1355 $data["nick"] = $feed_data["header"]["author-nick"];
1357 if (!empty($feed_data["header"]["author-avatar"])) {
1358 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1360 if (!empty($feed_data["header"]["author-id"])) {
1361 $data["alias"] = $feed_data["header"]["author-id"];
1363 if (!empty($feed_data["header"]["author-location"])) {
1364 $data["location"] = $feed_data["header"]["author-location"];
1366 if (!empty($feed_data["header"]["author-about"])) {
1367 $data["about"] = $feed_data["header"]["author-about"];
1369 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1370 // So we take the value that we just fetched, although the other one worked as well
1371 if (!empty($feed_data["header"]["author-link"])) {
1372 $data["url"] = $feed_data["header"]["author-link"];
1375 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1376 $data['url'] = $data["alias"];
1377 $data["alias"] = '';
1380 /// @todo Fetch location and "about" from the feed as well
1385 * @brief Fetch data from a pump.io profile page
1387 * @param string $profile_link Link to the profile page
1389 * @return array profile data
1391 private static function pumpioProfileData($profile_link)
1393 $doc = new DOMDocument();
1394 if (!@$doc->loadHTMLFile($profile_link)) {
1398 $xpath = new DomXPath($doc);
1402 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1404 if ($data["name"] == '') {
1405 // This is ugly - but pump.io doesn't seem to know a better way for it
1406 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1407 $pos = strpos($data["name"], chr(10));
1409 $data["name"] = trim(substr($data["name"], 0, $pos));
1413 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1415 if ($data["location"] == '') {
1416 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1419 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1421 if ($data["about"] == '') {
1422 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1425 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1427 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1430 foreach ($avatar->attributes as $attribute) {
1431 if ($attribute->name == "src") {
1432 $data["photo"] = trim($attribute->value);
1441 * @brief Check for pump.io contact
1443 * @param array $webfinger Webfinger data
1445 * @return array pump.io data
1447 private static function pumpio($webfinger, $addr)
1450 foreach ($webfinger["links"] as $link) {
1451 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1452 && (defaults($link, "type", "") == "text/html")
1453 && ($link["href"] != "")
1455 $data["url"] = $link["href"];
1456 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1457 $data["notify"] = $link["href"];
1458 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1459 $data["poll"] = $link["href"];
1460 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1461 $data["dialback"] = $link["href"];
1464 if (isset($data["poll"]) && isset($data["notify"])
1465 && isset($data["dialback"])
1466 && isset($data["url"])
1468 // by now we use these fields only for the network type detection
1469 // So we unset all data that isn't used at the moment
1470 unset($data["dialback"]);
1472 $data["network"] = Protocol::PUMPIO;
1477 $profile_data = self::pumpioProfileData($data["url"]);
1479 if (!$profile_data) {
1483 $data = array_merge($data, $profile_data);
1485 if (($addr != '') && ($data['name'] != '')) {
1486 $name = trim(str_replace($addr, '', $data['name']));
1488 $data['name'] = $name;
1496 * @brief Check page for feed link
1498 * @param string $url Page link
1500 * @return string feed link
1502 private static function getFeedLink($url)
1504 $doc = new DOMDocument();
1506 if (!@$doc->loadHTMLFile($url)) {
1510 $xpath = new DomXPath($doc);
1512 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1513 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1514 if (!is_object($feeds)) {
1518 if ($feeds->length == 0) {
1524 foreach ($feeds as $feed) {
1526 foreach ($feed->attributes as $attribute) {
1527 $attr[$attribute->name] = trim($attribute->value);
1530 if ($feed_url == "") {
1531 $feed_url = $attr["href"];
1539 * @brief Check for feed contact
1541 * @param string $url Profile link
1542 * @param boolean $probe Do a probe if the page contains a feed link
1544 * @return array feed data
1546 private static function feed($url, $probe = true)
1548 $ret = Network::curl($url);
1549 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1552 $feed = $ret['body'];
1553 $dummy1 = $dummy2 = $dummy3 = null;
1554 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1561 $feed_url = self::getFeedLink($url);
1567 return self::feed($feed_url, false);
1570 if (!empty($feed_data["header"]["author-name"])) {
1571 $data["name"] = $feed_data["header"]["author-name"];
1574 if (!empty($feed_data["header"]["author-nick"])) {
1575 $data["nick"] = $feed_data["header"]["author-nick"];
1578 if (!empty($feed_data["header"]["author-avatar"])) {
1579 $data["photo"] = $feed_data["header"]["author-avatar"];
1582 if (!empty($feed_data["header"]["author-id"])) {
1583 $data["alias"] = $feed_data["header"]["author-id"];
1586 $data["url"] = $url;
1587 $data["poll"] = $url;
1589 if (!empty($feed_data["header"]["author-link"])) {
1590 $data["baseurl"] = $feed_data["header"]["author-link"];
1592 $data["baseurl"] = $data["url"];
1595 $data["network"] = Protocol::FEED;
1601 * @brief Check for mail contact
1603 * @param string $uri Profile link
1604 * @param integer $uid User ID
1606 * @return array mail data
1608 private static function mail($uri, $uid)
1610 if (!Network::isEmailDomainValid($uri)) {
1618 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1620 $condition = ["`uid` = ? AND `server` != ''", $uid];
1621 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1622 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1624 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1628 $mailbox = Email::constructMailboxName($mailacct);
1630 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1631 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1636 $msgs = Email::poll($mbox, $uri);
1637 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1639 if (!count($msgs)) {
1643 $phost = substr($uri, strpos($uri, '@') + 1);
1646 $data["addr"] = $uri;
1647 $data["network"] = Protocol::MAIL;
1648 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1649 $data["nick"] = $data["name"];
1650 $data["photo"] = Network::lookupAvatarByEmail($uri);
1651 $data["url"] = 'mailto:'.$uri;
1652 $data["notify"] = 'smtp '.random_string();
1653 $data["poll"] = 'email '.random_string();
1655 $x = Email::messageMeta($mbox, $msgs[0]);
1656 if (stristr($x[0]->from, $uri)) {
1657 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1658 } elseif (stristr($x[0]->to, $uri)) {
1659 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1662 foreach ($adr as $feadr) {
1663 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1664 &&(strcasecmp($feadr->host, $phost) == 0)
1665 && (strlen($feadr->personal))
1667 $personal = imap_mime_header_decode($feadr->personal);
1669 foreach ($personal as $perspart) {
1670 if ($perspart->charset != "default") {
1671 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1673 $data["name"] .= $perspart->text;
1677 $data["name"] = notags($data["name"]);
1681 if (!empty($mbox)) {
1688 * @brief Mix two paths together to possibly fix missing parts
1690 * @param string $avatar Path to the avatar
1691 * @param string $base Another path that is hopefully complete
1693 * @return string fixed avatar path
1695 public static function fixAvatar($avatar, $base)
1697 $base_parts = parse_url($base);
1699 // Remove all parts that could create a problem
1700 unset($base_parts['path']);
1701 unset($base_parts['query']);
1702 unset($base_parts['fragment']);
1704 $avatar_parts = parse_url($avatar);
1707 $parts = array_merge($base_parts, $avatar_parts);
1709 // And put them together again
1710 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1711 $host = isset($parts['host']) ? $parts['host'] : '';
1712 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1713 $path = isset($parts['path']) ? $parts['path'] : '';
1714 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1715 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1717 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1719 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);