3 * @file src/Network/Probe.php
5 namespace Friendica\Network;
8 * @file src/Network/Probe.php
9 * @brief Functions for probing URL
14 use Friendica\Core\Cache;
15 use Friendica\Core\Config;
16 use Friendica\Core\Logger;
17 use Friendica\Core\Protocol;
18 use Friendica\Core\System;
19 use Friendica\Database\DBA;
20 use Friendica\Model\Contact;
21 use Friendica\Model\Profile;
22 use Friendica\Protocol\ActivityNamespace;
23 use Friendica\Protocol\ActivityPub;
24 use Friendica\Protocol\Email;
25 use Friendica\Protocol\Feed;
26 use Friendica\Util\Crypto;
27 use Friendica\Util\Network;
28 use Friendica\Util\Strings;
29 use Friendica\Util\XML;
32 * @brief This class contain functions for probing URL
37 private static $baseurl;
38 private static $istimeout;
41 * @brief Rearrange the array so that it always has the same order
43 * @param array $data Unordered data
45 * @return array Ordered data
47 private static function rearrangeData($data)
49 $fields = ["name", "nick", "guid", "url", "addr", "alias", "photo", "account-type",
50 "community", "keywords", "location", "about", "gender", "hide",
51 "batch", "notify", "poll", "request", "confirm", "poco",
52 "following", "followers", "inbox", "outbox", "sharedinbox",
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
102 * @throws HTTPException\InternalServerErrorException
104 private static function hostMeta($host)
106 // Reset the static variable
109 $ssl_url = "https://".$host."/.well-known/host-meta";
110 $url = "http://".$host."/.well-known/host-meta";
112 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
114 Logger::log("Probing for ".$host, Logger::DEBUG);
117 $curlResult = Network::curl($ssl_url, false, ['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;
122 } elseif ($curlResult->isTimeout()) {
123 Logger::info('Probing timeout', ['url' => $ssl_url], Logger::DEBUG);
124 self::$istimeout = true;
128 if (!is_object($xrd)) {
129 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
130 if ($curlResult->isTimeout()) {
131 Logger::info('Probing timeout', ['url' => $url], Logger::DEBUG);
132 self::$istimeout = true;
135 $xml = $curlResult->getBody();
136 $xrd = XML::parseString($xml, false);
137 $host_url = 'http://'.$host;
139 if (!is_object($xrd)) {
140 Logger::log("No xrd object found for ".$host, Logger::DEBUG);
144 $links = XML::elementToArray($xrd);
145 if (!isset($links["xrd"]["link"])) {
146 Logger::log("No xrd data found for ".$host, Logger::DEBUG);
150 $lrdd = ['application/jrd+json' => $host_url . '/.well-known/webfinger?resource={uri}'];
152 foreach ($links["xrd"]["link"] as $value => $link) {
153 if (!empty($link["@attributes"])) {
154 $attributes = $link["@attributes"];
155 } elseif ($value == "@attributes") {
161 if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
162 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
164 $lrdd[$type] = $attributes["template"];
168 self::$baseurl = $host_url;
170 Logger::log("Probing successful for ".$host, Logger::DEBUG);
176 * @brief Perform Webfinger lookup and return DFRN data
178 * Given an email style address, perform webfinger lookup and
179 * return the resulting DFRN profile URL, or if no DFRN profile URL
180 * is located, returns an OStatus subscription template (prefixed
181 * with the string 'stat:' to identify it as on OStatus template).
182 * If this isn't an email style address just return $webbie.
183 * Return an empty string if email-style addresses but webfinger fails,
184 * or if the resultant personal XRD doesn't contain a supported
185 * subscription/friend-request attribute.
187 * amended 7/9/2011 to return an hcard which could save potentially loading
188 * a lengthy content page to scrape dfrn attributes
190 * @param string $webbie Address that should be probed
191 * @param string $hcard_url Link to the hcard - is returned by reference
193 * @return string profile link
194 * @throws HTTPException\InternalServerErrorException
196 public static function webfingerDfrn($webbie, &$hcard_url)
200 $links = self::lrdd($webbie);
201 Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA);
202 if (!empty($links) && is_array($links)) {
203 foreach ($links as $link) {
204 if ($link['@attributes']['rel'] === ActivityNamespace::DFRN) {
205 $profile_link = $link['@attributes']['href'];
207 if (($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) && ($profile_link == "")) {
208 $profile_link = 'stat:'.$link['@attributes']['template'];
210 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
211 $hcard_url = $link['@attributes']['href'];
215 return $profile_link;
219 * @brief Check an URI for LRDD data
221 * this is a replacement for the "lrdd" function.
222 * It isn't used in this class and has some redundancies in the code.
223 * When time comes we can check the existing calls for "lrdd" if we can rework them.
225 * @param string $uri Address that should be probed
227 * @return array uri data
228 * @throws HTTPException\InternalServerErrorException
230 public static function lrdd($uri)
232 $lrdd = self::hostMeta($uri);
235 if (is_bool($lrdd)) {
240 $parts = @parse_url($uri);
241 if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
245 $host = $parts["host"];
246 if (!empty($parts["port"])) {
247 $host .= ':'.$parts["port"];
250 $path_parts = explode("/", trim($parts["path"], "/"));
252 $nick = array_pop($path_parts);
255 $lrdd = self::hostMeta($host);
256 $host .= "/".array_shift($path_parts);
257 } while (!$lrdd && (sizeof($path_parts) > 0));
261 Logger::log("No lrdd data found for ".$uri, Logger::DEBUG);
265 foreach ($lrdd as $type => $template) {
270 $path = str_replace('{uri}', urlencode($uri), $template);
271 $webfinger = self::webfinger($path, $type);
273 if (!$webfinger && (strstr($uri, "@"))) {
274 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
275 $webfinger = self::webfinger($path, $type);
278 // Special treatment for Mastodon
279 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
280 // But the webfinger for this format fails.
281 if (!$webfinger && !empty($nick)) {
282 // Mastodon uses a "@" as prefix for usernames in their url format
283 $nick = ltrim($nick, '@');
285 $addr = $nick."@".$host;
287 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
288 $webfinger = self::webfinger($path, $type);
292 if (!is_array($webfinger["links"])) {
293 Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
299 foreach ($webfinger["links"] as $link) {
300 $data[] = ["@attributes" => $link];
303 if (is_array($webfinger["aliases"])) {
304 foreach ($webfinger["aliases"] as $alias) {
305 $data[] = ["@attributes" =>
315 * @brief Fetch information (protocol endpoints and user information) about a given uri
317 * @param string $uri Address that should be probed
318 * @param string $network Test for this specific network
319 * @param integer $uid User ID for the probe (only used for mails)
320 * @param boolean $cache Use cached values?
322 * @return array uri data
323 * @throws HTTPException\InternalServerErrorException
324 * @throws \ImagickException
326 public static function uri($uri, $network = '', $uid = -1, $cache = true)
329 $result = Cache::get('Probe::uri:' . $network . ':' . $uri);
330 if (!is_null($result)) {
339 self::$istimeout = false;
341 if ($network != Protocol::ACTIVITYPUB) {
342 $data = self::detect($uri, $network, $uid);
347 // When the previous detection process had got a time out
348 // we could falsely detect a Friendica profile as AP profile.
349 if (!self::$istimeout) {
350 $ap_profile = ActivityPub::probeProfile($uri);
352 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
354 } elseif (!empty($ap_profile)) {
355 $ap_profile['batch'] = '';
356 $data = array_merge($ap_profile, $data);
359 Logger::notice('Time out detected. AP will not be probed.', ['uri' => $uri]);
362 if (!isset($data['url'])) {
366 if (!empty($data['photo']) && !empty($data['baseurl'])) {
367 $data['baseurl'] = Network::getUrlMatch(Strings::normaliseLink($data['baseurl']), Strings::normaliseLink($data['photo']));
368 } elseif (empty($data['photo'])) {
369 $data['photo'] = System::baseUrl() . '/images/person-300.jpg';
372 if (empty($data['name'])) {
373 if (!empty($data['nick'])) {
374 $data['name'] = $data['nick'];
377 if (empty($data['name'])) {
378 $data['name'] = $data['url'];
382 if (empty($data['nick'])) {
383 $data['nick'] = strtolower($data['name']);
385 if (strpos($data['nick'], ' ')) {
386 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
390 if (!empty(self::$baseurl)) {
391 $data['baseurl'] = self::$baseurl;
394 if (empty($data['network'])) {
395 $data['network'] = Protocol::PHANTOM;
398 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
399 $data['hide'] = self::getHideStatus($data['url']);
402 $data = self::rearrangeData($data);
404 // Only store into the cache if the value seems to be valid
405 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
406 Cache::set('Probe::uri:' . $network . ':' . $uri, $data, Cache::DAY);
414 * Fetches the "hide" status from the profile
416 * @param string $url URL of the profile
418 * @return boolean "hide" status
420 private static function getHideStatus($url)
422 $curlResult = Network::curl($url);
423 if (!$curlResult->isSuccess()) {
427 // If the file is too large then exit
428 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
432 // If it isn't a HTML file then exit
433 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
437 $body = $curlResult->getBody();
439 $doc = new DOMDocument();
440 @$doc->loadHTML($body);
442 $xpath = new DOMXPath($doc);
444 $list = $xpath->query('//meta[@name]');
445 foreach ($list as $node) {
447 if ($node->attributes->length) {
448 foreach ($node->attributes as $attribute) {
449 $meta_tag[$attribute->name] = $attribute->value;
453 if (empty($meta_tag['content'])) {
457 $content = strtolower(trim($meta_tag['content']));
459 switch (strtolower(trim($meta_tag['name']))) {
460 case 'dfrn-global-visibility':
461 if ($content == 'false') {
466 if (strpos($content, 'noindex') !== false) {
477 * @brief Checks if a profile url should be OStatus but only provides partial information
479 * @param array $webfinger Webfinger data
480 * @param string $lrdd Path template for webfinger request
481 * @param string $type type
483 * @return array fixed webfinger data
484 * @throws HTTPException\InternalServerErrorException
486 private static function fixOStatus($webfinger, $lrdd, $type)
488 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
495 foreach ($webfinger['links'] as $link) {
496 if ($link['rel'] == ActivityNamespace::OSTATUSSUB) {
499 if ($link['rel'] == 'magic-public-key') {
504 if (!$is_ostatus || $has_key) {
508 $url = Network::switchScheme($webfinger['subject']);
509 $path = str_replace('{uri}', urlencode($url), $lrdd);
510 $webfinger2 = self::webfinger($path, $type);
512 // Is the new webfinger detectable as OStatus?
513 if (self::ostatus($webfinger2, true)) {
514 $webfinger = $webfinger2;
521 * @brief Fetch information (protocol endpoints and user information) about a given uri
523 * This function is only called by the "uri" function that adds caching and rearranging of data.
525 * @param string $uri Address that should be probed
526 * @param string $network Test for this specific network
527 * @param integer $uid User ID for the probe (only used for mails)
529 * @return array uri data
530 * @throws HTTPException\InternalServerErrorException
532 private static function detect($uri, $network, $uid)
534 $parts = parse_url($uri);
536 if (!empty($parts["scheme"]) && !empty($parts["host"])) {
537 $host = $parts["host"];
538 if (!empty($parts["port"])) {
539 $host .= ':'.$parts["port"];
542 if ($host == 'twitter.com') {
543 return self::twitter($uri);
545 $lrdd = self::hostMeta($host);
547 if (is_bool($lrdd)) {
551 $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
553 while (!$lrdd && (sizeof($path_parts) > 1)) {
554 $host .= "/".array_shift($path_parts);
555 $lrdd = self::hostMeta($host);
558 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
559 return self::feed($uri);
561 $nick = array_pop($path_parts);
563 // Mastodon uses a "@" as prefix for usernames in their url format
564 $nick = ltrim($nick, '@');
566 $addr = $nick."@".$host;
567 } elseif (strstr($uri, '@')) {
568 // If the URI starts with "mailto:" then jump directly to the mail detection
569 if (strpos($uri, 'mailto:') !== false) {
570 $uri = str_replace('mailto:', '', $uri);
571 return self::mail($uri, $uid);
574 if ($network == Protocol::MAIL) {
575 return self::mail($uri, $uid);
577 // Remove "acct:" from the URI
578 $uri = str_replace('acct:', '', $uri);
580 $host = substr($uri, strpos($uri, '@') + 1);
581 $nick = substr($uri, 0, strpos($uri, '@'));
583 if (strpos($uri, '@twitter.com')) {
584 return self::twitter($uri);
586 $lrdd = self::hostMeta($host);
588 if (is_bool($lrdd)) {
593 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
594 return self::mail($uri, $uid);
598 Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
604 /// @todo Do we need the prefix "acct:" or "acct://"?
606 foreach ($lrdd as $type => $template) {
611 // At first try it with the given uri
612 $path = str_replace('{uri}', urlencode($uri), $template);
613 $webfinger = self::webfinger($path, $type);
615 // Fix possible problems with GNU Social probing to wrong scheme
616 $webfinger = self::fixOStatus($webfinger, $template, $type);
618 // We cannot be sure that the detected address was correct, so we don't use the values
619 if ($webfinger && ($uri != $addr)) {
624 // Try webfinger with the address (user@domain.tld)
626 $path = str_replace('{uri}', urlencode($addr), $template);
627 $webfinger = self::webfinger($path, $type);
630 // Mastodon needs to have it with "acct:"
632 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
633 $webfinger = self::webfinger($path, $type);
638 return self::feed($uri);
643 Logger::log("Probing ".$uri, Logger::DEBUG);
645 if (in_array($network, ["", Protocol::DFRN])) {
646 $result = self::dfrn($webfinger);
648 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
649 $result = self::diaspora($webfinger);
651 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
652 $result = self::ostatus($webfinger);
654 if (in_array($network, ['', Protocol::ZOT])) {
655 $result = self::zot($webfinger, $result);
657 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
658 $result = self::pumpio($webfinger, $addr);
660 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
661 $result = self::feed($uri);
663 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
664 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
665 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
666 $result["nick"] = $nick;
669 if (empty($result["addr"]) && ($addr != "")) {
670 $result["addr"] = $addr;
674 if (empty($result["network"])) {
675 $result["network"] = Protocol::PHANTOM;
678 if (empty($result["url"])) {
679 $result["url"] = $uri;
682 Logger::log($uri." is ".$result["network"], Logger::DEBUG);
684 if (empty($result["baseurl"]) && ($result["network"] != Protocol::PHANTOM)) {
685 $pos = strpos($result["url"], $host);
687 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
694 * Check for Zot contact
696 * @param array $webfinger Webfinger data
697 * @param array $data previously probed data
699 * @return array Zot data
700 * @throws HTTPException\InternalServerErrorException
702 private static function zot($webfinger, $data)
704 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
705 foreach ($webfinger["aliases"] as $alias) {
706 if (substr($alias, 0, 5) == 'acct:') {
707 $data["addr"] = substr($alias, 5);
712 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
713 $data["addr"] = substr($webfinger["subject"], 5);
717 foreach ($webfinger['links'] as $link) {
718 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
719 $zot_url = $link['href'];
723 if (empty($zot_url) && !empty($data['addr']) && !empty(self::$baseurl)) {
724 $condition = ['nurl' => Strings::normaliseLink(self::$baseurl), 'platform' => ['hubzilla']];
725 if (!DBA::exists('gserver', $condition)) {
728 $zot_url = self::$baseurl . '/.well-known/zot-info?address=' . $data['addr'];
731 if (empty($zot_url)) {
735 $data = self::pollZot($zot_url, $data);
737 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
738 foreach ($webfinger['aliases'] as $alias) {
739 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
740 $data['alias'] = $alias;
748 public static function pollZot($url, $data)
750 $curlResult = Network::curl($url);
751 if ($curlResult->isTimeout()) {
754 $content = $curlResult->getBody();
759 $json = json_decode($content, true);
760 if (!is_array($json)) {
764 if (empty($data['network'])) {
765 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
766 $data['network'] = Protocol::ZOT;
767 } elseif (!isset($json['protocols'])) {
768 $data['network'] = Protocol::ZOT;
772 if (!empty($json['guid']) && empty($data['guid'])) {
773 $data['guid'] = $json['guid'];
775 if (!empty($json['key']) && empty($data['pubkey'])) {
776 $data['pubkey'] = $json['key'];
778 if (!empty($json['name'])) {
779 $data['name'] = $json['name'];
781 if (!empty($json['photo'])) {
782 $data['photo'] = $json['photo'];
783 if (!empty($json['photo_updated'])) {
784 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
787 if (!empty($json['address'])) {
788 $data['addr'] = $json['address'];
790 if (!empty($json['url'])) {
791 $data['url'] = $json['url'];
793 if (!empty($json['connections_url'])) {
794 $data['poco'] = $json['connections_url'];
796 if (isset($json['searchable'])) {
797 $data['hide'] = !$json['searchable'];
799 if (!empty($json['public_forum'])) {
800 $data['community'] = $json['public_forum'];
801 $data['account-type'] = Contact::PAGE_COMMUNITY;
804 if (!empty($json['profile'])) {
805 $profile = $json['profile'];
806 if (!empty($profile['description'])) {
807 $data['about'] = $profile['description'];
809 if (!empty($profile['gender'])) {
810 $data['gender'] = $profile['gender'];
812 if (!empty($profile['keywords'])) {
813 $keywords = implode(', ', $profile['keywords']);
814 if (!empty($keywords)) {
815 $data['keywords'] = $keywords;
820 if (!empty($profile['region'])) {
821 $loc['region'] = $profile['region'];
823 if (!empty($profile['country'])) {
824 $loc['country-name'] = $profile['country'];
826 if (!empty($profile['hometown'])) {
827 $loc['locality'] = $profile['hometown'];
829 $location = Profile::formatLocation($loc);
830 if (!empty($location)) {
831 $data['location'] = $location;
839 * @brief Perform a webfinger request.
841 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
843 * @param string $url Address that should be probed
844 * @param string $type type
846 * @return array webfinger data
847 * @throws HTTPException\InternalServerErrorException
849 private static function webfinger($url, $type)
851 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
853 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
854 if ($curlResult->isTimeout()) {
855 self::$istimeout = true;
858 $data = $curlResult->getBody();
860 $webfinger = json_decode($data, true);
861 if (is_array($webfinger)) {
862 if (!isset($webfinger["links"])) {
863 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
869 // If it is not JSON, maybe it is XML
870 $xrd = XML::parseString($data, false);
871 if (!is_object($xrd)) {
872 Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
876 $xrd_arr = XML::elementToArray($xrd);
877 if (!isset($xrd_arr["xrd"]["link"])) {
878 Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
884 if (!empty($xrd_arr["xrd"]["subject"])) {
885 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
888 if (!empty($xrd_arr["xrd"]["alias"])) {
889 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
892 $webfinger["links"] = [];
894 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
895 if (!empty($data["@attributes"])) {
896 $attributes = $data["@attributes"];
897 } elseif ($value == "@attributes") {
903 $webfinger["links"][] = $attributes;
909 * @brief Poll the Friendica specific noscrape page.
911 * "noscrape" is a faster alternative to fetch the data from the hcard.
912 * This functionality was originally created for the directory.
914 * @param string $noscrape_url Link to the noscrape page
915 * @param array $data The already fetched data
917 * @return array noscrape data
918 * @throws HTTPException\InternalServerErrorException
920 private static function pollNoscrape($noscrape_url, $data)
922 $curlResult = Network::curl($noscrape_url);
923 if ($curlResult->isTimeout()) {
924 self::$istimeout = true;
927 $content = $curlResult->getBody();
929 Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
933 $json = json_decode($content, true);
934 if (!is_array($json)) {
935 Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
939 if (!empty($json["fn"])) {
940 $data["name"] = $json["fn"];
943 if (!empty($json["addr"])) {
944 $data["addr"] = $json["addr"];
947 if (!empty($json["nick"])) {
948 $data["nick"] = $json["nick"];
951 if (!empty($json["guid"])) {
952 $data["guid"] = $json["guid"];
955 if (!empty($json["comm"])) {
956 $data["community"] = $json["comm"];
959 if (!empty($json["tags"])) {
960 $keywords = implode(", ", $json["tags"]);
961 if ($keywords != "") {
962 $data["keywords"] = $keywords;
966 $location = Profile::formatLocation($json);
968 $data["location"] = $location;
971 if (!empty($json["about"])) {
972 $data["about"] = $json["about"];
975 if (!empty($json["gender"])) {
976 $data["gender"] = $json["gender"];
979 if (!empty($json["key"])) {
980 $data["pubkey"] = $json["key"];
983 if (!empty($json["photo"])) {
984 $data["photo"] = $json["photo"];
987 if (!empty($json["dfrn-request"])) {
988 $data["request"] = $json["dfrn-request"];
991 if (!empty($json["dfrn-confirm"])) {
992 $data["confirm"] = $json["dfrn-confirm"];
995 if (!empty($json["dfrn-notify"])) {
996 $data["notify"] = $json["dfrn-notify"];
999 if (!empty($json["dfrn-poll"])) {
1000 $data["poll"] = $json["dfrn-poll"];
1003 if (isset($json["hide"])) {
1004 $data["hide"] = (bool)$json["hide"];
1006 $data["hide"] = false;
1013 * @brief Check for valid DFRN data
1015 * @param array $data DFRN data
1017 * @return int Number of errors
1019 public static function validDfrn($data)
1022 if (!isset($data['key'])) {
1025 if (!isset($data['dfrn-request'])) {
1028 if (!isset($data['dfrn-confirm'])) {
1031 if (!isset($data['dfrn-notify'])) {
1034 if (!isset($data['dfrn-poll'])) {
1041 * @brief Fetch data from a DFRN profile page and via "noscrape"
1043 * @param string $profile_link Link to the profile page
1045 * @return array profile data
1046 * @throws HTTPException\InternalServerErrorException
1047 * @throws \ImagickException
1049 public static function profile($profile_link)
1053 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
1055 // Fetch data via noscrape - this is faster
1056 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1057 $data = self::pollNoscrape($noscrape_url, $data);
1059 if (!isset($data["notify"])
1060 || !isset($data["confirm"])
1061 || !isset($data["request"])
1062 || !isset($data["poll"])
1063 || !isset($data["name"])
1064 || !isset($data["photo"])
1066 $data = self::pollHcard($profile_link, $data, true);
1071 if (empty($data["addr"]) || empty($data["nick"])) {
1072 $probe_data = self::uri($profile_link);
1073 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1074 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1077 $prof_data["addr"] = $data["addr"];
1078 $prof_data["nick"] = $data["nick"];
1079 $prof_data["dfrn-request"] = $data['request'] ?? null;
1080 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1081 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1082 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1083 $prof_data["photo"] = $data['photo'] ?? null;
1084 $prof_data["fn"] = $data['name'] ?? null;
1085 $prof_data["key"] = $data['pubkey'] ?? null;
1087 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
1093 * @brief Check for DFRN contact
1095 * @param array $webfinger Webfinger data
1097 * @return array DFRN data
1098 * @throws HTTPException\InternalServerErrorException
1100 private static function dfrn($webfinger)
1104 // The array is reversed to take into account the order of preference for same-rel links
1105 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1106 foreach (array_reverse($webfinger["links"]) as $link) {
1107 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1108 $data["network"] = Protocol::DFRN;
1109 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1110 $data["poll"] = $link["href"];
1111 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1112 $data["url"] = $link["href"];
1113 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1114 $hcard_url = $link["href"];
1115 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1116 $data["poco"] = $link["href"];
1117 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1118 $data["photo"] = $link["href"];
1119 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1120 $data["baseurl"] = trim($link["href"], '/');
1121 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1122 $data["guid"] = $link["href"];
1123 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1124 $data["pubkey"] = base64_decode($link["href"]);
1126 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1127 if (strstr($data["pubkey"], 'RSA ')) {
1128 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1133 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1134 foreach ($webfinger["aliases"] as $alias) {
1135 if (empty($data["url"]) && !strstr($alias, "@")) {
1136 $data["url"] = $alias;
1137 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1138 $data["alias"] = $alias;
1139 } elseif (substr($alias, 0, 5) == 'acct:') {
1140 $data["addr"] = substr($alias, 5);
1145 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1146 $data["addr"] = substr($webfinger["subject"], 5);
1149 if (!isset($data["network"]) || ($hcard_url == "")) {
1153 // Fetch data via noscrape - this is faster
1154 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1155 $data = self::pollNoscrape($noscrape_url, $data);
1157 if (isset($data["notify"])
1158 && isset($data["confirm"])
1159 && isset($data["request"])
1160 && isset($data["poll"])
1161 && isset($data["name"])
1162 && isset($data["photo"])
1167 $data = self::pollHcard($hcard_url, $data, true);
1173 * @brief Poll the hcard page (Diaspora and Friendica specific)
1175 * @param string $hcard_url Link to the hcard page
1176 * @param array $data The already fetched data
1177 * @param boolean $dfrn Poll DFRN specific data
1179 * @return array hcard data
1180 * @throws HTTPException\InternalServerErrorException
1182 private static function pollHcard($hcard_url, $data, $dfrn = false)
1184 $curlResult = Network::curl($hcard_url);
1185 if ($curlResult->isTimeout()) {
1186 self::$istimeout = true;
1189 $content = $curlResult->getBody();
1194 $doc = new DOMDocument();
1195 if (!@$doc->loadHTML($content)) {
1199 $xpath = new DomXPath($doc);
1201 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1202 if (!is_object($vcards)) {
1206 if (!isset($data["baseurl"])) {
1207 $data["baseurl"] = "";
1210 if ($vcards->length > 0) {
1211 $vcard = $vcards->item(0);
1213 // We have to discard the guid from the hcard in favour of the guid from lrdd
1214 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1215 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1216 if (($search->length > 0) && empty($data["guid"])) {
1217 $data["guid"] = $search->item(0)->nodeValue;
1220 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1221 if ($search->length > 0) {
1222 $data["nick"] = $search->item(0)->nodeValue;
1225 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1226 if ($search->length > 0) {
1227 $data["name"] = $search->item(0)->nodeValue;
1230 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1231 if ($search->length > 0) {
1232 $data["searchable"] = $search->item(0)->nodeValue;
1235 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1236 if ($search->length > 0) {
1237 $data["pubkey"] = $search->item(0)->nodeValue;
1238 if (strstr($data["pubkey"], 'RSA ')) {
1239 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1243 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1244 if ($search->length > 0) {
1245 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1250 if (!empty($vcard)) {
1251 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1252 foreach ($photos as $photo) {
1254 foreach ($photo->attributes as $attribute) {
1255 $attr[$attribute->name] = trim($attribute->value);
1258 if (isset($attr["src"]) && isset($attr["width"])) {
1259 $avatar[$attr["width"]] = $attr["src"];
1262 // We don't have a width. So we just take everything that we got.
1263 // This is a Hubzilla workaround which doesn't send a width.
1264 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1265 $avatar[] = $attr["src"];
1270 if (sizeof($avatar)) {
1272 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1276 // Poll DFRN specific data
1277 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1278 if ($search->length > 0) {
1279 foreach ($search as $link) {
1280 //$data["request"] = $search->item(0)->nodeValue;
1282 foreach ($link->attributes as $attribute) {
1283 $attr[$attribute->name] = trim($attribute->value);
1286 $data[substr($attr["rel"], 5)] = $attr["href"];
1290 // Older Friendica versions had used the "uid" field differently than newer versions
1291 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1292 unset($data["guid"]);
1301 * @brief Check for Diaspora contact
1303 * @param array $webfinger Webfinger data
1305 * @return array Diaspora data
1306 * @throws HTTPException\InternalServerErrorException
1308 private static function diaspora($webfinger)
1313 // The array is reversed to take into account the order of preference for same-rel links
1314 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1315 foreach (array_reverse($webfinger["links"]) as $link) {
1316 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1317 $hcard_url = $link["href"];
1318 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1319 $data["baseurl"] = trim($link["href"], '/');
1320 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1321 $data["guid"] = $link["href"];
1322 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1323 $data["url"] = $link["href"];
1324 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1325 $data["poll"] = $link["href"];
1326 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1327 $data["poco"] = $link["href"];
1328 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1329 $data["notify"] = $link["href"];
1330 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1331 $data["pubkey"] = base64_decode($link["href"]);
1333 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1334 if (strstr($data["pubkey"], 'RSA ')) {
1335 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1340 if (empty($data["url"]) || empty($hcard_url)) {
1344 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1345 foreach ($webfinger["aliases"] as $alias) {
1346 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1347 $data["alias"] = $alias;
1348 } elseif (substr($alias, 0, 5) == 'acct:') {
1349 $data["addr"] = substr($alias, 5);
1354 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1355 $data["addr"] = substr($webfinger["subject"], 5);
1358 // Fetch further information from the hcard
1359 $data = self::pollHcard($hcard_url, $data);
1365 if (!empty($data["url"])
1366 && !empty($data["guid"])
1367 && !empty($data["baseurl"])
1368 && !empty($data["pubkey"])
1369 && !empty($hcard_url)
1371 $data["network"] = Protocol::DIASPORA;
1373 // The Diaspora handle must always be lowercase
1374 if (!empty($data["addr"])) {
1375 $data["addr"] = strtolower($data["addr"]);
1378 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1379 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1380 $data["batch"] = $data["baseurl"] . "/receive/public";
1389 * @brief Check for OStatus contact
1391 * @param array $webfinger Webfinger data
1392 * @param bool $short Short detection mode
1394 * @return array|bool OStatus data or "false" on error or "true" on short mode
1395 * @throws HTTPException\InternalServerErrorException
1397 private static function ostatus($webfinger, $short = false)
1401 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1402 foreach ($webfinger["aliases"] as $alias) {
1403 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1404 $data["addr"] = str_replace('acct:', '', $alias);
1409 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1410 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1412 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1415 if (is_array($webfinger["links"])) {
1416 // The array is reversed to take into account the order of preference for same-rel links
1417 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1418 foreach (array_reverse($webfinger["links"]) as $link) {
1419 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1420 && (($link["type"] ?? "") == "text/html")
1421 && ($link["href"] != "")
1423 $data["url"] = $link["href"];
1424 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1425 $data["notify"] = $link["href"];
1426 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1427 $data["poll"] = $link["href"];
1428 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1429 $pubkey = $link["href"];
1431 if (substr($pubkey, 0, 5) === 'data:') {
1432 if (strstr($pubkey, ',')) {
1433 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1435 $pubkey = substr($pubkey, 5);
1437 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1438 $curlResult = Network::curl($pubkey);
1439 if ($curlResult->isTimeout()) {
1440 self::$istimeout = true;
1443 $pubkey = $curlResult->getBody();
1446 $key = explode(".", $pubkey);
1448 if (sizeof($key) >= 3) {
1449 $m = Strings::base64UrlDecode($key[1]);
1450 $e = Strings::base64UrlDecode($key[2]);
1451 $data["pubkey"] = Crypto::meToPem($m, $e);
1457 if (isset($data["notify"]) && isset($data["pubkey"])
1458 && isset($data["poll"])
1459 && isset($data["url"])
1461 $data["network"] = Protocol::OSTATUS;
1470 // Fetch all additional data from the feed
1471 $curlResult = Network::curl($data["poll"]);
1472 if ($curlResult->isTimeout()) {
1473 self::$istimeout = true;
1476 $feed = $curlResult->getBody();
1480 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1485 if (!empty($feed_data["header"]["author-name"])) {
1486 $data["name"] = $feed_data["header"]["author-name"];
1488 if (!empty($feed_data["header"]["author-nick"])) {
1489 $data["nick"] = $feed_data["header"]["author-nick"];
1491 if (!empty($feed_data["header"]["author-avatar"])) {
1492 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1494 if (!empty($feed_data["header"]["author-id"])) {
1495 $data["alias"] = $feed_data["header"]["author-id"];
1497 if (!empty($feed_data["header"]["author-location"])) {
1498 $data["location"] = $feed_data["header"]["author-location"];
1500 if (!empty($feed_data["header"]["author-about"])) {
1501 $data["about"] = $feed_data["header"]["author-about"];
1503 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1504 // So we take the value that we just fetched, although the other one worked as well
1505 if (!empty($feed_data["header"]["author-link"])) {
1506 $data["url"] = $feed_data["header"]["author-link"];
1509 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1510 $data['url'] = $data["alias"];
1511 $data["alias"] = '';
1514 /// @todo Fetch location and "about" from the feed as well
1519 * @brief Fetch data from a pump.io profile page
1521 * @param string $profile_link Link to the profile page
1523 * @return array profile data
1525 private static function pumpioProfileData($profile_link)
1527 $curlResult = Network::curl($profile_link);
1528 if (!$curlResult->isSuccess()) {
1532 $doc = new DOMDocument();
1533 if (!@$doc->loadHTML($curlResult->getBody())) {
1537 $xpath = new DomXPath($doc);
1541 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1543 if ($data["name"] == '') {
1544 // This is ugly - but pump.io doesn't seem to know a better way for it
1545 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1546 $pos = strpos($data["name"], chr(10));
1548 $data["name"] = trim(substr($data["name"], 0, $pos));
1552 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1554 if ($data["location"] == '') {
1555 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1558 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1560 if ($data["about"] == '') {
1561 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1564 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1566 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1569 foreach ($avatar->attributes as $attribute) {
1570 if ($attribute->name == "src") {
1571 $data["photo"] = trim($attribute->value);
1580 * @brief Check for pump.io contact
1582 * @param array $webfinger Webfinger data
1583 * @param string $addr
1584 * @return array pump.io data
1586 private static function pumpio($webfinger, $addr)
1589 // The array is reversed to take into account the order of preference for same-rel links
1590 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1591 foreach (array_reverse($webfinger["links"]) as $link) {
1592 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1593 && (($link["type"] ?? "") == "text/html")
1594 && ($link["href"] != "")
1596 $data["url"] = $link["href"];
1597 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1598 $data["notify"] = $link["href"];
1599 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1600 $data["poll"] = $link["href"];
1601 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1602 $data["dialback"] = $link["href"];
1605 if (isset($data["poll"]) && isset($data["notify"])
1606 && isset($data["dialback"])
1607 && isset($data["url"])
1609 // by now we use these fields only for the network type detection
1610 // So we unset all data that isn't used at the moment
1611 unset($data["dialback"]);
1613 $data["network"] = Protocol::PUMPIO;
1618 $profile_data = self::pumpioProfileData($data["url"]);
1620 if (!$profile_data) {
1624 $data = array_merge($data, $profile_data);
1626 if (($addr != '') && ($data['name'] != '')) {
1627 $name = trim(str_replace($addr, '', $data['name']));
1629 $data['name'] = $name;
1637 * @brief Check for twitter contact
1639 * @param string $uri
1641 * @return array twitter data
1643 private static function twitter($uri)
1645 if (preg_match('=(.*)@twitter.com=i', $uri, $matches)) {
1646 $nick = $matches[1];
1647 } elseif (preg_match('=https?://twitter.com/(.*)=i', $uri, $matches)) {
1648 $nick = $matches[1];
1654 $data['url'] = 'https://twitter.com/' . $nick;
1655 $data['addr'] = $nick . '@twitter.com';
1656 $data['nick'] = $data['name'] = $nick;
1657 $data['network'] = Protocol::TWITTER;
1658 $data['baseurl'] = 'https://twitter.com';
1660 $curlResult = Network::curl($data['url'], false);
1661 if (!$curlResult->isSuccess()) {
1665 $body = $curlResult->getBody();
1666 $doc = new DOMDocument();
1667 @$doc->loadHTML($body);
1668 $xpath = new DOMXPath($doc);
1670 $list = $xpath->query('//img[@class]');
1671 foreach ($list as $node) {
1673 if ($node->attributes->length) {
1674 foreach ($node->attributes as $attribute) {
1675 $img_attr[$attribute->name] = $attribute->value;
1679 if (empty($img_attr['class'])) {
1683 if (strpos($img_attr['class'], 'ProfileAvatar-image') !== false) {
1684 if (!empty($img_attr['src'])) {
1685 $data['photo'] = $img_attr['src'];
1687 if (!empty($img_attr['alt'])) {
1688 $data['name'] = $img_attr['alt'];
1697 * @brief Check page for feed link
1699 * @param string $url Page link
1701 * @return string feed link
1703 private static function getFeedLink($url)
1705 $curlResult = Network::curl($url);
1706 if (!$curlResult->isSuccess()) {
1710 $doc = new DOMDocument();
1711 if (!@$doc->loadHTML($curlResult->getBody())) {
1715 $xpath = new DomXPath($doc);
1717 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1718 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1719 if (!is_object($feeds)) {
1723 if ($feeds->length == 0) {
1729 foreach ($feeds as $feed) {
1731 foreach ($feed->attributes as $attribute) {
1732 $attr[$attribute->name] = trim($attribute->value);
1735 if (empty($feed_url) && !empty($attr['href'])) {
1736 $feed_url = $attr["href"];
1744 * @brief Check for feed contact
1746 * @param string $url Profile link
1747 * @param boolean $probe Do a probe if the page contains a feed link
1749 * @return array feed data
1750 * @throws HTTPException\InternalServerErrorException
1752 private static function feed($url, $probe = true)
1754 $curlResult = Network::curl($url);
1755 if ($curlResult->isTimeout()) {
1756 self::$istimeout = true;
1759 $feed = $curlResult->getBody();
1760 $dummy1 = $dummy2 = $dummy3 = null;
1761 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1768 $feed_url = self::getFeedLink($url);
1774 return self::feed($feed_url, false);
1777 if (!empty($feed_data["header"]["author-name"])) {
1778 $data["name"] = $feed_data["header"]["author-name"];
1781 if (!empty($feed_data["header"]["author-nick"])) {
1782 $data["nick"] = $feed_data["header"]["author-nick"];
1785 if (!empty($feed_data["header"]["author-avatar"])) {
1786 $data["photo"] = $feed_data["header"]["author-avatar"];
1789 if (!empty($feed_data["header"]["author-id"])) {
1790 $data["alias"] = $feed_data["header"]["author-id"];
1793 $data["url"] = $url;
1794 $data["poll"] = $url;
1796 if (!empty($feed_data["header"]["author-link"])) {
1797 $data["baseurl"] = $feed_data["header"]["author-link"];
1799 $data["baseurl"] = $data["url"];
1802 $data["network"] = Protocol::FEED;
1808 * @brief Check for mail contact
1810 * @param string $uri Profile link
1811 * @param integer $uid User ID
1813 * @return array mail data
1814 * @throws \Exception
1816 private static function mail($uri, $uid)
1818 if (!Network::isEmailDomainValid($uri)) {
1826 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1828 $condition = ["`uid` = ? AND `server` != ''", $uid];
1829 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1830 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1832 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1836 $mailbox = Email::constructMailboxName($mailacct);
1838 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1839 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1844 $msgs = Email::poll($mbox, $uri);
1845 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1847 if (!count($msgs)) {
1851 $phost = substr($uri, strpos($uri, '@') + 1);
1854 $data["addr"] = $uri;
1855 $data["network"] = Protocol::MAIL;
1856 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1857 $data["nick"] = $data["name"];
1858 $data["photo"] = Network::lookupAvatarByEmail($uri);
1859 $data["url"] = 'mailto:'.$uri;
1860 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1861 $data["poll"] = 'email ' . Strings::getRandomHex();
1863 $x = Email::messageMeta($mbox, $msgs[0]);
1864 if (stristr($x[0]->from, $uri)) {
1865 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1866 } elseif (stristr($x[0]->to, $uri)) {
1867 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1870 foreach ($adr as $feadr) {
1871 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1872 &&(strcasecmp($feadr->host, $phost) == 0)
1873 && (strlen($feadr->personal))
1875 $personal = imap_mime_header_decode($feadr->personal);
1877 foreach ($personal as $perspart) {
1878 if ($perspart->charset != "default") {
1879 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1881 $data["name"] .= $perspart->text;
1885 $data["name"] = Strings::escapeTags($data["name"]);
1889 if (!empty($mbox)) {
1896 * @brief Mix two paths together to possibly fix missing parts
1898 * @param string $avatar Path to the avatar
1899 * @param string $base Another path that is hopefully complete
1901 * @return string fixed avatar path
1902 * @throws \Exception
1904 public static function fixAvatar($avatar, $base)
1906 $base_parts = parse_url($base);
1908 // Remove all parts that could create a problem
1909 unset($base_parts['path']);
1910 unset($base_parts['query']);
1911 unset($base_parts['fragment']);
1913 $avatar_parts = parse_url($avatar);
1916 $parts = array_merge($base_parts, $avatar_parts);
1918 // And put them together again
1919 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1920 $host = isset($parts['host']) ? $parts['host'] : '';
1921 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1922 $path = isset($parts['path']) ? $parts['path'] : '';
1923 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1924 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1926 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1928 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);