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;
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()->getHostName();
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::log("Probing for ".$host, Logger::DEBUG);
115 $curlResult = Network::curl($ssl_url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
116 if ($curlResult->isSuccess()) {
117 $xml = $curlResult->getBody();
118 $xrd = XML::parseString($xml, false);
119 $host_url = 'https://'.$host;
122 if (!is_object($xrd)) {
123 $curlResult = Network::curl($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
124 if ($curlResult->isTimeout()) {
125 Logger::log("Probing timeout for " . $url, Logger::DEBUG);
128 $xml = $curlResult->getBody();
129 $xrd = XML::parseString($xml, false);
130 $host_url = 'http://'.$host;
132 if (!is_object($xrd)) {
133 Logger::log("No xrd object found for ".$host, Logger::DEBUG);
137 $links = XML::elementToArray($xrd);
138 if (!isset($links["xrd"]["link"])) {
139 Logger::log("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 = $host_url;
167 Logger::log("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::log('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::log("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::log("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)) {
344 if (!isset($data['url'])) {
348 if (!empty($data['photo'])) {
349 $data['baseurl'] = Network::getUrlMatch(Strings::normaliseLink(defaults($data, 'baseurl', '')), Strings::normaliseLink($data['photo']));
351 $data['photo'] = System::baseUrl() . '/images/person-300.jpg';
354 if (empty($data['name'])) {
355 if (!empty($data['nick'])) {
356 $data['name'] = $data['nick'];
359 if (empty($data['name'])) {
360 $data['name'] = $data['url'];
364 if (empty($data['nick'])) {
365 $data['nick'] = strtolower($data['name']);
367 if (strpos($data['nick'], ' ')) {
368 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
372 if (!empty(self::$baseurl)) {
373 $data['baseurl'] = self::$baseurl;
376 if (empty($data['network'])) {
377 $data['network'] = Protocol::PHANTOM;
380 $data = self::rearrangeData($data);
382 // Only store into the cache if the value seems to be valid
383 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
384 Cache::set('Probe::uri:' . $network . ':' . $uri, $data, Cache::DAY);
386 /// @todo temporary fix - we need a real contact update function that updates only changing fields
387 /// The biggest problem is the avatar picture that could have a reduced image size.
388 /// It should only be updated if the existing picture isn't existing anymore.
389 /// We only update the contact when it is no probing for a specific network.
390 if (($data['network'] != Protocol::FEED)
399 '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']
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' => Strings::normaliseLink($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);
448 'name' => $data['name'],
449 'nick' => $data['nick'],
450 'url' => $data['url'],
451 'addr' => $data['addr'],
452 'alias' => $data['alias'],
453 'keywords' => $data['keywords'],
454 'location' => $data['location'],
455 'about' => $data['about'],
456 'batch' => $data['batch'],
457 'notify' => $data['notify'],
458 'poll' => $data['poll'],
459 'request' => $data['request'],
460 'confirm' => $data['confirm'],
461 'poco' => $data['poco'],
462 'network' => $data['network'],
463 'pubkey' => $data['pubkey'],
464 'priority' => $data['priority'],
466 'rel' => Contact::SHARING
471 foreach ($fields as $key => $val) {
473 unset($fields[$key]);
475 $fieldnames[] = $key;
479 $condition = ['nurl' => Strings::normaliseLink($data['url']), 'self' => false, 'uid' => 0];
481 // "$old_fields" will return a "false" when the contact doesn't exist.
482 // This won't trigger an insert. This is intended, since we only need
483 // public contacts for everyone we store items from.
484 // We don't need to store every contact on the planet.
485 $old_fields = DBA::selectFirst('contact', $fieldnames, $condition);
487 $fields['name-date'] = DateTimeFormat::utcNow();
488 $fields['uri-date'] = DateTimeFormat::utcNow();
489 $fields['success_update'] = DateTimeFormat::utcNow();
491 DBA::update('contact', $fields, $condition, $old_fields);
499 * @brief Switch the scheme of an url between http and https
501 * @param string $url URL
503 * @return string switched URL
505 private static function switchScheme($url)
507 $parts = parse_url($url);
509 if (!isset($parts['scheme'])) {
513 if ($parts['scheme'] == 'http') {
514 $url = str_replace('http://', 'https://', $url);
515 } elseif ($parts['scheme'] == 'https') {
516 $url = str_replace('https://', 'http://', $url);
523 * @brief Checks if a profile url should be OStatus but only provides partial information
525 * @param array $webfinger Webfinger data
526 * @param string $lrdd Path template for webfinger request
527 * @param string $type type
529 * @return array fixed webfinger data
531 private static function fixOStatus($webfinger, $lrdd, $type)
533 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
540 foreach ($webfinger['links'] as $link) {
541 if ($link['rel'] == NAMESPACE_OSTATUSSUB) {
544 if ($link['rel'] == 'magic-public-key') {
549 if (!$is_ostatus || $has_key) {
553 $url = self::switchScheme($webfinger['subject']);
554 $path = str_replace('{uri}', urlencode($url), $lrdd);
555 $webfinger2 = self::webfinger($path, $type);
557 // Is the new webfinger detectable as OStatus?
558 if (self::ostatus($webfinger2, true)) {
559 $webfinger = $webfinger2;
566 * @brief Fetch information (protocol endpoints and user information) about a given uri
568 * This function is only called by the "uri" function that adds caching and rearranging of data.
570 * @param string $uri Address that should be probed
571 * @param string $network Test for this specific network
572 * @param integer $uid User ID for the probe (only used for mails)
574 * @return array uri data
576 private static function detect($uri, $network, $uid)
578 $parts = parse_url($uri);
580 if (!empty($parts["scheme"]) && !empty($parts["host"])) {
581 $host = $parts["host"];
582 if (!empty($parts["port"])) {
583 $host .= ':'.$parts["port"];
586 if ($host == 'twitter.com') {
587 return ["network" => Protocol::TWITTER];
589 $lrdd = self::hostMeta($host);
591 if (is_bool($lrdd)) {
595 $path_parts = explode("/", trim(defaults($parts, 'path', ''), "/"));
597 while (!$lrdd && (sizeof($path_parts) > 1)) {
598 $host .= "/".array_shift($path_parts);
599 $lrdd = self::hostMeta($host);
602 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
603 return self::feed($uri);
605 $nick = array_pop($path_parts);
607 // Mastodon uses a "@" as prefix for usernames in their url format
608 $nick = ltrim($nick, '@');
610 $addr = $nick."@".$host;
611 } elseif (strstr($uri, '@')) {
612 // If the URI starts with "mailto:" then jump directly to the mail detection
613 if (strpos($uri, 'mailto:') !== false) {
614 $uri = str_replace('mailto:', '', $uri);
615 return self::mail($uri, $uid);
618 if ($network == Protocol::MAIL) {
619 return self::mail($uri, $uid);
621 // Remove "acct:" from the URI
622 $uri = str_replace('acct:', '', $uri);
624 $host = substr($uri, strpos($uri, '@') + 1);
625 $nick = substr($uri, 0, strpos($uri, '@'));
627 if (strpos($uri, '@twitter.com')) {
628 return ["network" => Protocol::TWITTER];
630 $lrdd = self::hostMeta($host);
632 if (is_bool($lrdd)) {
637 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
638 return self::mail($uri, $uid);
642 Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
648 /// @todo Do we need the prefix "acct:" or "acct://"?
650 foreach ($lrdd as $type => $template) {
655 // At first try it with the given uri
656 $path = str_replace('{uri}', urlencode($uri), $template);
657 $webfinger = self::webfinger($path, $type);
659 // Fix possible problems with GNU Social probing to wrong scheme
660 $webfinger = self::fixOStatus($webfinger, $template, $type);
662 // We cannot be sure that the detected address was correct, so we don't use the values
663 if ($webfinger && ($uri != $addr)) {
668 // Try webfinger with the address (user@domain.tld)
670 $path = str_replace('{uri}', urlencode($addr), $template);
671 $webfinger = self::webfinger($path, $type);
674 // Mastodon needs to have it with "acct:"
676 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
677 $webfinger = self::webfinger($path, $type);
682 return self::feed($uri);
687 Logger::log("Probing ".$uri, Logger::DEBUG);
689 if (in_array($network, ["", Protocol::DFRN])) {
690 $result = self::dfrn($webfinger);
692 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
693 $result = self::diaspora($webfinger);
695 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
696 $result = self::ostatus($webfinger);
698 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
699 $result = self::pumpio($webfinger, $addr);
701 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
702 $result = self::feed($uri);
704 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
705 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
706 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
707 $result["nick"] = $nick;
710 if (empty($result["addr"]) && ($addr != "")) {
711 $result["addr"] = $addr;
715 if (empty($result["network"])) {
716 $result["network"] = Protocol::PHANTOM;
719 if (empty($result["url"])) {
720 $result["url"] = $uri;
723 Logger::log($uri." is ".$result["network"], Logger::DEBUG);
725 if (empty($result["baseurl"])) {
726 $pos = strpos($result["url"], $host);
728 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
735 * @brief Perform a webfinger request.
737 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
739 * @param string $url Address that should be probed
740 * @param string $type type
742 * @return array webfinger data
744 private static function webfinger($url, $type)
746 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
749 $curlResult = Network::curl($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
750 if ($curlResult->isTimeout()) {
753 $data = $curlResult->getBody();
755 $webfinger = json_decode($data, true);
756 if (is_array($webfinger)) {
757 if (!isset($webfinger["links"])) {
758 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
764 // If it is not JSON, maybe it is XML
765 $xrd = XML::parseString($data, false);
766 if (!is_object($xrd)) {
767 Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
771 $xrd_arr = XML::elementToArray($xrd);
772 if (!isset($xrd_arr["xrd"]["link"])) {
773 Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
779 if (!empty($xrd_arr["xrd"]["subject"])) {
780 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
783 if (!empty($xrd_arr["xrd"]["alias"])) {
784 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
787 $webfinger["links"] = [];
789 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
790 if (!empty($data["@attributes"])) {
791 $attributes = $data["@attributes"];
792 } elseif ($value == "@attributes") {
798 $webfinger["links"][] = $attributes;
804 * @brief Poll the Friendica specific noscrape page.
806 * "noscrape" is a faster alternative to fetch the data from the hcard.
807 * This functionality was originally created for the directory.
809 * @param string $noscrape_url Link to the noscrape page
810 * @param array $data The already fetched data
812 * @return array noscrape data
814 private static function pollNoscrape($noscrape_url, $data)
816 $curlResult = Network::curl($noscrape_url);
817 if ($curlResult->isTimeout()) {
820 $content = $curlResult->getBody();
822 Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
826 $json = json_decode($content, true);
827 if (!is_array($json)) {
828 Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
832 if (!empty($json["fn"])) {
833 $data["name"] = $json["fn"];
836 if (!empty($json["addr"])) {
837 $data["addr"] = $json["addr"];
840 if (!empty($json["nick"])) {
841 $data["nick"] = $json["nick"];
844 if (!empty($json["guid"])) {
845 $data["guid"] = $json["guid"];
848 if (!empty($json["comm"])) {
849 $data["community"] = $json["comm"];
852 if (!empty($json["tags"])) {
853 $keywords = implode(" ", $json["tags"]);
854 if ($keywords != "") {
855 $data["keywords"] = $keywords;
859 $location = Profile::formatLocation($json);
861 $data["location"] = $location;
864 if (!empty($json["about"])) {
865 $data["about"] = $json["about"];
868 if (!empty($json["key"])) {
869 $data["pubkey"] = $json["key"];
872 if (!empty($json["photo"])) {
873 $data["photo"] = $json["photo"];
876 if (!empty($json["dfrn-request"])) {
877 $data["request"] = $json["dfrn-request"];
880 if (!empty($json["dfrn-confirm"])) {
881 $data["confirm"] = $json["dfrn-confirm"];
884 if (!empty($json["dfrn-notify"])) {
885 $data["notify"] = $json["dfrn-notify"];
888 if (!empty($json["dfrn-poll"])) {
889 $data["poll"] = $json["dfrn-poll"];
896 * @brief Check for valid DFRN data
898 * @param array $data DFRN data
900 * @return int Number of errors
902 public static function validDfrn($data)
905 if (!isset($data['key'])) {
908 if (!isset($data['dfrn-request'])) {
911 if (!isset($data['dfrn-confirm'])) {
914 if (!isset($data['dfrn-notify'])) {
917 if (!isset($data['dfrn-poll'])) {
924 * @brief Fetch data from a DFRN profile page and via "noscrape"
926 * @param string $profile_link Link to the profile page
928 * @return array profile data
930 public static function profile($profile_link)
934 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
936 // Fetch data via noscrape - this is faster
937 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
938 $data = self::pollNoscrape($noscrape_url, $data);
940 if (!isset($data["notify"])
941 || !isset($data["confirm"])
942 || !isset($data["request"])
943 || !isset($data["poll"])
944 || !isset($data["name"])
945 || !isset($data["photo"])
947 $data = self::pollHcard($profile_link, $data, true);
952 if (empty($data["addr"]) || empty($data["nick"])) {
953 $probe_data = self::uri($profile_link);
954 $data["addr"] = defaults($data, "addr", $probe_data["addr"]);
955 $data["nick"] = defaults($data, "nick", $probe_data["nick"]);
958 $prof_data["addr"] = $data["addr"];
959 $prof_data["nick"] = $data["nick"];
960 $prof_data["dfrn-request"] = defaults($data, 'request', null);
961 $prof_data["dfrn-confirm"] = defaults($data, 'confirm', null);
962 $prof_data["dfrn-notify"] = defaults($data, 'notify' , null);
963 $prof_data["dfrn-poll"] = defaults($data, 'poll' , null);
964 $prof_data["photo"] = defaults($data, 'photo' , null);
965 $prof_data["fn"] = defaults($data, 'name' , null);
966 $prof_data["key"] = defaults($data, 'pubkey' , null);
968 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
974 * @brief Check for DFRN contact
976 * @param array $webfinger Webfinger data
978 * @return array DFRN data
980 private static function dfrn($webfinger)
984 // The array is reversed to take into account the order of preference for same-rel links
985 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
986 foreach (array_reverse($webfinger["links"]) as $link) {
987 if (($link["rel"] == NAMESPACE_DFRN) && !empty($link["href"])) {
988 $data["network"] = Protocol::DFRN;
989 } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
990 $data["poll"] = $link["href"];
991 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (defaults($link, "type", "") == "text/html") && !empty($link["href"])) {
992 $data["url"] = $link["href"];
993 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
994 $hcard_url = $link["href"];
995 } elseif (($link["rel"] == NAMESPACE_POCO) && !empty($link["href"])) {
996 $data["poco"] = $link["href"];
997 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
998 $data["photo"] = $link["href"];
999 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1000 $data["baseurl"] = trim($link["href"], '/');
1001 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1002 $data["guid"] = $link["href"];
1003 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1004 $data["pubkey"] = base64_decode($link["href"]);
1006 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1007 if (strstr($data["pubkey"], 'RSA ')) {
1008 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1013 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1014 foreach ($webfinger["aliases"] as $alias) {
1015 if (empty($data["url"]) && !strstr($alias, "@")) {
1016 $data["url"] = $alias;
1017 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1018 $data["alias"] = $alias;
1019 } elseif (substr($alias, 0, 5) == 'acct:') {
1020 $data["addr"] = substr($alias, 5);
1025 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1026 $data["addr"] = substr($webfinger["subject"], 5);
1029 if (!isset($data["network"]) || ($hcard_url == "")) {
1033 // Fetch data via noscrape - this is faster
1034 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1035 $data = self::pollNoscrape($noscrape_url, $data);
1037 if (isset($data["notify"])
1038 && isset($data["confirm"])
1039 && isset($data["request"])
1040 && isset($data["poll"])
1041 && isset($data["name"])
1042 && isset($data["photo"])
1047 $data = self::pollHcard($hcard_url, $data, true);
1053 * @brief Poll the hcard page (Diaspora and Friendica specific)
1055 * @param string $hcard_url Link to the hcard page
1056 * @param array $data The already fetched data
1057 * @param boolean $dfrn Poll DFRN specific data
1059 * @return array hcard data
1061 private static function pollHcard($hcard_url, $data, $dfrn = false)
1063 $curlResult = Network::curl($hcard_url);
1064 if ($curlResult->isTimeout()) {
1067 $content = $curlResult->getBody();
1072 $doc = new DOMDocument();
1073 if (!@$doc->loadHTML($content)) {
1077 $xpath = new DomXPath($doc);
1079 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1080 if (!is_object($vcards)) {
1084 if (!isset($data["baseurl"])) {
1085 $data["baseurl"] = "";
1088 if ($vcards->length > 0) {
1089 $vcard = $vcards->item(0);
1091 // We have to discard the guid from the hcard in favour of the guid from lrdd
1092 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1093 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1094 if (($search->length > 0) && empty($data["guid"])) {
1095 $data["guid"] = $search->item(0)->nodeValue;
1098 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1099 if ($search->length > 0) {
1100 $data["nick"] = $search->item(0)->nodeValue;
1103 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1104 if ($search->length > 0) {
1105 $data["name"] = $search->item(0)->nodeValue;
1108 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1109 if ($search->length > 0) {
1110 $data["searchable"] = $search->item(0)->nodeValue;
1113 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1114 if ($search->length > 0) {
1115 $data["pubkey"] = $search->item(0)->nodeValue;
1116 if (strstr($data["pubkey"], 'RSA ')) {
1117 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1121 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1122 if ($search->length > 0) {
1123 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1128 if (!empty($vcard)) {
1129 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1130 foreach ($photos as $photo) {
1132 foreach ($photo->attributes as $attribute) {
1133 $attr[$attribute->name] = trim($attribute->value);
1136 if (isset($attr["src"]) && isset($attr["width"])) {
1137 $avatar[$attr["width"]] = $attr["src"];
1140 // We don't have a width. So we just take everything that we got.
1141 // This is a Hubzilla workaround which doesn't send a width.
1142 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1143 $avatar[] = $attr["src"];
1148 if (sizeof($avatar)) {
1150 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1154 // Poll DFRN specific data
1155 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1156 if ($search->length > 0) {
1157 foreach ($search as $link) {
1158 //$data["request"] = $search->item(0)->nodeValue;
1160 foreach ($link->attributes as $attribute) {
1161 $attr[$attribute->name] = trim($attribute->value);
1164 $data[substr($attr["rel"], 5)] = $attr["href"];
1168 // Older Friendica versions had used the "uid" field differently than newer versions
1169 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1170 unset($data["guid"]);
1179 * @brief Check for Diaspora contact
1181 * @param array $webfinger Webfinger data
1183 * @return array Diaspora data
1185 private static function diaspora($webfinger)
1189 // The array is reversed to take into account the order of preference for same-rel links
1190 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1191 foreach (array_reverse($webfinger["links"]) as $link) {
1192 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1193 $hcard_url = $link["href"];
1194 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1195 $data["baseurl"] = trim($link["href"], '/');
1196 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1197 $data["guid"] = $link["href"];
1198 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (defaults($link, "type", "") == "text/html") && !empty($link["href"])) {
1199 $data["url"] = $link["href"];
1200 } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
1201 $data["poll"] = $link["href"];
1202 } elseif (($link["rel"] == NAMESPACE_POCO) && !empty($link["href"])) {
1203 $data["poco"] = $link["href"];
1204 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1205 $data["notify"] = $link["href"];
1206 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1207 $data["pubkey"] = base64_decode($link["href"]);
1209 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1210 if (strstr($data["pubkey"], 'RSA ')) {
1211 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1216 if (!isset($data["url"]) || ($hcard_url == "")) {
1220 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1221 foreach ($webfinger["aliases"] as $alias) {
1222 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1223 $data["alias"] = $alias;
1224 } elseif (substr($alias, 0, 5) == 'acct:') {
1225 $data["addr"] = substr($alias, 5);
1230 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1231 $data["addr"] = substr($webfinger["subject"], 5);
1234 // Fetch further information from the hcard
1235 $data = self::pollHcard($hcard_url, $data);
1241 if (isset($data["url"])
1242 && isset($data["guid"])
1243 && isset($data["baseurl"])
1244 && isset($data["pubkey"])
1245 && ($hcard_url != "")
1247 $data["network"] = Protocol::DIASPORA;
1249 // The Diaspora handle must always be lowercase
1250 if (!empty($data["addr"])) {
1251 $data["addr"] = strtolower($data["addr"]);
1254 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1255 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1256 $data["batch"] = $data["baseurl"] . "/receive/public";
1265 * @brief Check for OStatus contact
1267 * @param array $webfinger Webfinger data
1268 * @param bool $short Short detection mode
1270 * @return array|bool OStatus data or "false" on error or "true" on short mode
1272 private static function ostatus($webfinger, $short = false)
1276 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1277 foreach ($webfinger["aliases"] as $alias) {
1278 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1279 $data["addr"] = str_replace('acct:', '', $alias);
1284 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1285 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1287 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1291 if (is_array($webfinger["links"])) {
1292 // The array is reversed to take into account the order of preference for same-rel links
1293 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1294 foreach (array_reverse($webfinger["links"]) as $link) {
1295 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1296 && (defaults($link, "type", "") == "text/html")
1297 && ($link["href"] != "")
1299 $data["url"] = $link["href"];
1300 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1301 $data["notify"] = $link["href"];
1302 } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
1303 $data["poll"] = $link["href"];
1304 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1305 $pubkey = $link["href"];
1307 if (substr($pubkey, 0, 5) === 'data:') {
1308 if (strstr($pubkey, ',')) {
1309 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1311 $pubkey = substr($pubkey, 5);
1313 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1314 $curlResult = Network::curl($pubkey);
1315 if ($curlResult->isTimeout()) {
1318 $pubkey = $curlResult->getBody();
1321 $key = explode(".", $pubkey);
1323 if (sizeof($key) >= 3) {
1324 $m = Strings::base64UrlDecode($key[1]);
1325 $e = Strings::base64UrlDecode($key[2]);
1326 $data["pubkey"] = Crypto::meToPem($m, $e);
1332 if (isset($data["notify"]) && isset($data["pubkey"])
1333 && isset($data["poll"])
1334 && isset($data["url"])
1336 $data["network"] = Protocol::OSTATUS;
1345 // Fetch all additional data from the feed
1346 $curlResult = Network::curl($data["poll"]);
1347 if ($curlResult->isTimeout()) {
1350 $feed = $curlResult->getBody();
1354 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1359 if (!empty($feed_data["header"]["author-name"])) {
1360 $data["name"] = $feed_data["header"]["author-name"];
1362 if (!empty($feed_data["header"]["author-nick"])) {
1363 $data["nick"] = $feed_data["header"]["author-nick"];
1365 if (!empty($feed_data["header"]["author-avatar"])) {
1366 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1368 if (!empty($feed_data["header"]["author-id"])) {
1369 $data["alias"] = $feed_data["header"]["author-id"];
1371 if (!empty($feed_data["header"]["author-location"])) {
1372 $data["location"] = $feed_data["header"]["author-location"];
1374 if (!empty($feed_data["header"]["author-about"])) {
1375 $data["about"] = $feed_data["header"]["author-about"];
1377 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1378 // So we take the value that we just fetched, although the other one worked as well
1379 if (!empty($feed_data["header"]["author-link"])) {
1380 $data["url"] = $feed_data["header"]["author-link"];
1383 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1384 $data['url'] = $data["alias"];
1385 $data["alias"] = '';
1388 /// @todo Fetch location and "about" from the feed as well
1393 * @brief Fetch data from a pump.io profile page
1395 * @param string $profile_link Link to the profile page
1397 * @return array profile data
1399 private static function pumpioProfileData($profile_link)
1401 $doc = new DOMDocument();
1402 if (!@$doc->loadHTMLFile($profile_link)) {
1406 $xpath = new DomXPath($doc);
1410 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1412 if ($data["name"] == '') {
1413 // This is ugly - but pump.io doesn't seem to know a better way for it
1414 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1415 $pos = strpos($data["name"], chr(10));
1417 $data["name"] = trim(substr($data["name"], 0, $pos));
1421 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1423 if ($data["location"] == '') {
1424 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1427 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1429 if ($data["about"] == '') {
1430 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1433 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1435 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1438 foreach ($avatar->attributes as $attribute) {
1439 if ($attribute->name == "src") {
1440 $data["photo"] = trim($attribute->value);
1449 * @brief Check for pump.io contact
1451 * @param array $webfinger Webfinger data
1453 * @return array pump.io data
1455 private static function pumpio($webfinger, $addr)
1458 // The array is reversed to take into account the order of preference for same-rel links
1459 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1460 foreach (array_reverse($webfinger["links"]) as $link) {
1461 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1462 && (defaults($link, "type", "") == "text/html")
1463 && ($link["href"] != "")
1465 $data["url"] = $link["href"];
1466 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1467 $data["notify"] = $link["href"];
1468 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1469 $data["poll"] = $link["href"];
1470 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1471 $data["dialback"] = $link["href"];
1474 if (isset($data["poll"]) && isset($data["notify"])
1475 && isset($data["dialback"])
1476 && isset($data["url"])
1478 // by now we use these fields only for the network type detection
1479 // So we unset all data that isn't used at the moment
1480 unset($data["dialback"]);
1482 $data["network"] = Protocol::PUMPIO;
1487 $profile_data = self::pumpioProfileData($data["url"]);
1489 if (!$profile_data) {
1493 $data = array_merge($data, $profile_data);
1495 if (($addr != '') && ($data['name'] != '')) {
1496 $name = trim(str_replace($addr, '', $data['name']));
1498 $data['name'] = $name;
1506 * @brief Check page for feed link
1508 * @param string $url Page link
1510 * @return string feed link
1512 private static function getFeedLink($url)
1514 $doc = new DOMDocument();
1516 if (!@$doc->loadHTMLFile($url)) {
1520 $xpath = new DomXPath($doc);
1522 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1523 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1524 if (!is_object($feeds)) {
1528 if ($feeds->length == 0) {
1534 foreach ($feeds as $feed) {
1536 foreach ($feed->attributes as $attribute) {
1537 $attr[$attribute->name] = trim($attribute->value);
1540 if ($feed_url == "") {
1541 $feed_url = $attr["href"];
1549 * @brief Check for feed contact
1551 * @param string $url Profile link
1552 * @param boolean $probe Do a probe if the page contains a feed link
1554 * @return array feed data
1556 private static function feed($url, $probe = true)
1558 $curlResult = Network::curl($url);
1559 if ($curlResult->isTimeout()) {
1562 $feed = $curlResult->getBody();
1563 $dummy1 = $dummy2 = $dummy3 = null;
1564 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1571 $feed_url = self::getFeedLink($url);
1577 return self::feed($feed_url, false);
1580 if (!empty($feed_data["header"]["author-name"])) {
1581 $data["name"] = $feed_data["header"]["author-name"];
1584 if (!empty($feed_data["header"]["author-nick"])) {
1585 $data["nick"] = $feed_data["header"]["author-nick"];
1588 if (!empty($feed_data["header"]["author-avatar"])) {
1589 $data["photo"] = $feed_data["header"]["author-avatar"];
1592 if (!empty($feed_data["header"]["author-id"])) {
1593 $data["alias"] = $feed_data["header"]["author-id"];
1596 $data["url"] = $url;
1597 $data["poll"] = $url;
1599 if (!empty($feed_data["header"]["author-link"])) {
1600 $data["baseurl"] = $feed_data["header"]["author-link"];
1602 $data["baseurl"] = $data["url"];
1605 $data["network"] = Protocol::FEED;
1611 * @brief Check for mail contact
1613 * @param string $uri Profile link
1614 * @param integer $uid User ID
1616 * @return array mail data
1618 private static function mail($uri, $uid)
1620 if (!Network::isEmailDomainValid($uri)) {
1628 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1630 $condition = ["`uid` = ? AND `server` != ''", $uid];
1631 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1632 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1634 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1638 $mailbox = Email::constructMailboxName($mailacct);
1640 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1641 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1646 $msgs = Email::poll($mbox, $uri);
1647 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1649 if (!count($msgs)) {
1653 $phost = substr($uri, strpos($uri, '@') + 1);
1656 $data["addr"] = $uri;
1657 $data["network"] = Protocol::MAIL;
1658 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1659 $data["nick"] = $data["name"];
1660 $data["photo"] = Network::lookupAvatarByEmail($uri);
1661 $data["url"] = 'mailto:'.$uri;
1662 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1663 $data["poll"] = 'email ' . Strings::getRandomHex();
1665 $x = Email::messageMeta($mbox, $msgs[0]);
1666 if (stristr($x[0]->from, $uri)) {
1667 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1668 } elseif (stristr($x[0]->to, $uri)) {
1669 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1672 foreach ($adr as $feadr) {
1673 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1674 &&(strcasecmp($feadr->host, $phost) == 0)
1675 && (strlen($feadr->personal))
1677 $personal = imap_mime_header_decode($feadr->personal);
1679 foreach ($personal as $perspart) {
1680 if ($perspart->charset != "default") {
1681 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1683 $data["name"] .= $perspart->text;
1687 $data["name"] = Strings::escapeTags($data["name"]);
1691 if (!empty($mbox)) {
1698 * @brief Mix two paths together to possibly fix missing parts
1700 * @param string $avatar Path to the avatar
1701 * @param string $base Another path that is hopefully complete
1703 * @return string fixed avatar path
1705 public static function fixAvatar($avatar, $base)
1707 $base_parts = parse_url($base);
1709 // Remove all parts that could create a problem
1710 unset($base_parts['path']);
1711 unset($base_parts['query']);
1712 unset($base_parts['fragment']);
1714 $avatar_parts = parse_url($avatar);
1717 $parts = array_merge($base_parts, $avatar_parts);
1719 // And put them together again
1720 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1721 $host = isset($parts['host']) ? $parts['host'] : '';
1722 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1723 $path = isset($parts['path']) ? $parts['path'] : '';
1724 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1725 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1727 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1729 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);