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\Logger;
16 use Friendica\Core\Protocol;
17 use Friendica\Core\System;
18 use Friendica\Database\DBA;
19 use Friendica\Model\Contact;
20 use Friendica\Model\Profile;
21 use Friendica\Protocol\Email;
22 use Friendica\Protocol\Feed;
23 use Friendica\Protocol\ActivityPub;
24 use Friendica\Util\Crypto;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\Network;
27 use Friendica\Util\Strings;
28 use Friendica\Util\XML;
31 require_once 'include/dba.php';
34 * @brief This class contain functions for probing URL
39 private static $baseurl;
42 * @brief Rearrange the array so that it always has the same order
44 * @param array $data Unordered data
46 * @return array Ordered data
48 private static function rearrangeData($data)
50 $fields = ["name", "nick", "guid", "url", "addr", "alias",
51 "photo", "community", "keywords", "location", "about",
52 "batch", "notify", "poll", "request", "confirm", "poco",
53 "priority", "network", "pubkey", "baseurl"];
56 foreach ($fields as $field) {
57 if (isset($data[$field])) {
58 $newdata[$field] = $data[$field];
60 $newdata[$field] = "";
64 // We don't use the "priority" field anymore and replace it with a dummy.
65 $newdata["priority"] = 0;
71 * @brief Check if the hostname belongs to the own server
73 * @param string $host The hostname that is to be checked
75 * @return bool Does the testes hostname belongs to the own server?
77 private static function ownHost($host)
79 $own_host = get_app()->getHostName();
81 $parts = parse_url($host);
83 if (!isset($parts['scheme'])) {
84 $parts = parse_url('http://'.$host);
87 if (!isset($parts['host'])) {
90 return $parts['host'] == $own_host;
94 * @brief Probes for webfinger path via "host-meta"
96 * We have to check if the servers in the future still will offer this.
97 * It seems as if it was dropped from the standard.
99 * @param string $host The host part of an url
101 * @return array with template and type of the webfinger template for JSON or XML
103 private static function hostMeta($host)
105 // Reset the static variable
108 $ssl_url = "https://".$host."/.well-known/host-meta";
109 $url = "http://".$host."/.well-known/host-meta";
111 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
114 Logger::log("Probing for ".$host, Logger::DEBUG);
117 $curlResult = Network::curl($ssl_url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
118 if ($curlResult->isSuccess()) {
119 $xml = $curlResult->getBody();
120 $xrd = XML::parseString($xml, false);
121 $host_url = 'https://'.$host;
124 if (!is_object($xrd)) {
125 $curlResult = Network::curl($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
126 if ($curlResult->isTimeout()) {
127 Logger::log("Probing timeout for " . $url, Logger::DEBUG);
130 $xml = $curlResult->getBody();
131 $xrd = XML::parseString($xml, false);
132 $host_url = 'http://'.$host;
134 if (!is_object($xrd)) {
135 Logger::log("No xrd object found for ".$host, Logger::DEBUG);
139 $links = XML::elementToArray($xrd);
140 if (!isset($links["xrd"]["link"])) {
141 Logger::log("No xrd data found for ".$host, Logger::DEBUG);
146 // The following webfinger path is defined in RFC 7033 https://tools.ietf.org/html/rfc7033
147 // Problem is that Hubzilla currently doesn't provide all data in the JSON webfinger
148 // compared to the XML webfinger. So this is commented out by now.
149 // $lrdd = array("application/jrd+json" => $host_url.'/.well-known/webfinger?resource={uri}');
151 foreach ($links["xrd"]["link"] as $value => $link) {
152 if (!empty($link["@attributes"])) {
153 $attributes = $link["@attributes"];
154 } elseif ($value == "@attributes") {
160 if (($attributes["rel"] == "lrdd") && !empty($attributes["template"])) {
161 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
163 $lrdd[$type] = $attributes["template"];
167 self::$baseurl = "http://".$host;
169 Logger::log("Probing successful for ".$host, Logger::DEBUG);
175 * @brief Perform Webfinger lookup and return DFRN data
177 * Given an email style address, perform webfinger lookup and
178 * return the resulting DFRN profile URL, or if no DFRN profile URL
179 * is located, returns an OStatus subscription template (prefixed
180 * with the string 'stat:' to identify it as on OStatus template).
181 * If this isn't an email style address just return $webbie.
182 * Return an empty string if email-style addresses but webfinger fails,
183 * or if the resultant personal XRD doesn't contain a supported
184 * subscription/friend-request attribute.
186 * amended 7/9/2011 to return an hcard which could save potentially loading
187 * a lengthy content page to scrape dfrn attributes
189 * @param string $webbie Address that should be probed
190 * @param string $hcard_url Link to the hcard - is returned by reference
192 * @return string profile link
194 public static function webfingerDfrn($webbie, &$hcard_url)
198 $links = self::lrdd($webbie);
199 Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA);
201 foreach ($links as $link) {
202 if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
203 $profile_link = $link['@attributes']['href'];
205 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) && ($profile_link == "")) {
206 $profile_link = 'stat:'.$link['@attributes']['template'];
208 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
209 $hcard_url = $link['@attributes']['href'];
213 return $profile_link;
217 * @brief Check an URI for LRDD data
219 * this is a replacement for the "lrdd" function.
220 * It isn't used in this class and has some redundancies in the code.
221 * When time comes we can check the existing calls for "lrdd" if we can rework them.
223 * @param string $uri Address that should be probed
225 * @return array uri data
227 public static function lrdd($uri)
229 $lrdd = self::hostMeta($uri);
232 if (is_bool($lrdd)) {
237 $parts = @parse_url($uri);
238 if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
242 $host = $parts["host"];
243 if (!empty($parts["port"])) {
244 $host .= ':'.$parts["port"];
247 $path_parts = explode("/", trim($parts["path"], "/"));
249 $nick = array_pop($path_parts);
252 $lrdd = self::hostMeta($host);
253 $host .= "/".array_shift($path_parts);
254 } while (!$lrdd && (sizeof($path_parts) > 0));
258 Logger::log("No lrdd data found for ".$uri, Logger::DEBUG);
262 foreach ($lrdd as $type => $template) {
267 $path = str_replace('{uri}', urlencode($uri), $template);
268 $webfinger = self::webfinger($path, $type);
270 if (!$webfinger && (strstr($uri, "@"))) {
271 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
272 $webfinger = self::webfinger($path, $type);
275 // Special treatment for Mastodon
276 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
277 // But the webfinger for this format fails.
278 if (!$webfinger && !empty($nick)) {
279 // Mastodon uses a "@" as prefix for usernames in their url format
280 $nick = ltrim($nick, '@');
282 $addr = $nick."@".$host;
284 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
285 $webfinger = self::webfinger($path, $type);
289 if (!is_array($webfinger["links"])) {
290 Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
296 foreach ($webfinger["links"] as $link) {
297 $data[] = ["@attributes" => $link];
300 if (is_array($webfinger["aliases"])) {
301 foreach ($webfinger["aliases"] as $alias) {
302 $data[] = ["@attributes" =>
312 * @brief Fetch information (protocol endpoints and user information) about a given uri
314 * @param string $uri Address that should be probed
315 * @param string $network Test for this specific network
316 * @param integer $uid User ID for the probe (only used for mails)
317 * @param boolean $cache Use cached values?
319 * @return array uri data
321 public static function uri($uri, $network = '', $uid = -1, $cache = true)
324 $result = Cache::get('Probe::uri:' . $network . ':' . $uri);
325 if (!is_null($result)) {
334 if ($network != Protocol::ACTIVITYPUB) {
335 $data = self::detect($uri, $network, $uid);
340 $ap_profile = ActivityPub::probeProfile($uri);
342 if (!empty($ap_profile) && (defaults($data, 'network', '') != Protocol::DFRN)) {
346 if (!isset($data['url'])) {
350 if (x($data, 'photo')) {
351 $data['baseurl'] = Network::getUrlMatch(Strings::normaliseLink(defaults($data, 'baseurl', '')), Strings::normaliseLink($data['photo']));
353 $data['photo'] = System::baseUrl() . '/images/person-300.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)
401 'name' => $data['name'],
402 'nick' => $data['nick'],
403 'url' => $data['url'],
404 'addr' => $data['addr'],
405 'photo' => $data['photo'],
406 'keywords' => $data['keywords'],
407 'location' => $data['location'],
408 'about' => $data['about'],
409 'notify' => $data['notify'],
410 'network' => $data['network'],
411 'server_url' => $data['baseurl']
414 // This doesn't cover the case when a community isn't a community anymore
415 if (!empty($data['community']) && $data['community']) {
416 $fields['community'] = $data['community'];
417 $fields['contact-type'] = Contact::ACCOUNT_TYPE_COMMUNITY;
422 foreach ($fields as $key => $val) {
424 unset($fields[$key]);
426 $fieldnames[] = $key;
430 $fields['updated'] = DateTimeFormat::utcNow();
432 $condition = ['nurl' => Strings::normaliseLink($data['url'])];
434 $old_fields = DBA::selectFirst('gcontact', $fieldnames, $condition);
436 // When the gcontact doesn't exist, the value "true" will trigger an insert.
437 // In difference to the public contacts we want to have every contact
438 // in the world in our global contacts.
442 // These values have to be set only on insert
443 $fields['photo'] = $data['photo'];
444 $fields['created'] = DateTimeFormat::utcNow();
447 DBA::update('gcontact', $fields, $condition, $old_fields);
450 'name' => $data['name'],
451 'nick' => $data['nick'],
452 'url' => $data['url'],
453 'addr' => $data['addr'],
454 'alias' => $data['alias'],
455 'keywords' => $data['keywords'],
456 'location' => $data['location'],
457 'about' => $data['about'],
458 'batch' => $data['batch'],
459 'notify' => $data['notify'],
460 'poll' => $data['poll'],
461 'request' => $data['request'],
462 'confirm' => $data['confirm'],
463 'poco' => $data['poco'],
464 'network' => $data['network'],
465 'pubkey' => $data['pubkey'],
466 'priority' => $data['priority'],
468 'rel' => Contact::SHARING
473 foreach ($fields as $key => $val) {
475 unset($fields[$key]);
477 $fieldnames[] = $key;
481 $condition = ['nurl' => Strings::normaliseLink($data['url']), 'self' => false, 'uid' => 0];
483 // "$old_fields" will return a "false" when the contact doesn't exist.
484 // This won't trigger an insert. This is intended, since we only need
485 // public contacts for everyone we store items from.
486 // We don't need to store every contact on the planet.
487 $old_fields = DBA::selectFirst('contact', $fieldnames, $condition);
489 $fields['name-date'] = DateTimeFormat::utcNow();
490 $fields['uri-date'] = DateTimeFormat::utcNow();
491 $fields['success_update'] = DateTimeFormat::utcNow();
493 DBA::update('contact', $fields, $condition, $old_fields);
501 * @brief Switch the scheme of an url between http and https
503 * @param string $url URL
505 * @return string switched URL
507 private static function switchScheme($url)
509 $parts = parse_url($url);
511 if (!isset($parts['scheme'])) {
515 if ($parts['scheme'] == 'http') {
516 $url = str_replace('http://', 'https://', $url);
517 } elseif ($parts['scheme'] == 'https') {
518 $url = str_replace('https://', 'http://', $url);
525 * @brief Checks if a profile url should be OStatus but only provides partial information
527 * @param array $webfinger Webfinger data
528 * @param string $lrdd Path template for webfinger request
529 * @param string $type type
531 * @return array fixed webfinger data
533 private static function fixOStatus($webfinger, $lrdd, $type)
535 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
542 foreach ($webfinger['links'] as $link) {
543 if ($link['rel'] == NAMESPACE_OSTATUSSUB) {
546 if ($link['rel'] == 'magic-public-key') {
551 if (!$is_ostatus || $has_key) {
555 $url = self::switchScheme($webfinger['subject']);
556 $path = str_replace('{uri}', urlencode($url), $lrdd);
557 $webfinger2 = self::webfinger($path, $type);
559 // Is the new webfinger detectable as OStatus?
560 if (self::ostatus($webfinger2, true)) {
561 $webfinger = $webfinger2;
568 * @brief Fetch information (protocol endpoints and user information) about a given uri
570 * This function is only called by the "uri" function that adds caching and rearranging of data.
572 * @param string $uri Address that should be probed
573 * @param string $network Test for this specific network
574 * @param integer $uid User ID for the probe (only used for mails)
576 * @return array uri data
578 private static function detect($uri, $network, $uid)
580 $parts = parse_url($uri);
582 if (!empty($parts["scheme"]) && !empty($parts["host"])) {
583 $host = $parts["host"];
584 if (!empty($parts["port"])) {
585 $host .= ':'.$parts["port"];
588 if ($host == 'twitter.com') {
589 return ["network" => Protocol::TWITTER];
591 $lrdd = self::hostMeta($host);
593 if (is_bool($lrdd)) {
597 $path_parts = explode("/", trim(defaults($parts, 'path', ''), "/"));
599 while (!$lrdd && (sizeof($path_parts) > 1)) {
600 $host .= "/".array_shift($path_parts);
601 $lrdd = self::hostMeta($host);
604 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
605 return self::feed($uri);
607 $nick = array_pop($path_parts);
609 // Mastodon uses a "@" as prefix for usernames in their url format
610 $nick = ltrim($nick, '@');
612 $addr = $nick."@".$host;
613 } elseif (strstr($uri, '@')) {
614 // If the URI starts with "mailto:" then jump directly to the mail detection
615 if (strpos($uri, 'mailto:') !== false) {
616 $uri = str_replace('mailto:', '', $uri);
617 return self::mail($uri, $uid);
620 if ($network == Protocol::MAIL) {
621 return self::mail($uri, $uid);
623 // Remove "acct:" from the URI
624 $uri = str_replace('acct:', '', $uri);
626 $host = substr($uri, strpos($uri, '@') + 1);
627 $nick = substr($uri, 0, strpos($uri, '@'));
629 if (strpos($uri, '@twitter.com')) {
630 return ["network" => Protocol::TWITTER];
632 $lrdd = self::hostMeta($host);
634 if (is_bool($lrdd)) {
639 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
640 return self::mail($uri, $uid);
644 Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
650 /// @todo Do we need the prefix "acct:" or "acct://"?
652 foreach ($lrdd as $type => $template) {
657 // At first try it with the given uri
658 $path = str_replace('{uri}', urlencode($uri), $template);
659 $webfinger = self::webfinger($path, $type);
661 // Fix possible problems with GNU Social probing to wrong scheme
662 $webfinger = self::fixOStatus($webfinger, $template, $type);
664 // We cannot be sure that the detected address was correct, so we don't use the values
665 if ($webfinger && ($uri != $addr)) {
670 // Try webfinger with the address (user@domain.tld)
672 $path = str_replace('{uri}', urlencode($addr), $template);
673 $webfinger = self::webfinger($path, $type);
676 // Mastodon needs to have it with "acct:"
678 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
679 $webfinger = self::webfinger($path, $type);
684 return self::feed($uri);
689 Logger::log("Probing ".$uri, Logger::DEBUG);
691 if (in_array($network, ["", Protocol::DFRN])) {
692 $result = self::dfrn($webfinger);
694 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
695 $result = self::diaspora($webfinger);
697 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
698 $result = self::ostatus($webfinger);
700 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
701 $result = self::pumpio($webfinger, $addr);
703 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
704 $result = self::feed($uri);
706 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
707 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
708 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
709 $result["nick"] = $nick;
712 if (empty($result["addr"]) && ($addr != "")) {
713 $result["addr"] = $addr;
717 if (empty($result["network"])) {
718 $result["network"] = Protocol::PHANTOM;
721 if (empty($result["url"])) {
722 $result["url"] = $uri;
725 Logger::log($uri." is ".$result["network"], Logger::DEBUG);
727 if (empty($result["baseurl"])) {
728 $pos = strpos($result["url"], $host);
730 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
737 * @brief Perform a webfinger request.
739 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
741 * @param string $url Address that should be probed
742 * @param string $type type
744 * @return array webfinger data
746 private static function webfinger($url, $type)
748 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
751 $curlResult = Network::curl($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
752 if ($curlResult->isTimeout()) {
755 $data = $curlResult->getBody();
757 $webfinger = json_decode($data, true);
758 if (is_array($webfinger)) {
759 if (!isset($webfinger["links"])) {
760 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
766 // If it is not JSON, maybe it is XML
767 $xrd = XML::parseString($data, false);
768 if (!is_object($xrd)) {
769 Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
773 $xrd_arr = XML::elementToArray($xrd);
774 if (!isset($xrd_arr["xrd"]["link"])) {
775 Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
781 if (!empty($xrd_arr["xrd"]["subject"])) {
782 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
785 if (!empty($xrd_arr["xrd"]["alias"])) {
786 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
789 $webfinger["links"] = [];
791 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
792 if (!empty($data["@attributes"])) {
793 $attributes = $data["@attributes"];
794 } elseif ($value == "@attributes") {
800 $webfinger["links"][] = $attributes;
806 * @brief Poll the Friendica specific noscrape page.
808 * "noscrape" is a faster alternative to fetch the data from the hcard.
809 * This functionality was originally created for the directory.
811 * @param string $noscrape_url Link to the noscrape page
812 * @param array $data The already fetched data
814 * @return array noscrape data
816 private static function pollNoscrape($noscrape_url, $data)
818 $curlResult = Network::curl($noscrape_url);
819 if ($curlResult->isTimeout()) {
822 $content = $curlResult->getBody();
824 Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
828 $json = json_decode($content, true);
829 if (!is_array($json)) {
830 Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
834 if (!empty($json["fn"])) {
835 $data["name"] = $json["fn"];
838 if (!empty($json["addr"])) {
839 $data["addr"] = $json["addr"];
842 if (!empty($json["nick"])) {
843 $data["nick"] = $json["nick"];
846 if (!empty($json["guid"])) {
847 $data["guid"] = $json["guid"];
850 if (!empty($json["comm"])) {
851 $data["community"] = $json["comm"];
854 if (!empty($json["tags"])) {
855 $keywords = implode(" ", $json["tags"]);
856 if ($keywords != "") {
857 $data["keywords"] = $keywords;
861 $location = Profile::formatLocation($json);
863 $data["location"] = $location;
866 if (!empty($json["about"])) {
867 $data["about"] = $json["about"];
870 if (!empty($json["key"])) {
871 $data["pubkey"] = $json["key"];
874 if (!empty($json["photo"])) {
875 $data["photo"] = $json["photo"];
878 if (!empty($json["dfrn-request"])) {
879 $data["request"] = $json["dfrn-request"];
882 if (!empty($json["dfrn-confirm"])) {
883 $data["confirm"] = $json["dfrn-confirm"];
886 if (!empty($json["dfrn-notify"])) {
887 $data["notify"] = $json["dfrn-notify"];
890 if (!empty($json["dfrn-poll"])) {
891 $data["poll"] = $json["dfrn-poll"];
898 * @brief Check for valid DFRN data
900 * @param array $data DFRN data
902 * @return int Number of errors
904 public static function validDfrn($data)
907 if (!isset($data['key'])) {
910 if (!isset($data['dfrn-request'])) {
913 if (!isset($data['dfrn-confirm'])) {
916 if (!isset($data['dfrn-notify'])) {
919 if (!isset($data['dfrn-poll'])) {
926 * @brief Fetch data from a DFRN profile page and via "noscrape"
928 * @param string $profile_link Link to the profile page
930 * @return array profile data
932 public static function profile($profile_link)
936 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
938 // Fetch data via noscrape - this is faster
939 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
940 $data = self::pollNoscrape($noscrape_url, $data);
942 if (!isset($data["notify"])
943 || !isset($data["confirm"])
944 || !isset($data["request"])
945 || !isset($data["poll"])
946 || !isset($data["name"])
947 || !isset($data["photo"])
949 $data = self::pollHcard($profile_link, $data, true);
954 if (empty($data["addr"]) || empty($data["nick"])) {
955 $probe_data = self::uri($profile_link);
956 $data["addr"] = defaults($data, "addr", $probe_data["addr"]);
957 $data["nick"] = defaults($data, "nick", $probe_data["nick"]);
960 $prof_data["addr"] = $data["addr"];
961 $prof_data["nick"] = $data["nick"];
962 $prof_data["dfrn-request"] = defaults($data, 'request', null);
963 $prof_data["dfrn-confirm"] = defaults($data, 'confirm', null);
964 $prof_data["dfrn-notify"] = defaults($data, 'notify' , null);
965 $prof_data["dfrn-poll"] = defaults($data, 'poll' , null);
966 $prof_data["photo"] = defaults($data, 'photo' , null);
967 $prof_data["fn"] = defaults($data, 'name' , null);
968 $prof_data["key"] = defaults($data, 'pubkey' , null);
970 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
976 * @brief Check for DFRN contact
978 * @param array $webfinger Webfinger data
980 * @return array DFRN data
982 private static function dfrn($webfinger)
986 // The array is reversed to take into account the order of preference for same-rel links
987 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
988 foreach (array_reverse($webfinger["links"]) as $link) {
989 if (($link["rel"] == NAMESPACE_DFRN) && !empty($link["href"])) {
990 $data["network"] = Protocol::DFRN;
991 } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
992 $data["poll"] = $link["href"];
993 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (defaults($link, "type", "") == "text/html") && !empty($link["href"])) {
994 $data["url"] = $link["href"];
995 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
996 $hcard_url = $link["href"];
997 } elseif (($link["rel"] == NAMESPACE_POCO) && !empty($link["href"])) {
998 $data["poco"] = $link["href"];
999 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1000 $data["photo"] = $link["href"];
1001 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1002 $data["baseurl"] = trim($link["href"], '/');
1003 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1004 $data["guid"] = $link["href"];
1005 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1006 $data["pubkey"] = base64_decode($link["href"]);
1008 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1009 if (strstr($data["pubkey"], 'RSA ')) {
1010 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1015 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1016 foreach ($webfinger["aliases"] as $alias) {
1017 if (empty($data["url"]) && !strstr($alias, "@")) {
1018 $data["url"] = $alias;
1019 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1020 $data["alias"] = $alias;
1021 } elseif (substr($alias, 0, 5) == 'acct:') {
1022 $data["addr"] = substr($alias, 5);
1027 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1028 $data["addr"] = substr($webfinger["subject"], 5);
1031 if (!isset($data["network"]) || ($hcard_url == "")) {
1035 // Fetch data via noscrape - this is faster
1036 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1037 $data = self::pollNoscrape($noscrape_url, $data);
1039 if (isset($data["notify"])
1040 && isset($data["confirm"])
1041 && isset($data["request"])
1042 && isset($data["poll"])
1043 && isset($data["name"])
1044 && isset($data["photo"])
1049 $data = self::pollHcard($hcard_url, $data, true);
1055 * @brief Poll the hcard page (Diaspora and Friendica specific)
1057 * @param string $hcard_url Link to the hcard page
1058 * @param array $data The already fetched data
1059 * @param boolean $dfrn Poll DFRN specific data
1061 * @return array hcard data
1063 private static function pollHcard($hcard_url, $data, $dfrn = false)
1065 $curlResult = Network::curl($hcard_url);
1066 if ($curlResult->isTimeout()) {
1069 $content = $curlResult->getBody();
1074 $doc = new DOMDocument();
1075 if (!@$doc->loadHTML($content)) {
1079 $xpath = new DomXPath($doc);
1081 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1082 if (!is_object($vcards)) {
1086 if (!isset($data["baseurl"])) {
1087 $data["baseurl"] = "";
1090 if ($vcards->length > 0) {
1091 $vcard = $vcards->item(0);
1093 // We have to discard the guid from the hcard in favour of the guid from lrdd
1094 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1095 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1096 if (($search->length > 0) && empty($data["guid"])) {
1097 $data["guid"] = $search->item(0)->nodeValue;
1100 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1101 if ($search->length > 0) {
1102 $data["nick"] = $search->item(0)->nodeValue;
1105 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1106 if ($search->length > 0) {
1107 $data["name"] = $search->item(0)->nodeValue;
1110 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1111 if ($search->length > 0) {
1112 $data["searchable"] = $search->item(0)->nodeValue;
1115 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1116 if ($search->length > 0) {
1117 $data["pubkey"] = $search->item(0)->nodeValue;
1118 if (strstr($data["pubkey"], 'RSA ')) {
1119 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1123 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1124 if ($search->length > 0) {
1125 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1130 if (!empty($vcard)) {
1131 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1132 foreach ($photos as $photo) {
1134 foreach ($photo->attributes as $attribute) {
1135 $attr[$attribute->name] = trim($attribute->value);
1138 if (isset($attr["src"]) && isset($attr["width"])) {
1139 $avatar[$attr["width"]] = $attr["src"];
1142 // We don't have a width. So we just take everything that we got.
1143 // This is a Hubzilla workaround which doesn't send a width.
1144 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1145 $avatar[] = $attr["src"];
1150 if (sizeof($avatar)) {
1152 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1156 // Poll DFRN specific data
1157 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1158 if ($search->length > 0) {
1159 foreach ($search as $link) {
1160 //$data["request"] = $search->item(0)->nodeValue;
1162 foreach ($link->attributes as $attribute) {
1163 $attr[$attribute->name] = trim($attribute->value);
1166 $data[substr($attr["rel"], 5)] = $attr["href"];
1170 // Older Friendica versions had used the "uid" field differently than newer versions
1171 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1172 unset($data["guid"]);
1181 * @brief Check for Diaspora contact
1183 * @param array $webfinger Webfinger data
1185 * @return array Diaspora data
1187 private static function diaspora($webfinger)
1191 // The array is reversed to take into account the order of preference for same-rel links
1192 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1193 foreach (array_reverse($webfinger["links"]) as $link) {
1194 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1195 $hcard_url = $link["href"];
1196 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1197 $data["baseurl"] = trim($link["href"], '/');
1198 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1199 $data["guid"] = $link["href"];
1200 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (defaults($link, "type", "") == "text/html") && !empty($link["href"])) {
1201 $data["url"] = $link["href"];
1202 } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
1203 $data["poll"] = $link["href"];
1204 } elseif (($link["rel"] == NAMESPACE_POCO) && !empty($link["href"])) {
1205 $data["poco"] = $link["href"];
1206 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1207 $data["notify"] = $link["href"];
1208 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1209 $data["pubkey"] = base64_decode($link["href"]);
1211 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1212 if (strstr($data["pubkey"], 'RSA ')) {
1213 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1218 if (!isset($data["url"]) || ($hcard_url == "")) {
1222 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1223 foreach ($webfinger["aliases"] as $alias) {
1224 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1225 $data["alias"] = $alias;
1226 } elseif (substr($alias, 0, 5) == 'acct:') {
1227 $data["addr"] = substr($alias, 5);
1232 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1233 $data["addr"] = substr($webfinger["subject"], 5);
1236 // Fetch further information from the hcard
1237 $data = self::pollHcard($hcard_url, $data);
1243 if (isset($data["url"])
1244 && isset($data["guid"])
1245 && isset($data["baseurl"])
1246 && isset($data["pubkey"])
1247 && ($hcard_url != "")
1249 $data["network"] = Protocol::DIASPORA;
1251 // The Diaspora handle must always be lowercase
1252 if (!empty($data["addr"])) {
1253 $data["addr"] = strtolower($data["addr"]);
1256 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1257 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1258 $data["batch"] = $data["baseurl"] . "/receive/public";
1267 * @brief Check for OStatus contact
1269 * @param array $webfinger Webfinger data
1270 * @param bool $short Short detection mode
1272 * @return array|bool OStatus data or "false" on error or "true" on short mode
1274 private static function ostatus($webfinger, $short = false)
1278 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1279 foreach ($webfinger["aliases"] as $alias) {
1280 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1281 $data["addr"] = str_replace('acct:', '', $alias);
1286 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1287 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1289 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1293 if (is_array($webfinger["links"])) {
1294 // The array is reversed to take into account the order of preference for same-rel links
1295 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1296 foreach (array_reverse($webfinger["links"]) as $link) {
1297 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1298 && (defaults($link, "type", "") == "text/html")
1299 && ($link["href"] != "")
1301 $data["url"] = $link["href"];
1302 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1303 $data["notify"] = $link["href"];
1304 } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
1305 $data["poll"] = $link["href"];
1306 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1307 $pubkey = $link["href"];
1309 if (substr($pubkey, 0, 5) === 'data:') {
1310 if (strstr($pubkey, ',')) {
1311 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1313 $pubkey = substr($pubkey, 5);
1315 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1316 $curlResult = Network::curl($pubkey);
1317 if ($curlResult->isTimeout()) {
1320 $pubkey = $curlResult['body'];
1323 $key = explode(".", $pubkey);
1325 if (sizeof($key) >= 3) {
1326 $m = Strings::base64UrlDecode($key[1]);
1327 $e = Strings::base64UrlDecode($key[2]);
1328 $data["pubkey"] = Crypto::meToPem($m, $e);
1334 if (isset($data["notify"]) && isset($data["pubkey"])
1335 && isset($data["poll"])
1336 && isset($data["url"])
1338 $data["network"] = Protocol::OSTATUS;
1347 // Fetch all additional data from the feed
1348 $curlResult = Network::curl($data["poll"]);
1349 if ($curlResult->isTimeout()) {
1352 $feed = $curlResult->getBody();
1356 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1361 if (!empty($feed_data["header"]["author-name"])) {
1362 $data["name"] = $feed_data["header"]["author-name"];
1364 if (!empty($feed_data["header"]["author-nick"])) {
1365 $data["nick"] = $feed_data["header"]["author-nick"];
1367 if (!empty($feed_data["header"]["author-avatar"])) {
1368 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1370 if (!empty($feed_data["header"]["author-id"])) {
1371 $data["alias"] = $feed_data["header"]["author-id"];
1373 if (!empty($feed_data["header"]["author-location"])) {
1374 $data["location"] = $feed_data["header"]["author-location"];
1376 if (!empty($feed_data["header"]["author-about"])) {
1377 $data["about"] = $feed_data["header"]["author-about"];
1379 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1380 // So we take the value that we just fetched, although the other one worked as well
1381 if (!empty($feed_data["header"]["author-link"])) {
1382 $data["url"] = $feed_data["header"]["author-link"];
1385 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1386 $data['url'] = $data["alias"];
1387 $data["alias"] = '';
1390 /// @todo Fetch location and "about" from the feed as well
1395 * @brief Fetch data from a pump.io profile page
1397 * @param string $profile_link Link to the profile page
1399 * @return array profile data
1401 private static function pumpioProfileData($profile_link)
1403 $doc = new DOMDocument();
1404 if (!@$doc->loadHTMLFile($profile_link)) {
1408 $xpath = new DomXPath($doc);
1412 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1414 if ($data["name"] == '') {
1415 // This is ugly - but pump.io doesn't seem to know a better way for it
1416 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1417 $pos = strpos($data["name"], chr(10));
1419 $data["name"] = trim(substr($data["name"], 0, $pos));
1423 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1425 if ($data["location"] == '') {
1426 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1429 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1431 if ($data["about"] == '') {
1432 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1435 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1437 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1440 foreach ($avatar->attributes as $attribute) {
1441 if ($attribute->name == "src") {
1442 $data["photo"] = trim($attribute->value);
1451 * @brief Check for pump.io contact
1453 * @param array $webfinger Webfinger data
1455 * @return array pump.io data
1457 private static function pumpio($webfinger, $addr)
1460 // The array is reversed to take into account the order of preference for same-rel links
1461 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1462 foreach (array_reverse($webfinger["links"]) as $link) {
1463 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1464 && (defaults($link, "type", "") == "text/html")
1465 && ($link["href"] != "")
1467 $data["url"] = $link["href"];
1468 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1469 $data["notify"] = $link["href"];
1470 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1471 $data["poll"] = $link["href"];
1472 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1473 $data["dialback"] = $link["href"];
1476 if (isset($data["poll"]) && isset($data["notify"])
1477 && isset($data["dialback"])
1478 && isset($data["url"])
1480 // by now we use these fields only for the network type detection
1481 // So we unset all data that isn't used at the moment
1482 unset($data["dialback"]);
1484 $data["network"] = Protocol::PUMPIO;
1489 $profile_data = self::pumpioProfileData($data["url"]);
1491 if (!$profile_data) {
1495 $data = array_merge($data, $profile_data);
1497 if (($addr != '') && ($data['name'] != '')) {
1498 $name = trim(str_replace($addr, '', $data['name']));
1500 $data['name'] = $name;
1508 * @brief Check page for feed link
1510 * @param string $url Page link
1512 * @return string feed link
1514 private static function getFeedLink($url)
1516 $doc = new DOMDocument();
1518 if (!@$doc->loadHTMLFile($url)) {
1522 $xpath = new DomXPath($doc);
1524 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1525 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1526 if (!is_object($feeds)) {
1530 if ($feeds->length == 0) {
1536 foreach ($feeds as $feed) {
1538 foreach ($feed->attributes as $attribute) {
1539 $attr[$attribute->name] = trim($attribute->value);
1542 if ($feed_url == "") {
1543 $feed_url = $attr["href"];
1551 * @brief Check for feed contact
1553 * @param string $url Profile link
1554 * @param boolean $probe Do a probe if the page contains a feed link
1556 * @return array feed data
1558 private static function feed($url, $probe = true)
1560 $curlResult = Network::curl($url);
1561 if ($curlResult->isTimeout()) {
1564 $feed = $curlResult->getBody();
1565 $dummy1 = $dummy2 = $dummy3 = null;
1566 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1573 $feed_url = self::getFeedLink($url);
1579 return self::feed($feed_url, false);
1582 if (!empty($feed_data["header"]["author-name"])) {
1583 $data["name"] = $feed_data["header"]["author-name"];
1586 if (!empty($feed_data["header"]["author-nick"])) {
1587 $data["nick"] = $feed_data["header"]["author-nick"];
1590 if (!empty($feed_data["header"]["author-avatar"])) {
1591 $data["photo"] = $feed_data["header"]["author-avatar"];
1594 if (!empty($feed_data["header"]["author-id"])) {
1595 $data["alias"] = $feed_data["header"]["author-id"];
1598 $data["url"] = $url;
1599 $data["poll"] = $url;
1601 if (!empty($feed_data["header"]["author-link"])) {
1602 $data["baseurl"] = $feed_data["header"]["author-link"];
1604 $data["baseurl"] = $data["url"];
1607 $data["network"] = Protocol::FEED;
1613 * @brief Check for mail contact
1615 * @param string $uri Profile link
1616 * @param integer $uid User ID
1618 * @return array mail data
1620 private static function mail($uri, $uid)
1622 if (!Network::isEmailDomainValid($uri)) {
1630 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1632 $condition = ["`uid` = ? AND `server` != ''", $uid];
1633 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1634 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1636 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1640 $mailbox = Email::constructMailboxName($mailacct);
1642 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1643 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1648 $msgs = Email::poll($mbox, $uri);
1649 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1651 if (!count($msgs)) {
1655 $phost = substr($uri, strpos($uri, '@') + 1);
1658 $data["addr"] = $uri;
1659 $data["network"] = Protocol::MAIL;
1660 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1661 $data["nick"] = $data["name"];
1662 $data["photo"] = Network::lookupAvatarByEmail($uri);
1663 $data["url"] = 'mailto:'.$uri;
1664 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1665 $data["poll"] = 'email ' . Strings::getRandomHex();
1667 $x = Email::messageMeta($mbox, $msgs[0]);
1668 if (stristr($x[0]->from, $uri)) {
1669 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1670 } elseif (stristr($x[0]->to, $uri)) {
1671 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1674 foreach ($adr as $feadr) {
1675 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1676 &&(strcasecmp($feadr->host, $phost) == 0)
1677 && (strlen($feadr->personal))
1679 $personal = imap_mime_header_decode($feadr->personal);
1681 foreach ($personal as $perspart) {
1682 if ($perspart->charset != "default") {
1683 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1685 $data["name"] .= $perspart->text;
1689 $data["name"] = Strings::escapeTags($data["name"]);
1693 if (!empty($mbox)) {
1700 * @brief Mix two paths together to possibly fix missing parts
1702 * @param string $avatar Path to the avatar
1703 * @param string $base Another path that is hopefully complete
1705 * @return string fixed avatar path
1707 public static function fixAvatar($avatar, $base)
1709 $base_parts = parse_url($base);
1711 // Remove all parts that could create a problem
1712 unset($base_parts['path']);
1713 unset($base_parts['query']);
1714 unset($base_parts['fragment']);
1716 $avatar_parts = parse_url($avatar);
1719 $parts = array_merge($base_parts, $avatar_parts);
1721 // And put them together again
1722 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1723 $host = isset($parts['host']) ? $parts['host'] : '';
1724 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1725 $path = isset($parts['path']) ? $parts['path'] : '';
1726 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1727 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1729 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1731 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);