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);
336 if (in_array(defaults($data, 'network', ''), ['', Protocol::PHANTOM])) {
337 $ap_profile = ActivityPub::fetchProfile($uri);
338 if (!empty($ap_profile) && ($ap_profile['network'] == Protocol::ACTIVITYPUB)) {
343 if (!isset($data["url"])) {
347 if (x($data, "photo")) {
348 $data["baseurl"] = Network::getUrlMatch(normalise_link(defaults($data, "baseurl", "")), normalise_link($data["photo"]));
350 $data["photo"] = System::baseUrl().'/images/person-175.jpg';
353 if (empty($data["name"])) {
354 if (!empty($data["nick"])) {
355 $data["name"] = $data["nick"];
358 if (!x($data, "name")) {
359 $data["name"] = $data["url"];
363 if (empty($data["nick"])) {
364 $data["nick"] = strtolower($data["name"]);
366 if (strpos($data['nick'], ' ')) {
367 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
371 if (!empty(self::$baseurl)) {
372 $data["baseurl"] = self::$baseurl;
375 if (empty($data["network"])) {
376 $data["network"] = Protocol::PHANTOM;
379 $data = self::rearrangeData($data);
381 // Only store into the cache if the value seems to be valid
382 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
383 Cache::set("Probe::uri:".$network.":".$uri, $data, CACHE_DAY);
385 /// @todo temporary fix - we need a real contact update function that updates only changing fields
386 /// The biggest problem is the avatar picture that could have a reduced image size.
387 /// It should only be updated if the existing picture isn't existing anymore.
388 /// We only update the contact when it is no probing for a specific network.
389 if (($data['network'] != Protocol::FEED)
397 $fields = ['name' => $data['name'],
398 'nick' => $data['nick'],
399 'url' => $data['url'],
400 'addr' => $data['addr'],
401 'photo' => $data['photo'],
402 'keywords' => $data['keywords'],
403 'location' => $data['location'],
404 'about' => $data['about'],
405 'notify' => $data['notify'],
406 'network' => $data['network'],
407 'server_url' => $data['baseurl']];
409 // This doesn't cover the case when a community isn't a community anymore
410 if (!empty($data['community']) && $data['community']) {
411 $fields['community'] = $data['community'];
412 $fields['contact-type'] = Contact::ACCOUNT_TYPE_COMMUNITY;
417 foreach ($fields as $key => $val) {
419 unset($fields[$key]);
421 $fieldnames[] = $key;
425 $fields['updated'] = DateTimeFormat::utcNow();
427 $condition = ['nurl' => normalise_link($data["url"])];
429 $old_fields = DBA::selectFirst('gcontact', $fieldnames, $condition);
431 // When the gcontact doesn't exist, the value "true" will trigger an insert.
432 // In difference to the public contacts we want to have every contact
433 // in the world in our global contacts.
437 // These values have to be set only on insert
438 $fields['photo'] = $data['photo'];
439 $fields['created'] = DateTimeFormat::utcNow();
442 DBA::update('gcontact', $fields, $condition, $old_fields);
444 $fields = ['name' => $data['name'],
445 'nick' => $data['nick'],
446 'url' => $data['url'],
447 'addr' => $data['addr'],
448 'alias' => $data['alias'],
449 'keywords' => $data['keywords'],
450 'location' => $data['location'],
451 'about' => $data['about'],
452 'batch' => $data['batch'],
453 'notify' => $data['notify'],
454 'poll' => $data['poll'],
455 'request' => $data['request'],
456 'confirm' => $data['confirm'],
457 'poco' => $data['poco'],
458 'network' => $data['network'],
459 'pubkey' => $data['pubkey'],
460 'priority' => $data['priority'],
462 'rel' => Contact::SHARING];
466 foreach ($fields as $key => $val) {
468 unset($fields[$key]);
470 $fieldnames[] = $key;
474 $condition = ['nurl' => normalise_link($data["url"]), 'self' => false, 'uid' => 0];
476 // "$old_fields" will return a "false" when the contact doesn't exist.
477 // This won't trigger an insert. This is intended, since we only need
478 // public contacts for everyone we store items from.
479 // We don't need to store every contact on the planet.
480 $old_fields = DBA::selectFirst('contact', $fieldnames, $condition);
482 $fields['name-date'] = DateTimeFormat::utcNow();
483 $fields['uri-date'] = DateTimeFormat::utcNow();
484 $fields['success_update'] = DateTimeFormat::utcNow();
486 DBA::update('contact', $fields, $condition, $old_fields);
494 * @brief Switch the scheme of an url between http and https
496 * @param string $url URL
498 * @return string switched URL
500 private static function switchScheme($url)
502 $parts = parse_url($url);
504 if (!isset($parts['scheme'])) {
508 if ($parts['scheme'] == 'http') {
509 $url = str_replace('http://', 'https://', $url);
510 } elseif ($parts['scheme'] == 'https') {
511 $url = str_replace('https://', 'http://', $url);
518 * @brief Checks if a profile url should be OStatus but only provides partial information
520 * @param array $webfinger Webfinger data
521 * @param string $lrdd Path template for webfinger request
522 * @param string $type type
524 * @return array fixed webfinger data
526 private static function fixOStatus($webfinger, $lrdd, $type)
528 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
535 foreach ($webfinger['links'] as $link) {
536 if ($link['rel'] == NAMESPACE_OSTATUSSUB) {
539 if ($link['rel'] == 'magic-public-key') {
544 if (!$is_ostatus || $has_key) {
548 $url = self::switchScheme($webfinger['subject']);
549 $path = str_replace('{uri}', urlencode($url), $lrdd);
550 $webfinger2 = self::webfinger($path, $type);
552 // Is the new webfinger detectable as OStatus?
553 if (self::ostatus($webfinger2, true)) {
554 $webfinger = $webfinger2;
561 * @brief Fetch information (protocol endpoints and user information) about a given uri
563 * This function is only called by the "uri" function that adds caching and rearranging of data.
565 * @param string $uri Address that should be probed
566 * @param string $network Test for this specific network
567 * @param integer $uid User ID for the probe (only used for mails)
569 * @return array uri data
571 private static function detect($uri, $network, $uid)
573 $parts = parse_url($uri);
575 if (!empty($parts["scheme"]) && !empty($parts["host"]) && !empty($parts["path"])) {
576 $host = $parts["host"];
577 if (!empty($parts["port"])) {
578 $host .= ':'.$parts["port"];
581 if ($host == 'twitter.com') {
582 return ["network" => Protocol::TWITTER];
584 $lrdd = self::hostMeta($host);
586 if (is_bool($lrdd)) {
590 $path_parts = explode("/", trim($parts["path"], "/"));
592 while (!$lrdd && (sizeof($path_parts) > 1)) {
593 $host .= "/".array_shift($path_parts);
594 $lrdd = self::hostMeta($host);
597 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
598 return self::feed($uri);
600 $nick = array_pop($path_parts);
602 // Mastodon uses a "@" as prefix for usernames in their url format
603 $nick = ltrim($nick, '@');
605 $addr = $nick."@".$host;
606 } elseif (strstr($uri, '@')) {
607 // If the URI starts with "mailto:" then jump directly to the mail detection
608 if (strpos($uri, 'mailto:') !== false) {
609 $uri = str_replace('mailto:', '', $uri);
610 return self::mail($uri, $uid);
613 if ($network == Protocol::MAIL) {
614 return self::mail($uri, $uid);
616 // Remove "acct:" from the URI
617 $uri = str_replace('acct:', '', $uri);
619 $host = substr($uri, strpos($uri, '@') + 1);
620 $nick = substr($uri, 0, strpos($uri, '@'));
622 if (strpos($uri, '@twitter.com')) {
623 return ["network" => Protocol::TWITTER];
625 $lrdd = self::hostMeta($host);
627 if (is_bool($lrdd)) {
632 logger('No XRD data was found for '.$uri, LOGGER_DEBUG);
633 return self::mail($uri, $uid);
637 logger("Uri ".$uri." was not detectable", LOGGER_DEBUG);
643 /// @todo Do we need the prefix "acct:" or "acct://"?
645 foreach ($lrdd as $type => $template) {
650 // At first try it with the given uri
651 $path = str_replace('{uri}', urlencode($uri), $template);
652 $webfinger = self::webfinger($path, $type);
654 // Fix possible problems with GNU Social probing to wrong scheme
655 $webfinger = self::fixOStatus($webfinger, $template, $type);
657 // We cannot be sure that the detected address was correct, so we don't use the values
658 if ($webfinger && ($uri != $addr)) {
663 // Try webfinger with the address (user@domain.tld)
665 $path = str_replace('{uri}', urlencode($addr), $template);
666 $webfinger = self::webfinger($path, $type);
669 // Mastodon needs to have it with "acct:"
671 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
672 $webfinger = self::webfinger($path, $type);
677 return self::feed($uri);
682 logger("Probing ".$uri, LOGGER_DEBUG);
684 if (in_array($network, ["", Protocol::DFRN])) {
685 $result = self::dfrn($webfinger);
687 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
688 $result = self::diaspora($webfinger);
690 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
691 $result = self::ostatus($webfinger);
693 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
694 $result = self::pumpio($webfinger, $addr);
696 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
697 $result = self::feed($uri);
699 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
700 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
701 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
702 $result["nick"] = $nick;
705 if (empty($result["addr"]) && ($addr != "")) {
706 $result["addr"] = $addr;
710 if (empty($result["network"])) {
711 $result["network"] = Protocol::PHANTOM;
714 if (empty($result["url"])) {
715 $result["url"] = $uri;
718 logger($uri." is ".$result["network"], LOGGER_DEBUG);
720 if (empty($result["baseurl"])) {
721 $pos = strpos($result["url"], $host);
723 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
730 * @brief Perform a webfinger request.
732 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
734 * @param string $url Address that should be probed
735 * @param string $type type
737 * @return array webfinger data
739 private static function webfinger($url, $type)
741 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
744 $ret = Network::curl($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
745 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
748 $data = $ret['body'];
750 $webfinger = json_decode($data, true);
751 if (is_array($webfinger)) {
752 if (!isset($webfinger["links"])) {
753 logger("No json webfinger links for ".$url, LOGGER_DEBUG);
759 // If it is not JSON, maybe it is XML
760 $xrd = XML::parseString($data, false);
761 if (!is_object($xrd)) {
762 logger("No webfinger data retrievable for ".$url, LOGGER_DEBUG);
766 $xrd_arr = XML::elementToArray($xrd);
767 if (!isset($xrd_arr["xrd"]["link"])) {
768 logger("No XML webfinger links for ".$url, LOGGER_DEBUG);
774 if (!empty($xrd_arr["xrd"]["subject"])) {
775 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
778 if (!empty($xrd_arr["xrd"]["alias"])) {
779 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
782 $webfinger["links"] = [];
784 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
785 if (!empty($data["@attributes"])) {
786 $attributes = $data["@attributes"];
787 } elseif ($value == "@attributes") {
793 $webfinger["links"][] = $attributes;
799 * @brief Poll the Friendica specific noscrape page.
801 * "noscrape" is a faster alternative to fetch the data from the hcard.
802 * This functionality was originally created for the directory.
804 * @param string $noscrape_url Link to the noscrape page
805 * @param array $data The already fetched data
807 * @return array noscrape data
809 private static function pollNoscrape($noscrape_url, $data)
811 $ret = Network::curl($noscrape_url);
812 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
815 $content = $ret['body'];
817 logger("Empty body for ".$noscrape_url, LOGGER_DEBUG);
821 $json = json_decode($content, true);
822 if (!is_array($json)) {
823 logger("No json data for ".$noscrape_url, LOGGER_DEBUG);
827 if (!empty($json["fn"])) {
828 $data["name"] = $json["fn"];
831 if (!empty($json["addr"])) {
832 $data["addr"] = $json["addr"];
835 if (!empty($json["nick"])) {
836 $data["nick"] = $json["nick"];
839 if (!empty($json["guid"])) {
840 $data["guid"] = $json["guid"];
843 if (!empty($json["comm"])) {
844 $data["community"] = $json["comm"];
847 if (!empty($json["tags"])) {
848 $keywords = implode(" ", $json["tags"]);
849 if ($keywords != "") {
850 $data["keywords"] = $keywords;
854 $location = Profile::formatLocation($json);
856 $data["location"] = $location;
859 if (!empty($json["about"])) {
860 $data["about"] = $json["about"];
863 if (!empty($json["key"])) {
864 $data["pubkey"] = $json["key"];
867 if (!empty($json["photo"])) {
868 $data["photo"] = $json["photo"];
871 if (!empty($json["dfrn-request"])) {
872 $data["request"] = $json["dfrn-request"];
875 if (!empty($json["dfrn-confirm"])) {
876 $data["confirm"] = $json["dfrn-confirm"];
879 if (!empty($json["dfrn-notify"])) {
880 $data["notify"] = $json["dfrn-notify"];
883 if (!empty($json["dfrn-poll"])) {
884 $data["poll"] = $json["dfrn-poll"];
891 * @brief Check for valid DFRN data
893 * @param array $data DFRN data
895 * @return int Number of errors
897 public static function validDfrn($data)
900 if (!isset($data['key'])) {
903 if (!isset($data['dfrn-request'])) {
906 if (!isset($data['dfrn-confirm'])) {
909 if (!isset($data['dfrn-notify'])) {
912 if (!isset($data['dfrn-poll'])) {
919 * @brief Fetch data from a DFRN profile page and via "noscrape"
921 * @param string $profile_link Link to the profile page
923 * @return array profile data
925 public static function profile($profile_link)
929 logger("Check profile ".$profile_link, LOGGER_DEBUG);
931 // Fetch data via noscrape - this is faster
932 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
933 $data = self::pollNoscrape($noscrape_url, $data);
935 if (!isset($data["notify"])
936 || !isset($data["confirm"])
937 || !isset($data["request"])
938 || !isset($data["poll"])
939 || !isset($data["name"])
940 || !isset($data["photo"])
942 $data = self::pollHcard($profile_link, $data, true);
947 if (empty($data["addr"]) || empty($data["nick"])) {
948 $probe_data = self::uri($profile_link);
949 $data["addr"] = defaults($data, "addr", $probe_data["addr"]);
950 $data["nick"] = defaults($data, "nick", $probe_data["nick"]);
953 $prof_data["addr"] = $data["addr"];
954 $prof_data["nick"] = $data["nick"];
955 $prof_data["dfrn-request"] = $data["request"];
956 $prof_data["dfrn-confirm"] = $data["confirm"];
957 $prof_data["dfrn-notify"] = $data["notify"];
958 $prof_data["dfrn-poll"] = $data["poll"];
959 $prof_data["photo"] = $data["photo"];
960 $prof_data["fn"] = $data["name"];
961 $prof_data["key"] = $data["pubkey"];
963 logger("Result for profile ".$profile_link.": ".print_r($prof_data, true), LOGGER_DEBUG);
969 * @brief Check for DFRN contact
971 * @param array $webfinger Webfinger data
973 * @return array DFRN data
975 private static function dfrn($webfinger)
979 foreach ($webfinger["links"] as $link) {
980 if (($link["rel"] == NAMESPACE_DFRN) && ($link["href"] != "")) {
981 $data["network"] = Protocol::DFRN;
982 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
983 $data["poll"] = $link["href"];
984 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
985 $data["url"] = $link["href"];
986 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
987 $hcard_url = $link["href"];
988 } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
989 $data["poco"] = $link["href"];
990 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && ($link["href"] != "")) {
991 $data["photo"] = $link["href"];
992 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
993 $data["baseurl"] = trim($link["href"], '/');
994 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
995 $data["guid"] = $link["href"];
996 } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
997 $data["pubkey"] = base64_decode($link["href"]);
999 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1000 if (strstr($data["pubkey"], 'RSA ')) {
1001 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1006 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1007 foreach ($webfinger["aliases"] as $alias) {
1008 if (empty($data["url"]) && !strstr($alias, "@")) {
1009 $data["url"] = $alias;
1010 } elseif (!strstr($alias, "@") && normalise_link($alias) != normalise_link($data["url"])) {
1011 $data["alias"] = $alias;
1012 } elseif (substr($alias, 0, 5) == 'acct:') {
1013 $data["addr"] = substr($alias, 5);
1018 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1019 $data["addr"] = substr($webfinger["subject"], 5);
1022 if (!isset($data["network"]) || ($hcard_url == "")) {
1026 // Fetch data via noscrape - this is faster
1027 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1028 $data = self::pollNoscrape($noscrape_url, $data);
1030 if (isset($data["notify"])
1031 && isset($data["confirm"])
1032 && isset($data["request"])
1033 && isset($data["poll"])
1034 && isset($data["name"])
1035 && isset($data["photo"])
1040 $data = self::pollHcard($hcard_url, $data, true);
1046 * @brief Poll the hcard page (Diaspora and Friendica specific)
1048 * @param string $hcard_url Link to the hcard page
1049 * @param array $data The already fetched data
1050 * @param boolean $dfrn Poll DFRN specific data
1052 * @return array hcard data
1054 private static function pollHcard($hcard_url, $data, $dfrn = false)
1056 $ret = Network::curl($hcard_url);
1057 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1060 $content = $ret['body'];
1065 $doc = new DOMDocument();
1066 if (!@$doc->loadHTML($content)) {
1070 $xpath = new DomXPath($doc);
1072 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1073 if (!is_object($vcards)) {
1077 if (!isset($data["baseurl"])) {
1078 $data["baseurl"] = "";
1081 if ($vcards->length > 0) {
1082 $vcard = $vcards->item(0);
1084 // We have to discard the guid from the hcard in favour of the guid from lrdd
1085 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1086 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1087 if (($search->length > 0) && empty($data["guid"])) {
1088 $data["guid"] = $search->item(0)->nodeValue;
1091 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1092 if ($search->length > 0) {
1093 $data["nick"] = $search->item(0)->nodeValue;
1096 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1097 if ($search->length > 0) {
1098 $data["name"] = $search->item(0)->nodeValue;
1101 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1102 if ($search->length > 0) {
1103 $data["searchable"] = $search->item(0)->nodeValue;
1106 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1107 if ($search->length > 0) {
1108 $data["pubkey"] = $search->item(0)->nodeValue;
1109 if (strstr($data["pubkey"], 'RSA ')) {
1110 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1114 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1115 if ($search->length > 0) {
1116 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1121 if (!empty($vcard)) {
1122 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1123 foreach ($photos as $photo) {
1125 foreach ($photo->attributes as $attribute) {
1126 $attr[$attribute->name] = trim($attribute->value);
1129 if (isset($attr["src"]) && isset($attr["width"])) {
1130 $avatar[$attr["width"]] = $attr["src"];
1133 // We don't have a width. So we just take everything that we got.
1134 // This is a Hubzilla workaround which doesn't send a width.
1135 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1136 $avatar[] = $attr["src"];
1141 if (sizeof($avatar)) {
1143 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1147 // Poll DFRN specific data
1148 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1149 if ($search->length > 0) {
1150 foreach ($search as $link) {
1151 //$data["request"] = $search->item(0)->nodeValue;
1153 foreach ($link->attributes as $attribute) {
1154 $attr[$attribute->name] = trim($attribute->value);
1157 $data[substr($attr["rel"], 5)] = $attr["href"];
1161 // Older Friendica versions had used the "uid" field differently than newer versions
1162 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1163 unset($data["guid"]);
1172 * @brief Check for Diaspora contact
1174 * @param array $webfinger Webfinger data
1176 * @return array Diaspora data
1178 private static function diaspora($webfinger)
1182 foreach ($webfinger["links"] as $link) {
1183 if (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
1184 $hcard_url = $link["href"];
1185 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
1186 $data["baseurl"] = trim($link["href"], '/');
1187 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
1188 $data["guid"] = $link["href"];
1189 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
1190 $data["url"] = $link["href"];
1191 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1192 $data["poll"] = $link["href"];
1193 } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
1194 $data["poco"] = $link["href"];
1195 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1196 $data["notify"] = $link["href"];
1197 } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
1198 $data["pubkey"] = base64_decode($link["href"]);
1200 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1201 if (strstr($data["pubkey"], 'RSA ')) {
1202 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1207 if (!isset($data["url"]) || ($hcard_url == "")) {
1211 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1212 foreach ($webfinger["aliases"] as $alias) {
1213 if (normalise_link($alias) != normalise_link($data["url"]) && ! strstr($alias, "@")) {
1214 $data["alias"] = $alias;
1215 } elseif (substr($alias, 0, 5) == 'acct:') {
1216 $data["addr"] = substr($alias, 5);
1221 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1222 $data["addr"] = substr($webfinger["subject"], 5);
1225 // Fetch further information from the hcard
1226 $data = self::pollHcard($hcard_url, $data);
1232 if (isset($data["url"])
1233 && isset($data["guid"])
1234 && isset($data["baseurl"])
1235 && isset($data["pubkey"])
1236 && ($hcard_url != "")
1238 $data["network"] = Protocol::DIASPORA;
1240 // The Diaspora handle must always be lowercase
1241 if (!empty($data["addr"])) {
1242 $data["addr"] = strtolower($data["addr"]);
1245 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1246 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1247 $data["batch"] = $data["baseurl"] . "/receive/public";
1256 * @brief Check for OStatus contact
1258 * @param array $webfinger Webfinger data
1259 * @param bool $short Short detection mode
1261 * @return array|bool OStatus data or "false" on error or "true" on short mode
1263 private static function ostatus($webfinger, $short = false)
1267 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1268 foreach ($webfinger["aliases"] as $alias) {
1269 if (strstr($alias, "@") && !strstr(normalise_link($alias), "http://")) {
1270 $data["addr"] = str_replace('acct:', '', $alias);
1275 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1276 && !strstr(normalise_link($webfinger["subject"]), "http://")
1278 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1282 if (is_array($webfinger["links"])) {
1283 foreach ($webfinger["links"] as $link) {
1284 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1285 && ($link["type"] == "text/html")
1286 && ($link["href"] != "")
1288 $data["url"] = $link["href"];
1289 } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1290 $data["notify"] = $link["href"];
1291 } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1292 $data["poll"] = $link["href"];
1293 } elseif (($link["rel"] == "magic-public-key") && ($link["href"] != "")) {
1294 $pubkey = $link["href"];
1296 if (substr($pubkey, 0, 5) === 'data:') {
1297 if (strstr($pubkey, ',')) {
1298 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1300 $pubkey = substr($pubkey, 5);
1302 } elseif (normalise_link($pubkey) == 'http://') {
1303 $ret = Network::curl($pubkey);
1304 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1307 $pubkey = $ret['body'];
1310 $key = explode(".", $pubkey);
1312 if (sizeof($key) >= 3) {
1313 $m = base64url_decode($key[1]);
1314 $e = base64url_decode($key[2]);
1315 $data["pubkey"] = Crypto::meToPem($m, $e);
1321 if (isset($data["notify"]) && isset($data["pubkey"])
1322 && isset($data["poll"])
1323 && isset($data["url"])
1325 $data["network"] = Protocol::OSTATUS;
1334 // Fetch all additional data from the feed
1335 $ret = Network::curl($data["poll"]);
1336 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1339 $feed = $ret['body'];
1343 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1348 if (!empty($feed_data["header"]["author-name"])) {
1349 $data["name"] = $feed_data["header"]["author-name"];
1351 if (!empty($feed_data["header"]["author-nick"])) {
1352 $data["nick"] = $feed_data["header"]["author-nick"];
1354 if (!empty($feed_data["header"]["author-avatar"])) {
1355 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1357 if (!empty($feed_data["header"]["author-id"])) {
1358 $data["alias"] = $feed_data["header"]["author-id"];
1360 if (!empty($feed_data["header"]["author-location"])) {
1361 $data["location"] = $feed_data["header"]["author-location"];
1363 if (!empty($feed_data["header"]["author-about"])) {
1364 $data["about"] = $feed_data["header"]["author-about"];
1366 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1367 // So we take the value that we just fetched, although the other one worked as well
1368 if (!empty($feed_data["header"]["author-link"])) {
1369 $data["url"] = $feed_data["header"]["author-link"];
1372 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1373 $data['url'] = $data["alias"];
1374 $data["alias"] = '';
1377 /// @todo Fetch location and "about" from the feed as well
1382 * @brief Fetch data from a pump.io profile page
1384 * @param string $profile_link Link to the profile page
1386 * @return array profile data
1388 private static function pumpioProfileData($profile_link)
1390 $doc = new DOMDocument();
1391 if (!@$doc->loadHTMLFile($profile_link)) {
1395 $xpath = new DomXPath($doc);
1399 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1401 if ($data["name"] == '') {
1402 // This is ugly - but pump.io doesn't seem to know a better way for it
1403 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1404 $pos = strpos($data["name"], chr(10));
1406 $data["name"] = trim(substr($data["name"], 0, $pos));
1410 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1412 if ($data["location"] == '') {
1413 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1416 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1418 if ($data["about"] == '') {
1419 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1422 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1424 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1427 foreach ($avatar->attributes as $attribute) {
1428 if ($attribute->name == "src") {
1429 $data["photo"] = trim($attribute->value);
1438 * @brief Check for pump.io contact
1440 * @param array $webfinger Webfinger data
1442 * @return array pump.io data
1444 private static function pumpio($webfinger, $addr)
1447 foreach ($webfinger["links"] as $link) {
1448 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1449 && ($link["type"] == "text/html")
1450 && ($link["href"] != "")
1452 $data["url"] = $link["href"];
1453 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1454 $data["notify"] = $link["href"];
1455 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1456 $data["poll"] = $link["href"];
1457 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1458 $data["dialback"] = $link["href"];
1461 if (isset($data["poll"]) && isset($data["notify"])
1462 && isset($data["dialback"])
1463 && isset($data["url"])
1465 // by now we use these fields only for the network type detection
1466 // So we unset all data that isn't used at the moment
1467 unset($data["dialback"]);
1469 $data["network"] = Protocol::PUMPIO;
1474 $profile_data = self::pumpioProfileData($data["url"]);
1476 if (!$profile_data) {
1480 $data = array_merge($data, $profile_data);
1482 if (($addr != '') && ($data['name'] != '')) {
1483 $name = trim(str_replace($addr, '', $data['name']));
1485 $data['name'] = $name;
1493 * @brief Check page for feed link
1495 * @param string $url Page link
1497 * @return string feed link
1499 private static function getFeedLink($url)
1501 $doc = new DOMDocument();
1503 if (!@$doc->loadHTMLFile($url)) {
1507 $xpath = new DomXPath($doc);
1509 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1510 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1511 if (!is_object($feeds)) {
1515 if ($feeds->length == 0) {
1521 foreach ($feeds as $feed) {
1523 foreach ($feed->attributes as $attribute) {
1524 $attr[$attribute->name] = trim($attribute->value);
1527 if ($feed_url == "") {
1528 $feed_url = $attr["href"];
1536 * @brief Check for feed contact
1538 * @param string $url Profile link
1539 * @param boolean $probe Do a probe if the page contains a feed link
1541 * @return array feed data
1543 private static function feed($url, $probe = true)
1545 $ret = Network::curl($url);
1546 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1549 $feed = $ret['body'];
1550 $dummy1 = $dummy2 = $dummy3 = null;
1551 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1558 $feed_url = self::getFeedLink($url);
1564 return self::feed($feed_url, false);
1567 if (!empty($feed_data["header"]["author-name"])) {
1568 $data["name"] = $feed_data["header"]["author-name"];
1571 if (!empty($feed_data["header"]["author-nick"])) {
1572 $data["nick"] = $feed_data["header"]["author-nick"];
1575 if (!empty($feed_data["header"]["author-avatar"])) {
1576 $data["photo"] = $feed_data["header"]["author-avatar"];
1579 if (!empty($feed_data["header"]["author-id"])) {
1580 $data["alias"] = $feed_data["header"]["author-id"];
1583 $data["url"] = $url;
1584 $data["poll"] = $url;
1586 if (!empty($feed_data["header"]["author-link"])) {
1587 $data["baseurl"] = $feed_data["header"]["author-link"];
1589 $data["baseurl"] = $data["url"];
1592 $data["network"] = Protocol::FEED;
1598 * @brief Check for mail contact
1600 * @param string $uri Profile link
1601 * @param integer $uid User ID
1603 * @return array mail data
1605 private static function mail($uri, $uid)
1607 if (!Network::isEmailDomainValid($uri)) {
1615 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1617 $condition = ["`uid` = ? AND `server` != ''", $uid];
1618 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1619 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1621 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1625 $mailbox = Email::constructMailboxName($mailacct);
1627 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1628 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1633 $msgs = Email::poll($mbox, $uri);
1634 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1636 if (!count($msgs)) {
1640 $phost = substr($uri, strpos($uri, '@') + 1);
1643 $data["addr"] = $uri;
1644 $data["network"] = Protocol::MAIL;
1645 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1646 $data["nick"] = $data["name"];
1647 $data["photo"] = Network::lookupAvatarByEmail($uri);
1648 $data["url"] = 'mailto:'.$uri;
1649 $data["notify"] = 'smtp '.random_string();
1650 $data["poll"] = 'email '.random_string();
1652 $x = Email::messageMeta($mbox, $msgs[0]);
1653 if (stristr($x[0]->from, $uri)) {
1654 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1655 } elseif (stristr($x[0]->to, $uri)) {
1656 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1659 foreach ($adr as $feadr) {
1660 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1661 &&(strcasecmp($feadr->host, $phost) == 0)
1662 && (strlen($feadr->personal))
1664 $personal = imap_mime_header_decode($feadr->personal);
1666 foreach ($personal as $perspart) {
1667 if ($perspart->charset != "default") {
1668 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1670 $data["name"] .= $perspart->text;
1674 $data["name"] = notags($data["name"]);
1678 if (!empty($mbox)) {
1685 * @brief Mix two paths together to possibly fix missing parts
1687 * @param string $avatar Path to the avatar
1688 * @param string $base Another path that is hopefully complete
1690 * @return string fixed avatar path
1692 public static function fixAvatar($avatar, $base)
1694 $base_parts = parse_url($base);
1696 // Remove all parts that could create a problem
1697 unset($base_parts['path']);
1698 unset($base_parts['query']);
1699 unset($base_parts['fragment']);
1701 $avatar_parts = parse_url($avatar);
1704 $parts = array_merge($base_parts, $avatar_parts);
1706 // And put them together again
1707 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1708 $host = isset($parts['host']) ? $parts['host'] : '';
1709 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1710 $path = isset($parts['path']) ? $parts['path'] : '';
1711 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1712 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1714 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1716 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);