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\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 = DI::baseUrl()->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 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
119 if ($curlResult->isSuccess()) {
120 $xml = $curlResult->getBody();
121 $xrd = XML::parseString($xml, false);
122 $host_url = 'https://'.$host;
123 } elseif ($curlResult->isTimeout()) {
124 Logger::info('Probing timeout', ['url' => $ssl_url], Logger::DEBUG);
125 self::$istimeout = true;
129 if (!is_object($xrd)) {
130 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
131 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
132 if ($curlResult->isTimeout()) {
133 Logger::info('Probing timeout', ['url' => $url], Logger::DEBUG);
134 self::$istimeout = true;
136 } elseif ($connection_error && $ssl_connection_error) {
137 self::$istimeout = true;
141 $xml = $curlResult->getBody();
142 $xrd = XML::parseString($xml, false);
143 $host_url = 'http://'.$host;
145 if (!is_object($xrd)) {
146 Logger::log("No xrd object found for ".$host, Logger::DEBUG);
150 $links = XML::elementToArray($xrd);
151 if (!isset($links["xrd"]["link"])) {
152 Logger::log("No xrd data found for ".$host, Logger::DEBUG);
156 $lrdd = ['application/jrd+json' => $host_url . '/.well-known/webfinger?resource={uri}'];
158 foreach ($links["xrd"]["link"] as $value => $link) {
159 if (!empty($link["@attributes"])) {
160 $attributes = $link["@attributes"];
161 } elseif ($value == "@attributes") {
167 if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
168 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
170 $lrdd[$type] = $attributes["template"];
174 self::$baseurl = $host_url;
176 Logger::log("Probing successful for ".$host, Logger::DEBUG);
182 * @brief Perform Webfinger lookup and return DFRN data
184 * Given an email style address, perform webfinger lookup and
185 * return the resulting DFRN profile URL, or if no DFRN profile URL
186 * is located, returns an OStatus subscription template (prefixed
187 * with the string 'stat:' to identify it as on OStatus template).
188 * If this isn't an email style address just return $webbie.
189 * Return an empty string if email-style addresses but webfinger fails,
190 * or if the resultant personal XRD doesn't contain a supported
191 * subscription/friend-request attribute.
193 * amended 7/9/2011 to return an hcard which could save potentially loading
194 * a lengthy content page to scrape dfrn attributes
196 * @param string $webbie Address that should be probed
197 * @param string $hcard_url Link to the hcard - is returned by reference
199 * @return string profile link
200 * @throws HTTPException\InternalServerErrorException
202 public static function webfingerDfrn($webbie, &$hcard_url)
206 $links = self::lrdd($webbie);
207 Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA);
208 if (!empty($links) && is_array($links)) {
209 foreach ($links as $link) {
210 if ($link['@attributes']['rel'] === ActivityNamespace::DFRN) {
211 $profile_link = $link['@attributes']['href'];
213 if (($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) && ($profile_link == "")) {
214 $profile_link = 'stat:'.$link['@attributes']['template'];
216 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
217 $hcard_url = $link['@attributes']['href'];
221 return $profile_link;
225 * @brief Check an URI for LRDD data
227 * this is a replacement for the "lrdd" function.
228 * It isn't used in this class and has some redundancies in the code.
229 * When time comes we can check the existing calls for "lrdd" if we can rework them.
231 * @param string $uri Address that should be probed
233 * @return array uri data
234 * @throws HTTPException\InternalServerErrorException
236 public static function lrdd($uri)
238 $lrdd = self::hostMeta($uri);
241 if (is_bool($lrdd)) {
246 $parts = @parse_url($uri);
247 if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
251 $host = $parts["host"];
252 if (!empty($parts["port"])) {
253 $host .= ':'.$parts["port"];
256 $path_parts = explode("/", trim($parts["path"], "/"));
258 $nick = array_pop($path_parts);
261 $lrdd = self::hostMeta($host);
262 $host .= "/".array_shift($path_parts);
263 } while (!$lrdd && (sizeof($path_parts) > 0));
267 Logger::log("No lrdd data found for ".$uri, Logger::DEBUG);
271 foreach ($lrdd as $type => $template) {
276 $path = str_replace('{uri}', urlencode($uri), $template);
277 $webfinger = self::webfinger($path, $type);
279 if (!$webfinger && (strstr($uri, "@"))) {
280 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
281 $webfinger = self::webfinger($path, $type);
284 // Special treatment for Mastodon
285 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
286 // But the webfinger for this format fails.
287 if (!$webfinger && !empty($nick)) {
288 // Mastodon uses a "@" as prefix for usernames in their url format
289 $nick = ltrim($nick, '@');
291 $addr = $nick."@".$host;
293 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
294 $webfinger = self::webfinger($path, $type);
298 if (!is_array($webfinger["links"])) {
299 Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
305 foreach ($webfinger["links"] as $link) {
306 $data[] = ["@attributes" => $link];
309 if (is_array($webfinger["aliases"])) {
310 foreach ($webfinger["aliases"] as $alias) {
311 $data[] = ["@attributes" =>
321 * @brief Fetch information (protocol endpoints and user information) about a given uri
323 * @param string $uri Address that should be probed
324 * @param string $network Test for this specific network
325 * @param integer $uid User ID for the probe (only used for mails)
326 * @param boolean $cache Use cached values?
328 * @return array uri data
329 * @throws HTTPException\InternalServerErrorException
330 * @throws \ImagickException
332 public static function uri($uri, $network = '', $uid = -1, $cache = true)
335 $result = Cache::get('Probe::uri:' . $network . ':' . $uri);
336 if (!is_null($result)) {
345 self::$istimeout = false;
347 if ($network != Protocol::ACTIVITYPUB) {
348 $data = self::detect($uri, $network, $uid);
353 // When the previous detection process had got a time out
354 // we could falsely detect a Friendica profile as AP profile.
355 if (!self::$istimeout) {
356 $ap_profile = ActivityPub::probeProfile($uri);
358 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
360 } elseif (!empty($ap_profile)) {
361 $ap_profile['batch'] = '';
362 $data = array_merge($ap_profile, $data);
365 Logger::notice('Time out detected. AP will not be probed.', ['uri' => $uri]);
368 if (!isset($data['url'])) {
372 if (!empty($data['photo']) && !empty($data['baseurl'])) {
373 $data['baseurl'] = Network::getUrlMatch(Strings::normaliseLink($data['baseurl']), Strings::normaliseLink($data['photo']));
374 } elseif (empty($data['photo'])) {
375 $data['photo'] = DI::baseUrl() . '/images/person-300.jpg';
378 if (empty($data['name'])) {
379 if (!empty($data['nick'])) {
380 $data['name'] = $data['nick'];
383 if (empty($data['name'])) {
384 $data['name'] = $data['url'];
388 if (empty($data['nick'])) {
389 $data['nick'] = strtolower($data['name']);
391 if (strpos($data['nick'], ' ')) {
392 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
396 if (!empty(self::$baseurl)) {
397 $data['baseurl'] = self::$baseurl;
400 if (empty($data['network'])) {
401 $data['network'] = Protocol::PHANTOM;
404 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
405 $data['hide'] = self::getHideStatus($data['url']);
408 $data = self::rearrangeData($data);
410 // Only store into the cache if the value seems to be valid
411 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
412 DI::cache()->set('Probe::uri:' . $network . ':' . $uri, $data, Cache::DAY);
420 * Fetches the "hide" status from the profile
422 * @param string $url URL of the profile
424 * @return boolean "hide" status
426 private static function getHideStatus($url)
428 $curlResult = Network::curl($url);
429 if (!$curlResult->isSuccess()) {
433 // If the file is too large then exit
434 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
438 // If it isn't a HTML file then exit
439 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
443 $body = $curlResult->getBody();
445 $doc = new DOMDocument();
446 @$doc->loadHTML($body);
448 $xpath = new DOMXPath($doc);
450 $list = $xpath->query('//meta[@name]');
451 foreach ($list as $node) {
453 if ($node->attributes->length) {
454 foreach ($node->attributes as $attribute) {
455 $meta_tag[$attribute->name] = $attribute->value;
459 if (empty($meta_tag['content'])) {
463 $content = strtolower(trim($meta_tag['content']));
465 switch (strtolower(trim($meta_tag['name']))) {
466 case 'dfrn-global-visibility':
467 if ($content == 'false') {
472 if (strpos($content, 'noindex') !== false) {
483 * @brief Checks if a profile url should be OStatus but only provides partial information
485 * @param array $webfinger Webfinger data
486 * @param string $lrdd Path template for webfinger request
487 * @param string $type type
489 * @return array fixed webfinger data
490 * @throws HTTPException\InternalServerErrorException
492 private static function fixOStatus($webfinger, $lrdd, $type)
494 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
501 foreach ($webfinger['links'] as $link) {
502 if ($link['rel'] == ActivityNamespace::OSTATUSSUB) {
505 if ($link['rel'] == 'magic-public-key') {
510 if (!$is_ostatus || $has_key) {
514 $url = Network::switchScheme($webfinger['subject']);
515 $path = str_replace('{uri}', urlencode($url), $lrdd);
516 $webfinger2 = self::webfinger($path, $type);
518 // Is the new webfinger detectable as OStatus?
519 if (self::ostatus($webfinger2, true)) {
520 $webfinger = $webfinger2;
527 * @brief Fetch information (protocol endpoints and user information) about a given uri
529 * This function is only called by the "uri" function that adds caching and rearranging of data.
531 * @param string $uri Address that should be probed
532 * @param string $network Test for this specific network
533 * @param integer $uid User ID for the probe (only used for mails)
535 * @return array uri data
536 * @throws HTTPException\InternalServerErrorException
538 private static function detect($uri, $network, $uid)
540 $parts = parse_url($uri);
542 if (!empty($parts["scheme"]) && !empty($parts["host"])) {
543 $host = $parts["host"];
544 if (!empty($parts["port"])) {
545 $host .= ':'.$parts["port"];
548 if ($host == 'twitter.com') {
549 return self::twitter($uri);
551 $lrdd = self::hostMeta($host);
553 if (is_bool($lrdd)) {
557 $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
559 while (!$lrdd && (sizeof($path_parts) > 1)) {
560 $host .= "/".array_shift($path_parts);
561 $lrdd = self::hostMeta($host);
564 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
565 return self::feed($uri);
567 $nick = array_pop($path_parts);
569 // Mastodon uses a "@" as prefix for usernames in their url format
570 $nick = ltrim($nick, '@');
572 $addr = $nick."@".$host;
573 } elseif (strstr($uri, '@')) {
574 // If the URI starts with "mailto:" then jump directly to the mail detection
575 if (strpos($uri, 'mailto:') !== false) {
576 $uri = str_replace('mailto:', '', $uri);
577 return self::mail($uri, $uid);
580 if ($network == Protocol::MAIL) {
581 return self::mail($uri, $uid);
583 // Remove "acct:" from the URI
584 $uri = str_replace('acct:', '', $uri);
586 $host = substr($uri, strpos($uri, '@') + 1);
587 $nick = substr($uri, 0, strpos($uri, '@'));
589 if (strpos($uri, '@twitter.com')) {
590 return self::twitter($uri);
592 $lrdd = self::hostMeta($host);
594 if (is_bool($lrdd)) {
599 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
600 return self::mail($uri, $uid);
604 Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
610 /// @todo Do we need the prefix "acct:" or "acct://"?
612 foreach ($lrdd as $type => $template) {
617 // At first try it with the given uri
618 $path = str_replace('{uri}', urlencode($uri), $template);
619 $webfinger = self::webfinger($path, $type);
621 // Fix possible problems with GNU Social probing to wrong scheme
622 $webfinger = self::fixOStatus($webfinger, $template, $type);
624 // We cannot be sure that the detected address was correct, so we don't use the values
625 if ($webfinger && ($uri != $addr)) {
630 // Try webfinger with the address (user@domain.tld)
632 $path = str_replace('{uri}', urlencode($addr), $template);
633 $webfinger = self::webfinger($path, $type);
636 // Mastodon needs to have it with "acct:"
638 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
639 $webfinger = self::webfinger($path, $type);
644 return self::feed($uri);
649 Logger::log("Probing ".$uri, Logger::DEBUG);
651 if (in_array($network, ["", Protocol::DFRN])) {
652 $result = self::dfrn($webfinger);
654 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
655 $result = self::diaspora($webfinger);
657 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
658 $result = self::ostatus($webfinger);
660 if (in_array($network, ['', Protocol::ZOT])) {
661 $result = self::zot($webfinger, $result);
663 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
664 $result = self::pumpio($webfinger, $addr);
666 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
667 $result = self::feed($uri);
669 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
670 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
671 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
672 $result["nick"] = $nick;
675 if (empty($result["addr"]) && ($addr != "")) {
676 $result["addr"] = $addr;
680 if (empty($result["network"])) {
681 $result["network"] = Protocol::PHANTOM;
684 if (empty($result["url"])) {
685 $result["url"] = $uri;
688 Logger::log($uri." is ".$result["network"], Logger::DEBUG);
690 if (empty($result["baseurl"]) && ($result["network"] != Protocol::PHANTOM)) {
691 $pos = strpos($result["url"], $host);
693 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
700 * Check for Zot contact
702 * @param array $webfinger Webfinger data
703 * @param array $data previously probed data
705 * @return array Zot data
706 * @throws HTTPException\InternalServerErrorException
708 private static function zot($webfinger, $data)
710 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
711 foreach ($webfinger["aliases"] as $alias) {
712 if (substr($alias, 0, 5) == 'acct:') {
713 $data["addr"] = substr($alias, 5);
718 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
719 $data["addr"] = substr($webfinger["subject"], 5);
723 foreach ($webfinger['links'] as $link) {
724 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
725 $zot_url = $link['href'];
729 if (empty($zot_url) && !empty($data['addr']) && !empty(self::$baseurl)) {
730 $condition = ['nurl' => Strings::normaliseLink(self::$baseurl), 'platform' => ['hubzilla']];
731 if (!DBA::exists('gserver', $condition)) {
734 $zot_url = self::$baseurl . '/.well-known/zot-info?address=' . $data['addr'];
737 if (empty($zot_url)) {
741 $data = self::pollZot($zot_url, $data);
743 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
744 foreach ($webfinger['aliases'] as $alias) {
745 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
746 $data['alias'] = $alias;
754 public static function pollZot($url, $data)
756 $curlResult = Network::curl($url);
757 if ($curlResult->isTimeout()) {
760 $content = $curlResult->getBody();
765 $json = json_decode($content, true);
766 if (!is_array($json)) {
770 if (empty($data['network'])) {
771 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
772 $data['network'] = Protocol::ZOT;
773 } elseif (!isset($json['protocols'])) {
774 $data['network'] = Protocol::ZOT;
778 if (!empty($json['guid']) && empty($data['guid'])) {
779 $data['guid'] = $json['guid'];
781 if (!empty($json['key']) && empty($data['pubkey'])) {
782 $data['pubkey'] = $json['key'];
784 if (!empty($json['name'])) {
785 $data['name'] = $json['name'];
787 if (!empty($json['photo'])) {
788 $data['photo'] = $json['photo'];
789 if (!empty($json['photo_updated'])) {
790 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
793 if (!empty($json['address'])) {
794 $data['addr'] = $json['address'];
796 if (!empty($json['url'])) {
797 $data['url'] = $json['url'];
799 if (!empty($json['connections_url'])) {
800 $data['poco'] = $json['connections_url'];
802 if (isset($json['searchable'])) {
803 $data['hide'] = !$json['searchable'];
805 if (!empty($json['public_forum'])) {
806 $data['community'] = $json['public_forum'];
807 $data['account-type'] = Contact::PAGE_COMMUNITY;
810 if (!empty($json['profile'])) {
811 $profile = $json['profile'];
812 if (!empty($profile['description'])) {
813 $data['about'] = $profile['description'];
815 if (!empty($profile['gender'])) {
816 $data['gender'] = $profile['gender'];
818 if (!empty($profile['keywords'])) {
819 $keywords = implode(', ', $profile['keywords']);
820 if (!empty($keywords)) {
821 $data['keywords'] = $keywords;
826 if (!empty($profile['region'])) {
827 $loc['region'] = $profile['region'];
829 if (!empty($profile['country'])) {
830 $loc['country-name'] = $profile['country'];
832 if (!empty($profile['hometown'])) {
833 $loc['locality'] = $profile['hometown'];
835 $location = Profile::formatLocation($loc);
836 if (!empty($location)) {
837 $data['location'] = $location;
845 * @brief Perform a webfinger request.
847 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
849 * @param string $url Address that should be probed
850 * @param string $type type
852 * @return array webfinger data
853 * @throws HTTPException\InternalServerErrorException
855 private static function webfinger($url, $type)
857 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
859 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
860 if ($curlResult->isTimeout()) {
861 self::$istimeout = true;
864 $data = $curlResult->getBody();
866 $webfinger = json_decode($data, true);
867 if (is_array($webfinger)) {
868 if (!isset($webfinger["links"])) {
869 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
875 // If it is not JSON, maybe it is XML
876 $xrd = XML::parseString($data, false);
877 if (!is_object($xrd)) {
878 Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
882 $xrd_arr = XML::elementToArray($xrd);
883 if (!isset($xrd_arr["xrd"]["link"])) {
884 Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
890 if (!empty($xrd_arr["xrd"]["subject"])) {
891 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
894 if (!empty($xrd_arr["xrd"]["alias"])) {
895 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
898 $webfinger["links"] = [];
900 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
901 if (!empty($data["@attributes"])) {
902 $attributes = $data["@attributes"];
903 } elseif ($value == "@attributes") {
909 $webfinger["links"][] = $attributes;
915 * @brief Poll the Friendica specific noscrape page.
917 * "noscrape" is a faster alternative to fetch the data from the hcard.
918 * This functionality was originally created for the directory.
920 * @param string $noscrape_url Link to the noscrape page
921 * @param array $data The already fetched data
923 * @return array noscrape data
924 * @throws HTTPException\InternalServerErrorException
926 private static function pollNoscrape($noscrape_url, $data)
928 $curlResult = Network::curl($noscrape_url);
929 if ($curlResult->isTimeout()) {
930 self::$istimeout = true;
933 $content = $curlResult->getBody();
935 Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
939 $json = json_decode($content, true);
940 if (!is_array($json)) {
941 Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
945 if (!empty($json["fn"])) {
946 $data["name"] = $json["fn"];
949 if (!empty($json["addr"])) {
950 $data["addr"] = $json["addr"];
953 if (!empty($json["nick"])) {
954 $data["nick"] = $json["nick"];
957 if (!empty($json["guid"])) {
958 $data["guid"] = $json["guid"];
961 if (!empty($json["comm"])) {
962 $data["community"] = $json["comm"];
965 if (!empty($json["tags"])) {
966 $keywords = implode(", ", $json["tags"]);
967 if ($keywords != "") {
968 $data["keywords"] = $keywords;
972 $location = Profile::formatLocation($json);
974 $data["location"] = $location;
977 if (!empty($json["about"])) {
978 $data["about"] = $json["about"];
981 if (!empty($json["gender"])) {
982 $data["gender"] = $json["gender"];
985 if (!empty($json["key"])) {
986 $data["pubkey"] = $json["key"];
989 if (!empty($json["photo"])) {
990 $data["photo"] = $json["photo"];
993 if (!empty($json["dfrn-request"])) {
994 $data["request"] = $json["dfrn-request"];
997 if (!empty($json["dfrn-confirm"])) {
998 $data["confirm"] = $json["dfrn-confirm"];
1001 if (!empty($json["dfrn-notify"])) {
1002 $data["notify"] = $json["dfrn-notify"];
1005 if (!empty($json["dfrn-poll"])) {
1006 $data["poll"] = $json["dfrn-poll"];
1009 if (isset($json["hide"])) {
1010 $data["hide"] = (bool)$json["hide"];
1012 $data["hide"] = false;
1019 * @brief Check for valid DFRN data
1021 * @param array $data DFRN data
1023 * @return int Number of errors
1025 public static function validDfrn($data)
1028 if (!isset($data['key'])) {
1031 if (!isset($data['dfrn-request'])) {
1034 if (!isset($data['dfrn-confirm'])) {
1037 if (!isset($data['dfrn-notify'])) {
1040 if (!isset($data['dfrn-poll'])) {
1047 * @brief Fetch data from a DFRN profile page and via "noscrape"
1049 * @param string $profile_link Link to the profile page
1051 * @return array profile data
1052 * @throws HTTPException\InternalServerErrorException
1053 * @throws \ImagickException
1055 public static function profile($profile_link)
1059 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
1061 // Fetch data via noscrape - this is faster
1062 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1063 $data = self::pollNoscrape($noscrape_url, $data);
1065 if (!isset($data["notify"])
1066 || !isset($data["confirm"])
1067 || !isset($data["request"])
1068 || !isset($data["poll"])
1069 || !isset($data["name"])
1070 || !isset($data["photo"])
1072 $data = self::pollHcard($profile_link, $data, true);
1077 if (empty($data["addr"]) || empty($data["nick"])) {
1078 $probe_data = self::uri($profile_link);
1079 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1080 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1083 $prof_data["addr"] = $data["addr"];
1084 $prof_data["nick"] = $data["nick"];
1085 $prof_data["dfrn-request"] = $data['request'] ?? null;
1086 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1087 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1088 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1089 $prof_data["photo"] = $data['photo'] ?? null;
1090 $prof_data["fn"] = $data['name'] ?? null;
1091 $prof_data["key"] = $data['pubkey'] ?? null;
1093 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
1099 * @brief Check for DFRN contact
1101 * @param array $webfinger Webfinger data
1103 * @return array DFRN data
1104 * @throws HTTPException\InternalServerErrorException
1106 private static function dfrn($webfinger)
1110 // The array is reversed to take into account the order of preference for same-rel links
1111 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1112 foreach (array_reverse($webfinger["links"]) as $link) {
1113 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1114 $data["network"] = Protocol::DFRN;
1115 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1116 $data["poll"] = $link["href"];
1117 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1118 $data["url"] = $link["href"];
1119 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1120 $hcard_url = $link["href"];
1121 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1122 $data["poco"] = $link["href"];
1123 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1124 $data["photo"] = $link["href"];
1125 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1126 $data["baseurl"] = trim($link["href"], '/');
1127 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1128 $data["guid"] = $link["href"];
1129 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1130 $data["pubkey"] = base64_decode($link["href"]);
1132 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1133 if (strstr($data["pubkey"], 'RSA ')) {
1134 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1139 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1140 foreach ($webfinger["aliases"] as $alias) {
1141 if (empty($data["url"]) && !strstr($alias, "@")) {
1142 $data["url"] = $alias;
1143 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1144 $data["alias"] = $alias;
1145 } elseif (substr($alias, 0, 5) == 'acct:') {
1146 $data["addr"] = substr($alias, 5);
1151 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1152 $data["addr"] = substr($webfinger["subject"], 5);
1155 if (!isset($data["network"]) || ($hcard_url == "")) {
1159 // Fetch data via noscrape - this is faster
1160 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1161 $data = self::pollNoscrape($noscrape_url, $data);
1163 if (isset($data["notify"])
1164 && isset($data["confirm"])
1165 && isset($data["request"])
1166 && isset($data["poll"])
1167 && isset($data["name"])
1168 && isset($data["photo"])
1173 $data = self::pollHcard($hcard_url, $data, true);
1179 * @brief Poll the hcard page (Diaspora and Friendica specific)
1181 * @param string $hcard_url Link to the hcard page
1182 * @param array $data The already fetched data
1183 * @param boolean $dfrn Poll DFRN specific data
1185 * @return array hcard data
1186 * @throws HTTPException\InternalServerErrorException
1188 private static function pollHcard($hcard_url, $data, $dfrn = false)
1190 $curlResult = Network::curl($hcard_url);
1191 if ($curlResult->isTimeout()) {
1192 self::$istimeout = true;
1195 $content = $curlResult->getBody();
1200 $doc = new DOMDocument();
1201 if (!@$doc->loadHTML($content)) {
1205 $xpath = new DomXPath($doc);
1207 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1208 if (!is_object($vcards)) {
1212 if (!isset($data["baseurl"])) {
1213 $data["baseurl"] = "";
1216 if ($vcards->length > 0) {
1217 $vcard = $vcards->item(0);
1219 // We have to discard the guid from the hcard in favour of the guid from lrdd
1220 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1221 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1222 if (($search->length > 0) && empty($data["guid"])) {
1223 $data["guid"] = $search->item(0)->nodeValue;
1226 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1227 if ($search->length > 0) {
1228 $data["nick"] = $search->item(0)->nodeValue;
1231 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1232 if ($search->length > 0) {
1233 $data["name"] = $search->item(0)->nodeValue;
1236 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1237 if ($search->length > 0) {
1238 $data["searchable"] = $search->item(0)->nodeValue;
1241 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1242 if ($search->length > 0) {
1243 $data["pubkey"] = $search->item(0)->nodeValue;
1244 if (strstr($data["pubkey"], 'RSA ')) {
1245 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1249 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1250 if ($search->length > 0) {
1251 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1256 if (!empty($vcard)) {
1257 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1258 foreach ($photos as $photo) {
1260 foreach ($photo->attributes as $attribute) {
1261 $attr[$attribute->name] = trim($attribute->value);
1264 if (isset($attr["src"]) && isset($attr["width"])) {
1265 $avatar[$attr["width"]] = $attr["src"];
1268 // We don't have a width. So we just take everything that we got.
1269 // This is a Hubzilla workaround which doesn't send a width.
1270 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1271 $avatar[] = $attr["src"];
1276 if (sizeof($avatar)) {
1278 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1282 // Poll DFRN specific data
1283 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1284 if ($search->length > 0) {
1285 foreach ($search as $link) {
1286 //$data["request"] = $search->item(0)->nodeValue;
1288 foreach ($link->attributes as $attribute) {
1289 $attr[$attribute->name] = trim($attribute->value);
1292 $data[substr($attr["rel"], 5)] = $attr["href"];
1296 // Older Friendica versions had used the "uid" field differently than newer versions
1297 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1298 unset($data["guid"]);
1307 * @brief Check for Diaspora contact
1309 * @param array $webfinger Webfinger data
1311 * @return array Diaspora data
1312 * @throws HTTPException\InternalServerErrorException
1314 private static function diaspora($webfinger)
1319 // The array is reversed to take into account the order of preference for same-rel links
1320 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1321 foreach (array_reverse($webfinger["links"]) as $link) {
1322 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1323 $hcard_url = $link["href"];
1324 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1325 $data["baseurl"] = trim($link["href"], '/');
1326 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1327 $data["guid"] = $link["href"];
1328 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1329 $data["url"] = $link["href"];
1330 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1331 $data["poll"] = $link["href"];
1332 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1333 $data["poco"] = $link["href"];
1334 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1335 $data["notify"] = $link["href"];
1336 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1337 $data["pubkey"] = base64_decode($link["href"]);
1339 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1340 if (strstr($data["pubkey"], 'RSA ')) {
1341 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1346 if (empty($data["url"]) || empty($hcard_url)) {
1350 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1351 foreach ($webfinger["aliases"] as $alias) {
1352 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1353 $data["alias"] = $alias;
1354 } elseif (substr($alias, 0, 5) == 'acct:') {
1355 $data["addr"] = substr($alias, 5);
1360 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1361 $data["addr"] = substr($webfinger["subject"], 5);
1364 // Fetch further information from the hcard
1365 $data = self::pollHcard($hcard_url, $data);
1371 if (!empty($data["url"])
1372 && !empty($data["guid"])
1373 && !empty($data["baseurl"])
1374 && !empty($data["pubkey"])
1375 && !empty($hcard_url)
1377 $data["network"] = Protocol::DIASPORA;
1379 // The Diaspora handle must always be lowercase
1380 if (!empty($data["addr"])) {
1381 $data["addr"] = strtolower($data["addr"]);
1384 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1385 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1386 $data["batch"] = $data["baseurl"] . "/receive/public";
1395 * @brief Check for OStatus contact
1397 * @param array $webfinger Webfinger data
1398 * @param bool $short Short detection mode
1400 * @return array|bool OStatus data or "false" on error or "true" on short mode
1401 * @throws HTTPException\InternalServerErrorException
1403 private static function ostatus($webfinger, $short = false)
1407 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1408 foreach ($webfinger["aliases"] as $alias) {
1409 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1410 $data["addr"] = str_replace('acct:', '', $alias);
1415 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1416 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1418 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1421 if (is_array($webfinger["links"])) {
1422 // The array is reversed to take into account the order of preference for same-rel links
1423 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1424 foreach (array_reverse($webfinger["links"]) as $link) {
1425 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1426 && (($link["type"] ?? "") == "text/html")
1427 && ($link["href"] != "")
1429 $data["url"] = $link["href"];
1430 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1431 $data["notify"] = $link["href"];
1432 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1433 $data["poll"] = $link["href"];
1434 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1435 $pubkey = $link["href"];
1437 if (substr($pubkey, 0, 5) === 'data:') {
1438 if (strstr($pubkey, ',')) {
1439 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1441 $pubkey = substr($pubkey, 5);
1443 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1444 $curlResult = Network::curl($pubkey);
1445 if ($curlResult->isTimeout()) {
1446 self::$istimeout = true;
1449 $pubkey = $curlResult->getBody();
1452 $key = explode(".", $pubkey);
1454 if (sizeof($key) >= 3) {
1455 $m = Strings::base64UrlDecode($key[1]);
1456 $e = Strings::base64UrlDecode($key[2]);
1457 $data["pubkey"] = Crypto::meToPem($m, $e);
1463 if (isset($data["notify"]) && isset($data["pubkey"])
1464 && isset($data["poll"])
1465 && isset($data["url"])
1467 $data["network"] = Protocol::OSTATUS;
1476 // Fetch all additional data from the feed
1477 $curlResult = Network::curl($data["poll"]);
1478 if ($curlResult->isTimeout()) {
1479 self::$istimeout = true;
1482 $feed = $curlResult->getBody();
1483 $feed_data = Feed::import($feed);
1488 if (!empty($feed_data["header"]["author-name"])) {
1489 $data["name"] = $feed_data["header"]["author-name"];
1491 if (!empty($feed_data["header"]["author-nick"])) {
1492 $data["nick"] = $feed_data["header"]["author-nick"];
1494 if (!empty($feed_data["header"]["author-avatar"])) {
1495 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1497 if (!empty($feed_data["header"]["author-id"])) {
1498 $data["alias"] = $feed_data["header"]["author-id"];
1500 if (!empty($feed_data["header"]["author-location"])) {
1501 $data["location"] = $feed_data["header"]["author-location"];
1503 if (!empty($feed_data["header"]["author-about"])) {
1504 $data["about"] = $feed_data["header"]["author-about"];
1506 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1507 // So we take the value that we just fetched, although the other one worked as well
1508 if (!empty($feed_data["header"]["author-link"])) {
1509 $data["url"] = $feed_data["header"]["author-link"];
1512 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1513 $data['url'] = $data["alias"];
1514 $data["alias"] = '';
1517 /// @todo Fetch location and "about" from the feed as well
1522 * @brief Fetch data from a pump.io profile page
1524 * @param string $profile_link Link to the profile page
1526 * @return array profile data
1528 private static function pumpioProfileData($profile_link)
1530 $curlResult = Network::curl($profile_link);
1531 if (!$curlResult->isSuccess()) {
1535 $doc = new DOMDocument();
1536 if (!@$doc->loadHTML($curlResult->getBody())) {
1540 $xpath = new DomXPath($doc);
1544 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1546 if ($data["name"] == '') {
1547 // This is ugly - but pump.io doesn't seem to know a better way for it
1548 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1549 $pos = strpos($data["name"], chr(10));
1551 $data["name"] = trim(substr($data["name"], 0, $pos));
1555 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1557 if ($data["location"] == '') {
1558 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1561 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1563 if ($data["about"] == '') {
1564 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1567 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1569 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1572 foreach ($avatar->attributes as $attribute) {
1573 if ($attribute->name == "src") {
1574 $data["photo"] = trim($attribute->value);
1583 * @brief Check for pump.io contact
1585 * @param array $webfinger Webfinger data
1586 * @param string $addr
1587 * @return array pump.io data
1589 private static function pumpio($webfinger, $addr)
1592 // The array is reversed to take into account the order of preference for same-rel links
1593 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1594 foreach (array_reverse($webfinger["links"]) as $link) {
1595 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1596 && (($link["type"] ?? "") == "text/html")
1597 && ($link["href"] != "")
1599 $data["url"] = $link["href"];
1600 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1601 $data["notify"] = $link["href"];
1602 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1603 $data["poll"] = $link["href"];
1604 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1605 $data["dialback"] = $link["href"];
1608 if (isset($data["poll"]) && isset($data["notify"])
1609 && isset($data["dialback"])
1610 && isset($data["url"])
1612 // by now we use these fields only for the network type detection
1613 // So we unset all data that isn't used at the moment
1614 unset($data["dialback"]);
1616 $data["network"] = Protocol::PUMPIO;
1621 $profile_data = self::pumpioProfileData($data["url"]);
1623 if (!$profile_data) {
1627 $data = array_merge($data, $profile_data);
1629 if (($addr != '') && ($data['name'] != '')) {
1630 $name = trim(str_replace($addr, '', $data['name']));
1632 $data['name'] = $name;
1640 * @brief Check for twitter contact
1642 * @param string $uri
1644 * @return array twitter data
1646 private static function twitter($uri)
1648 if (preg_match('=(.*)@twitter.com=i', $uri, $matches)) {
1649 $nick = $matches[1];
1650 } elseif (preg_match('=https?://twitter.com/(.*)=i', $uri, $matches)) {
1651 $nick = $matches[1];
1657 $data['url'] = 'https://twitter.com/' . $nick;
1658 $data['addr'] = $nick . '@twitter.com';
1659 $data['nick'] = $data['name'] = $nick;
1660 $data['network'] = Protocol::TWITTER;
1661 $data['baseurl'] = 'https://twitter.com';
1663 $curlResult = Network::curl($data['url'], false);
1664 if (!$curlResult->isSuccess()) {
1668 $body = $curlResult->getBody();
1669 $doc = new DOMDocument();
1670 @$doc->loadHTML($body);
1671 $xpath = new DOMXPath($doc);
1673 $list = $xpath->query('//img[@class]');
1674 foreach ($list as $node) {
1676 if ($node->attributes->length) {
1677 foreach ($node->attributes as $attribute) {
1678 $img_attr[$attribute->name] = $attribute->value;
1682 if (empty($img_attr['class'])) {
1686 if (strpos($img_attr['class'], 'ProfileAvatar-image') !== false) {
1687 if (!empty($img_attr['src'])) {
1688 $data['photo'] = $img_attr['src'];
1690 if (!empty($img_attr['alt'])) {
1691 $data['name'] = $img_attr['alt'];
1700 * @brief Check page for feed link
1702 * @param string $url Page link
1704 * @return string feed link
1706 private static function getFeedLink($url)
1708 $curlResult = Network::curl($url);
1709 if (!$curlResult->isSuccess()) {
1713 $doc = new DOMDocument();
1714 if (!@$doc->loadHTML($curlResult->getBody())) {
1718 $xpath = new DomXPath($doc);
1720 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1721 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1722 if (!is_object($feeds)) {
1726 if ($feeds->length == 0) {
1732 foreach ($feeds as $feed) {
1734 foreach ($feed->attributes as $attribute) {
1735 $attr[$attribute->name] = trim($attribute->value);
1738 if (empty($feed_url) && !empty($attr['href'])) {
1739 $feed_url = $attr["href"];
1747 * @brief Check for feed contact
1749 * @param string $url Profile link
1750 * @param boolean $probe Do a probe if the page contains a feed link
1752 * @return array feed data
1753 * @throws HTTPException\InternalServerErrorException
1755 private static function feed($url, $probe = true)
1757 $curlResult = Network::curl($url);
1758 if ($curlResult->isTimeout()) {
1759 self::$istimeout = true;
1762 $feed = $curlResult->getBody();
1763 $feed_data = Feed::import($feed);
1770 $feed_url = self::getFeedLink($url);
1776 return self::feed($feed_url, false);
1779 if (!empty($feed_data["header"]["author-name"])) {
1780 $data["name"] = $feed_data["header"]["author-name"];
1783 if (!empty($feed_data["header"]["author-nick"])) {
1784 $data["nick"] = $feed_data["header"]["author-nick"];
1787 if (!empty($feed_data["header"]["author-avatar"])) {
1788 $data["photo"] = $feed_data["header"]["author-avatar"];
1791 if (!empty($feed_data["header"]["author-id"])) {
1792 $data["alias"] = $feed_data["header"]["author-id"];
1795 $data["url"] = $url;
1796 $data["poll"] = $url;
1798 if (!empty($feed_data["header"]["author-link"])) {
1799 $data["baseurl"] = $feed_data["header"]["author-link"];
1801 $data["baseurl"] = $data["url"];
1804 $data["network"] = Protocol::FEED;
1810 * @brief Check for mail contact
1812 * @param string $uri Profile link
1813 * @param integer $uid User ID
1815 * @return array mail data
1816 * @throws \Exception
1818 private static function mail($uri, $uid)
1820 if (!Network::isEmailDomainValid($uri)) {
1828 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1830 $condition = ["`uid` = ? AND `server` != ''", $uid];
1831 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1832 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1834 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1838 $mailbox = Email::constructMailboxName($mailacct);
1840 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1841 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1846 $msgs = Email::poll($mbox, $uri);
1847 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1849 if (!count($msgs)) {
1853 $phost = substr($uri, strpos($uri, '@') + 1);
1856 $data["addr"] = $uri;
1857 $data["network"] = Protocol::MAIL;
1858 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1859 $data["nick"] = $data["name"];
1860 $data["photo"] = Network::lookupAvatarByEmail($uri);
1861 $data["url"] = 'mailto:'.$uri;
1862 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1863 $data["poll"] = 'email ' . Strings::getRandomHex();
1865 $x = Email::messageMeta($mbox, $msgs[0]);
1866 if (stristr($x[0]->from, $uri)) {
1867 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1868 } elseif (stristr($x[0]->to, $uri)) {
1869 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1872 foreach ($adr as $feadr) {
1873 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1874 &&(strcasecmp($feadr->host, $phost) == 0)
1875 && (strlen($feadr->personal))
1877 $personal = imap_mime_header_decode($feadr->personal);
1879 foreach ($personal as $perspart) {
1880 if ($perspart->charset != "default") {
1881 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1883 $data["name"] .= $perspart->text;
1887 $data["name"] = Strings::escapeTags($data["name"]);
1891 if (!empty($mbox)) {
1898 * @brief Mix two paths together to possibly fix missing parts
1900 * @param string $avatar Path to the avatar
1901 * @param string $base Another path that is hopefully complete
1903 * @return string fixed avatar path
1904 * @throws \Exception
1906 public static function fixAvatar($avatar, $base)
1908 $base_parts = parse_url($base);
1910 // Remove all parts that could create a problem
1911 unset($base_parts['path']);
1912 unset($base_parts['query']);
1913 unset($base_parts['fragment']);
1915 $avatar_parts = parse_url($avatar);
1918 $parts = array_merge($base_parts, $avatar_parts);
1920 // And put them together again
1921 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1922 $host = isset($parts['host']) ? $parts['host'] : '';
1923 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1924 $path = isset($parts['path']) ? $parts['path'] : '';
1925 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1926 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1928 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1930 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);