3 * @file src/Network/Probe.php
5 namespace Friendica\Network;
8 * @file src/Network/Probe.php
9 * Functions for probing URL
14 use Friendica\Core\Cache\Duration;
15 use Friendica\Core\Logger;
16 use Friendica\Core\Protocol;
17 use Friendica\Database\DBA;
19 use Friendica\Model\Contact;
20 use Friendica\Model\Profile;
21 use Friendica\Protocol\ActivityNamespace;
22 use Friendica\Protocol\ActivityPub;
23 use Friendica\Protocol\Email;
24 use Friendica\Protocol\Feed;
25 use Friendica\Util\Crypto;
26 use Friendica\Util\Network;
27 use Friendica\Util\Strings;
28 use Friendica\Util\XML;
31 * This class contain functions for probing URL
36 private static $baseurl;
37 private static $istimeout;
40 * Rearrange the array so that it always has the same order
42 * @param array $data Unordered data
44 * @return array Ordered data
46 private static function rearrangeData($data)
48 $fields = ["name", "nick", "guid", "url", "addr", "alias", "photo", "account-type",
49 "community", "keywords", "location", "about", "gender", "hide",
50 "batch", "notify", "poll", "request", "confirm", "poco",
51 "following", "followers", "inbox", "outbox", "sharedinbox",
52 "priority", "network", "pubkey", "baseurl"];
55 foreach ($fields as $field) {
56 if (isset($data[$field])) {
57 $newdata[$field] = $data[$field];
59 $newdata[$field] = "";
63 // We don't use the "priority" field anymore and replace it with a dummy.
64 $newdata["priority"] = 0;
70 * Check if the hostname belongs to the own server
72 * @param string $host The hostname that is to be checked
74 * @return bool Does the testes hostname belongs to the own server?
76 private static function ownHost($host)
78 $own_host = DI::baseUrl()->getHostname();
80 $parts = parse_url($host);
82 if (!isset($parts['scheme'])) {
83 $parts = parse_url('http://'.$host);
86 if (!isset($parts['host'])) {
89 return $parts['host'] == $own_host;
93 * Probes for webfinger path via "host-meta"
95 * We have to check if the servers in the future still will offer this.
96 * It seems as if it was dropped from the standard.
98 * @param string $host The host part of an url
100 * @return array with template and type of the webfinger template for JSON or XML
101 * @throws HTTPException\InternalServerErrorException
103 private static function hostMeta($host)
105 // Reset the static variable
108 $ssl_url = "https://".$host."/.well-known/host-meta";
109 $url = "http://".$host."/.well-known/host-meta";
111 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
113 Logger::log("Probing for ".$host, Logger::DEBUG);
116 $curlResult = Network::curl($ssl_url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
117 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
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 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
131 if ($curlResult->isTimeout()) {
132 Logger::info('Probing timeout', ['url' => $url], Logger::DEBUG);
133 self::$istimeout = true;
135 } elseif ($connection_error && $ssl_connection_error) {
136 self::$istimeout = true;
140 $xml = $curlResult->getBody();
141 $xrd = XML::parseString($xml, false);
142 $host_url = 'http://'.$host;
144 if (!is_object($xrd)) {
145 Logger::log("No xrd object found for ".$host, Logger::DEBUG);
149 $links = XML::elementToArray($xrd);
150 if (!isset($links["xrd"]["link"])) {
151 Logger::log("No xrd data found for ".$host, Logger::DEBUG);
155 $lrdd = ['application/jrd+json' => $host_url . '/.well-known/webfinger?resource={uri}'];
157 foreach ($links["xrd"]["link"] as $value => $link) {
158 if (!empty($link["@attributes"])) {
159 $attributes = $link["@attributes"];
160 } elseif ($value == "@attributes") {
166 if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
167 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
169 $lrdd[$type] = $attributes["template"];
173 self::$baseurl = $host_url;
175 Logger::log("Probing successful for ".$host, Logger::DEBUG);
181 * Perform Webfinger lookup and return DFRN data
183 * Given an email style address, perform webfinger lookup and
184 * return the resulting DFRN profile URL, or if no DFRN profile URL
185 * is located, returns an OStatus subscription template (prefixed
186 * with the string 'stat:' to identify it as on OStatus template).
187 * If this isn't an email style address just return $webbie.
188 * Return an empty string if email-style addresses but webfinger fails,
189 * or if the resultant personal XRD doesn't contain a supported
190 * subscription/friend-request attribute.
192 * amended 7/9/2011 to return an hcard which could save potentially loading
193 * a lengthy content page to scrape dfrn attributes
195 * @param string $webbie Address that should be probed
196 * @param string $hcard_url Link to the hcard - is returned by reference
198 * @return string profile link
199 * @throws HTTPException\InternalServerErrorException
201 public static function webfingerDfrn($webbie, &$hcard_url)
205 $links = self::lrdd($webbie);
206 Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA);
207 if (!empty($links) && is_array($links)) {
208 foreach ($links as $link) {
209 if ($link['@attributes']['rel'] === ActivityNamespace::DFRN) {
210 $profile_link = $link['@attributes']['href'];
212 if (($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) && ($profile_link == "")) {
213 $profile_link = 'stat:'.$link['@attributes']['template'];
215 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
216 $hcard_url = $link['@attributes']['href'];
220 return $profile_link;
224 * Check an URI for LRDD data
226 * this is a replacement for the "lrdd" function.
227 * It isn't used in this class and has some redundancies in the code.
228 * When time comes we can check the existing calls for "lrdd" if we can rework them.
230 * @param string $uri Address that should be probed
232 * @return array uri data
233 * @throws HTTPException\InternalServerErrorException
235 public static function lrdd($uri)
237 $lrdd = self::hostMeta($uri);
240 if (is_bool($lrdd)) {
245 $parts = @parse_url($uri);
246 if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
250 $host = $parts["host"];
251 if (!empty($parts["port"])) {
252 $host .= ':'.$parts["port"];
255 $path_parts = explode("/", trim($parts["path"], "/"));
257 $nick = array_pop($path_parts);
260 $lrdd = self::hostMeta($host);
261 $host .= "/".array_shift($path_parts);
262 } while (!$lrdd && (sizeof($path_parts) > 0));
266 Logger::log("No lrdd data found for ".$uri, Logger::DEBUG);
270 foreach ($lrdd as $type => $template) {
275 $path = str_replace('{uri}', urlencode($uri), $template);
276 $webfinger = self::webfinger($path, $type);
278 if (!$webfinger && (strstr($uri, "@"))) {
279 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
280 $webfinger = self::webfinger($path, $type);
283 // Special treatment for Mastodon
284 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
285 // But the webfinger for this format fails.
286 if (!$webfinger && !empty($nick)) {
287 // Mastodon uses a "@" as prefix for usernames in their url format
288 $nick = ltrim($nick, '@');
290 $addr = $nick."@".$host;
292 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
293 $webfinger = self::webfinger($path, $type);
297 if (!is_array($webfinger["links"])) {
298 Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
304 foreach ($webfinger["links"] as $link) {
305 $data[] = ["@attributes" => $link];
308 if (is_array($webfinger["aliases"])) {
309 foreach ($webfinger["aliases"] as $alias) {
310 $data[] = ["@attributes" =>
320 * Fetch information (protocol endpoints and user information) about a given uri
322 * @param string $uri Address that should be probed
323 * @param string $network Test for this specific network
324 * @param integer $uid User ID for the probe (only used for mails)
325 * @param boolean $cache Use cached values?
327 * @return array uri data
328 * @throws HTTPException\InternalServerErrorException
329 * @throws \ImagickException
331 public static function uri($uri, $network = '', $uid = -1, $cache = true)
334 $result = DI::cache()->get('Probe::uri:' . $network . ':' . $uri);
335 if (!is_null($result)) {
344 self::$istimeout = false;
346 if ($network != Protocol::ACTIVITYPUB) {
347 $data = self::detect($uri, $network, $uid);
352 // When the previous detection process had got a time out
353 // we could falsely detect a Friendica profile as AP profile.
354 if (!self::$istimeout) {
355 $ap_profile = ActivityPub::probeProfile($uri);
357 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
359 } elseif (!empty($ap_profile)) {
360 $ap_profile['batch'] = '';
361 $data = array_merge($ap_profile, $data);
364 Logger::notice('Time out detected. AP will not be probed.', ['uri' => $uri]);
367 if (!isset($data['url'])) {
371 if (!empty($data['photo']) && !empty($data['baseurl'])) {
372 $data['baseurl'] = Network::getUrlMatch(Strings::normaliseLink($data['baseurl']), Strings::normaliseLink($data['photo']));
373 } elseif (empty($data['photo'])) {
374 $data['photo'] = DI::baseUrl() . '/images/person-300.jpg';
377 if (empty($data['name'])) {
378 if (!empty($data['nick'])) {
379 $data['name'] = $data['nick'];
382 if (empty($data['name'])) {
383 $data['name'] = $data['url'];
387 if (empty($data['nick'])) {
388 $data['nick'] = strtolower($data['name']);
390 if (strpos($data['nick'], ' ')) {
391 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
395 if (!empty(self::$baseurl)) {
396 $data['baseurl'] = self::$baseurl;
399 if (empty($data['network'])) {
400 $data['network'] = Protocol::PHANTOM;
403 // Ensure that local connections always are DFRN
404 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
405 $data['network'] = Protocol::DFRN;
408 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
409 $data['hide'] = self::getHideStatus($data['url']);
412 $data = self::rearrangeData($data);
414 // Only store into the cache if the value seems to be valid
415 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
416 DI::cache()->set('Probe::uri:' . $network . ':' . $uri, $data, Duration::DAY);
424 * Fetches the "hide" status from the profile
426 * @param string $url URL of the profile
428 * @return boolean "hide" status
430 private static function getHideStatus($url)
432 $curlResult = Network::curl($url);
433 if (!$curlResult->isSuccess()) {
437 // If the file is too large then exit
438 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
442 // If it isn't a HTML file then exit
443 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
447 $body = $curlResult->getBody();
449 $doc = new DOMDocument();
450 @$doc->loadHTML($body);
452 $xpath = new DOMXPath($doc);
454 $list = $xpath->query('//meta[@name]');
455 foreach ($list as $node) {
457 if ($node->attributes->length) {
458 foreach ($node->attributes as $attribute) {
459 $meta_tag[$attribute->name] = $attribute->value;
463 if (empty($meta_tag['content'])) {
467 $content = strtolower(trim($meta_tag['content']));
469 switch (strtolower(trim($meta_tag['name']))) {
470 case 'dfrn-global-visibility':
471 if ($content == 'false') {
476 if (strpos($content, 'noindex') !== false) {
487 * Checks if a profile url should be OStatus but only provides partial information
489 * @param array $webfinger Webfinger data
490 * @param string $lrdd Path template for webfinger request
491 * @param string $type type
493 * @return array fixed webfinger data
494 * @throws HTTPException\InternalServerErrorException
496 private static function fixOStatus($webfinger, $lrdd, $type)
498 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
505 foreach ($webfinger['links'] as $link) {
506 if ($link['rel'] == ActivityNamespace::OSTATUSSUB) {
509 if ($link['rel'] == 'magic-public-key') {
514 if (!$is_ostatus || $has_key) {
518 $url = Network::switchScheme($webfinger['subject']);
519 $path = str_replace('{uri}', urlencode($url), $lrdd);
520 $webfinger2 = self::webfinger($path, $type);
522 // Is the new webfinger detectable as OStatus?
523 if (self::ostatus($webfinger2, true)) {
524 $webfinger = $webfinger2;
531 * Fetch information (protocol endpoints and user information) about a given uri
533 * This function is only called by the "uri" function that adds caching and rearranging of data.
535 * @param string $uri Address that should be probed
536 * @param string $network Test for this specific network
537 * @param integer $uid User ID for the probe (only used for mails)
539 * @return array uri data
540 * @throws HTTPException\InternalServerErrorException
542 private static function detect($uri, $network, $uid)
544 $parts = parse_url($uri);
546 if (!empty($parts["scheme"]) && !empty($parts["host"])) {
547 $host = $parts["host"];
548 if (!empty($parts["port"])) {
549 $host .= ':'.$parts["port"];
552 if ($host == 'twitter.com') {
553 return self::twitter($uri);
555 $lrdd = self::hostMeta($host);
557 if (is_bool($lrdd)) {
561 $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
563 while (!$lrdd && (sizeof($path_parts) > 1)) {
564 $host .= "/".array_shift($path_parts);
565 $lrdd = self::hostMeta($host);
568 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
569 return self::feed($uri);
571 $nick = array_pop($path_parts);
573 // Mastodon uses a "@" as prefix for usernames in their url format
574 $nick = ltrim($nick, '@');
576 $addr = $nick."@".$host;
577 } elseif (strstr($uri, '@')) {
578 // If the URI starts with "mailto:" then jump directly to the mail detection
579 if (strpos($uri, 'mailto:') !== false) {
580 $uri = str_replace('mailto:', '', $uri);
581 return self::mail($uri, $uid);
584 if ($network == Protocol::MAIL) {
585 return self::mail($uri, $uid);
587 // Remove "acct:" from the URI
588 $uri = str_replace('acct:', '', $uri);
590 $host = substr($uri, strpos($uri, '@') + 1);
591 $nick = substr($uri, 0, strpos($uri, '@'));
593 if (strpos($uri, '@twitter.com')) {
594 return self::twitter($uri);
596 $lrdd = self::hostMeta($host);
598 if (is_bool($lrdd)) {
603 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
604 return self::mail($uri, $uid);
608 Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
614 /// @todo Do we need the prefix "acct:" or "acct://"?
616 foreach ($lrdd as $type => $template) {
621 // At first try it with the given uri
622 $path = str_replace('{uri}', urlencode($uri), $template);
623 $webfinger = self::webfinger($path, $type);
625 // Fix possible problems with GNU Social probing to wrong scheme
626 $webfinger = self::fixOStatus($webfinger, $template, $type);
628 // We cannot be sure that the detected address was correct, so we don't use the values
629 if ($webfinger && ($uri != $addr)) {
634 // Try webfinger with the address (user@domain.tld)
636 $path = str_replace('{uri}', urlencode($addr), $template);
637 $webfinger = self::webfinger($path, $type);
640 // Mastodon needs to have it with "acct:"
642 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
643 $webfinger = self::webfinger($path, $type);
648 return self::feed($uri);
653 Logger::log("Probing ".$uri, Logger::DEBUG);
655 if (in_array($network, ["", Protocol::DFRN])) {
656 $result = self::dfrn($webfinger);
658 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
659 $result = self::diaspora($webfinger);
661 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
662 $result = self::ostatus($webfinger);
664 if (in_array($network, ['', Protocol::ZOT])) {
665 $result = self::zot($webfinger, $result);
667 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
668 $result = self::pumpio($webfinger, $addr);
670 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
671 $result = self::feed($uri);
673 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
674 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
675 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
676 $result["nick"] = $nick;
679 if (empty($result["addr"]) && ($addr != "")) {
680 $result["addr"] = $addr;
684 if (empty($result["network"])) {
685 $result["network"] = Protocol::PHANTOM;
688 if (empty($result["url"])) {
689 $result["url"] = $uri;
692 Logger::log($uri." is ".$result["network"], Logger::DEBUG);
694 if (empty($result["baseurl"]) && ($result["network"] != Protocol::PHANTOM)) {
695 $pos = strpos($result["url"], $host);
697 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
704 * Check for Zot contact
706 * @param array $webfinger Webfinger data
707 * @param array $data previously probed data
709 * @return array Zot data
710 * @throws HTTPException\InternalServerErrorException
712 private static function zot($webfinger, $data)
714 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
715 foreach ($webfinger["aliases"] as $alias) {
716 if (substr($alias, 0, 5) == 'acct:') {
717 $data["addr"] = substr($alias, 5);
722 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
723 $data["addr"] = substr($webfinger["subject"], 5);
727 foreach ($webfinger['links'] as $link) {
728 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
729 $zot_url = $link['href'];
733 if (empty($zot_url) && !empty($data['addr']) && !empty(self::$baseurl)) {
734 $condition = ['nurl' => Strings::normaliseLink(self::$baseurl), 'platform' => ['hubzilla']];
735 if (!DBA::exists('gserver', $condition)) {
738 $zot_url = self::$baseurl . '/.well-known/zot-info?address=' . $data['addr'];
741 if (empty($zot_url)) {
745 $data = self::pollZot($zot_url, $data);
747 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
748 foreach ($webfinger['aliases'] as $alias) {
749 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
750 $data['alias'] = $alias;
758 public static function pollZot($url, $data)
760 $curlResult = Network::curl($url);
761 if ($curlResult->isTimeout()) {
764 $content = $curlResult->getBody();
769 $json = json_decode($content, true);
770 if (!is_array($json)) {
774 if (empty($data['network'])) {
775 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
776 $data['network'] = Protocol::ZOT;
777 } elseif (!isset($json['protocols'])) {
778 $data['network'] = Protocol::ZOT;
782 if (!empty($json['guid']) && empty($data['guid'])) {
783 $data['guid'] = $json['guid'];
785 if (!empty($json['key']) && empty($data['pubkey'])) {
786 $data['pubkey'] = $json['key'];
788 if (!empty($json['name'])) {
789 $data['name'] = $json['name'];
791 if (!empty($json['photo'])) {
792 $data['photo'] = $json['photo'];
793 if (!empty($json['photo_updated'])) {
794 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
797 if (!empty($json['address'])) {
798 $data['addr'] = $json['address'];
800 if (!empty($json['url'])) {
801 $data['url'] = $json['url'];
803 if (!empty($json['connections_url'])) {
804 $data['poco'] = $json['connections_url'];
806 if (isset($json['searchable'])) {
807 $data['hide'] = !$json['searchable'];
809 if (!empty($json['public_forum'])) {
810 $data['community'] = $json['public_forum'];
811 $data['account-type'] = Contact::PAGE_COMMUNITY;
814 if (!empty($json['profile'])) {
815 $profile = $json['profile'];
816 if (!empty($profile['description'])) {
817 $data['about'] = $profile['description'];
819 if (!empty($profile['gender'])) {
820 $data['gender'] = $profile['gender'];
822 if (!empty($profile['keywords'])) {
823 $keywords = implode(', ', $profile['keywords']);
824 if (!empty($keywords)) {
825 $data['keywords'] = $keywords;
830 if (!empty($profile['region'])) {
831 $loc['region'] = $profile['region'];
833 if (!empty($profile['country'])) {
834 $loc['country-name'] = $profile['country'];
836 $location = Profile::formatLocation($loc);
837 if (!empty($location)) {
838 $data['location'] = $location;
846 * Perform a webfinger request.
848 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
850 * @param string $url Address that should be probed
851 * @param string $type type
853 * @return array webfinger data
854 * @throws HTTPException\InternalServerErrorException
856 private static function webfinger($url, $type)
858 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
860 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
861 if ($curlResult->isTimeout()) {
862 self::$istimeout = true;
865 $data = $curlResult->getBody();
867 $webfinger = json_decode($data, true);
868 if (is_array($webfinger)) {
869 if (!isset($webfinger["links"])) {
870 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
876 // If it is not JSON, maybe it is XML
877 $xrd = XML::parseString($data, false);
878 if (!is_object($xrd)) {
879 Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
883 $xrd_arr = XML::elementToArray($xrd);
884 if (!isset($xrd_arr["xrd"]["link"])) {
885 Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
891 if (!empty($xrd_arr["xrd"]["subject"])) {
892 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
895 if (!empty($xrd_arr["xrd"]["alias"])) {
896 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
899 $webfinger["links"] = [];
901 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
902 if (!empty($data["@attributes"])) {
903 $attributes = $data["@attributes"];
904 } elseif ($value == "@attributes") {
910 $webfinger["links"][] = $attributes;
916 * Poll the Friendica specific noscrape page.
918 * "noscrape" is a faster alternative to fetch the data from the hcard.
919 * This functionality was originally created for the directory.
921 * @param string $noscrape_url Link to the noscrape page
922 * @param array $data The already fetched data
924 * @return array noscrape data
925 * @throws HTTPException\InternalServerErrorException
927 private static function pollNoscrape($noscrape_url, $data)
929 $curlResult = Network::curl($noscrape_url);
930 if ($curlResult->isTimeout()) {
931 self::$istimeout = true;
934 $content = $curlResult->getBody();
936 Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
940 $json = json_decode($content, true);
941 if (!is_array($json)) {
942 Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
946 if (!empty($json["fn"])) {
947 $data["name"] = $json["fn"];
950 if (!empty($json["addr"])) {
951 $data["addr"] = $json["addr"];
954 if (!empty($json["nick"])) {
955 $data["nick"] = $json["nick"];
958 if (!empty($json["guid"])) {
959 $data["guid"] = $json["guid"];
962 if (!empty($json["comm"])) {
963 $data["community"] = $json["comm"];
966 if (!empty($json["tags"])) {
967 $keywords = implode(", ", $json["tags"]);
968 if ($keywords != "") {
969 $data["keywords"] = $keywords;
973 $location = Profile::formatLocation($json);
975 $data["location"] = $location;
978 if (!empty($json["about"])) {
979 $data["about"] = $json["about"];
982 if (!empty($json["gender"])) {
983 $data["gender"] = $json["gender"];
986 if (!empty($json["key"])) {
987 $data["pubkey"] = $json["key"];
990 if (!empty($json["photo"])) {
991 $data["photo"] = $json["photo"];
994 if (!empty($json["dfrn-request"])) {
995 $data["request"] = $json["dfrn-request"];
998 if (!empty($json["dfrn-confirm"])) {
999 $data["confirm"] = $json["dfrn-confirm"];
1002 if (!empty($json["dfrn-notify"])) {
1003 $data["notify"] = $json["dfrn-notify"];
1006 if (!empty($json["dfrn-poll"])) {
1007 $data["poll"] = $json["dfrn-poll"];
1010 if (isset($json["hide"])) {
1011 $data["hide"] = (bool)$json["hide"];
1013 $data["hide"] = false;
1020 * Check for valid DFRN data
1022 * @param array $data DFRN data
1024 * @return int Number of errors
1026 public static function validDfrn($data)
1029 if (!isset($data['key'])) {
1032 if (!isset($data['dfrn-request'])) {
1035 if (!isset($data['dfrn-confirm'])) {
1038 if (!isset($data['dfrn-notify'])) {
1041 if (!isset($data['dfrn-poll'])) {
1048 * Fetch data from a DFRN profile page and via "noscrape"
1050 * @param string $profile_link Link to the profile page
1052 * @return array profile data
1053 * @throws HTTPException\InternalServerErrorException
1054 * @throws \ImagickException
1056 public static function profile($profile_link)
1060 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
1062 // Fetch data via noscrape - this is faster
1063 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1064 $data = self::pollNoscrape($noscrape_url, $data);
1066 if (!isset($data["notify"])
1067 || !isset($data["confirm"])
1068 || !isset($data["request"])
1069 || !isset($data["poll"])
1070 || !isset($data["name"])
1071 || !isset($data["photo"])
1073 $data = self::pollHcard($profile_link, $data, true);
1078 if (empty($data["addr"]) || empty($data["nick"])) {
1079 $probe_data = self::uri($profile_link);
1080 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1081 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1084 $prof_data["addr"] = $data["addr"];
1085 $prof_data["nick"] = $data["nick"];
1086 $prof_data["dfrn-request"] = $data['request'] ?? null;
1087 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1088 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1089 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1090 $prof_data["photo"] = $data['photo'] ?? null;
1091 $prof_data["fn"] = $data['name'] ?? null;
1092 $prof_data["key"] = $data['pubkey'] ?? null;
1094 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
1100 * Check for DFRN contact
1102 * @param array $webfinger Webfinger data
1104 * @return array DFRN data
1105 * @throws HTTPException\InternalServerErrorException
1107 private static function dfrn($webfinger)
1111 // The array is reversed to take into account the order of preference for same-rel links
1112 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1113 foreach (array_reverse($webfinger["links"]) as $link) {
1114 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1115 $data["network"] = Protocol::DFRN;
1116 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1117 $data["poll"] = $link["href"];
1118 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1119 $data["url"] = $link["href"];
1120 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1121 $hcard_url = $link["href"];
1122 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1123 $data["poco"] = $link["href"];
1124 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1125 $data["photo"] = $link["href"];
1126 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1127 $data["baseurl"] = trim($link["href"], '/');
1128 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1129 $data["guid"] = $link["href"];
1130 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1131 $data["pubkey"] = base64_decode($link["href"]);
1133 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1134 if (strstr($data["pubkey"], 'RSA ')) {
1135 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1140 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1141 foreach ($webfinger["aliases"] as $alias) {
1142 if (empty($data["url"]) && !strstr($alias, "@")) {
1143 $data["url"] = $alias;
1144 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1145 $data["alias"] = $alias;
1146 } elseif (substr($alias, 0, 5) == 'acct:') {
1147 $data["addr"] = substr($alias, 5);
1152 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1153 $data["addr"] = substr($webfinger["subject"], 5);
1156 if (!isset($data["network"]) || ($hcard_url == "")) {
1160 // Fetch data via noscrape - this is faster
1161 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1162 $data = self::pollNoscrape($noscrape_url, $data);
1164 if (isset($data["notify"])
1165 && isset($data["confirm"])
1166 && isset($data["request"])
1167 && isset($data["poll"])
1168 && isset($data["name"])
1169 && isset($data["photo"])
1174 $data = self::pollHcard($hcard_url, $data, true);
1180 * Poll the hcard page (Diaspora and Friendica specific)
1182 * @param string $hcard_url Link to the hcard page
1183 * @param array $data The already fetched data
1184 * @param boolean $dfrn Poll DFRN specific data
1186 * @return array hcard data
1187 * @throws HTTPException\InternalServerErrorException
1189 private static function pollHcard($hcard_url, $data, $dfrn = false)
1191 $curlResult = Network::curl($hcard_url);
1192 if ($curlResult->isTimeout()) {
1193 self::$istimeout = true;
1196 $content = $curlResult->getBody();
1201 $doc = new DOMDocument();
1202 if (!@$doc->loadHTML($content)) {
1206 $xpath = new DomXPath($doc);
1208 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1209 if (!is_object($vcards)) {
1213 if (!isset($data["baseurl"])) {
1214 $data["baseurl"] = "";
1217 if ($vcards->length > 0) {
1218 $vcard = $vcards->item(0);
1220 // We have to discard the guid from the hcard in favour of the guid from lrdd
1221 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1222 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1223 if (($search->length > 0) && empty($data["guid"])) {
1224 $data["guid"] = $search->item(0)->nodeValue;
1227 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1228 if ($search->length > 0) {
1229 $data["nick"] = $search->item(0)->nodeValue;
1232 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1233 if ($search->length > 0) {
1234 $data["name"] = $search->item(0)->nodeValue;
1237 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1238 if ($search->length > 0) {
1239 $data["searchable"] = $search->item(0)->nodeValue;
1242 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1243 if ($search->length > 0) {
1244 $data["pubkey"] = $search->item(0)->nodeValue;
1245 if (strstr($data["pubkey"], 'RSA ')) {
1246 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1250 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1251 if ($search->length > 0) {
1252 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1257 if (!empty($vcard)) {
1258 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1259 foreach ($photos as $photo) {
1261 foreach ($photo->attributes as $attribute) {
1262 $attr[$attribute->name] = trim($attribute->value);
1265 if (isset($attr["src"]) && isset($attr["width"])) {
1266 $avatar[$attr["width"]] = $attr["src"];
1269 // We don't have a width. So we just take everything that we got.
1270 // This is a Hubzilla workaround which doesn't send a width.
1271 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1272 $avatar[] = $attr["src"];
1277 if (sizeof($avatar)) {
1279 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1283 // Poll DFRN specific data
1284 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1285 if ($search->length > 0) {
1286 foreach ($search as $link) {
1287 //$data["request"] = $search->item(0)->nodeValue;
1289 foreach ($link->attributes as $attribute) {
1290 $attr[$attribute->name] = trim($attribute->value);
1293 $data[substr($attr["rel"], 5)] = $attr["href"];
1297 // Older Friendica versions had used the "uid" field differently than newer versions
1298 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1299 unset($data["guid"]);
1308 * Check for Diaspora contact
1310 * @param array $webfinger Webfinger data
1312 * @return array Diaspora data
1313 * @throws HTTPException\InternalServerErrorException
1315 private static function diaspora($webfinger)
1320 // The array is reversed to take into account the order of preference for same-rel links
1321 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1322 foreach (array_reverse($webfinger["links"]) as $link) {
1323 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1324 $hcard_url = $link["href"];
1325 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1326 $data["baseurl"] = trim($link["href"], '/');
1327 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1328 $data["guid"] = $link["href"];
1329 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1330 $data["url"] = $link["href"];
1331 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1332 $data["poll"] = $link["href"];
1333 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1334 $data["poco"] = $link["href"];
1335 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1336 $data["notify"] = $link["href"];
1337 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1338 $data["pubkey"] = base64_decode($link["href"]);
1340 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1341 if (strstr($data["pubkey"], 'RSA ')) {
1342 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1347 if (empty($data["url"]) || empty($hcard_url)) {
1351 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1352 foreach ($webfinger["aliases"] as $alias) {
1353 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1354 $data["alias"] = $alias;
1355 } elseif (substr($alias, 0, 5) == 'acct:') {
1356 $data["addr"] = substr($alias, 5);
1361 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1362 $data["addr"] = substr($webfinger["subject"], 5);
1365 // Fetch further information from the hcard
1366 $data = self::pollHcard($hcard_url, $data);
1372 if (!empty($data["url"])
1373 && !empty($data["guid"])
1374 && !empty($data["baseurl"])
1375 && !empty($data["pubkey"])
1376 && !empty($hcard_url)
1378 $data["network"] = Protocol::DIASPORA;
1380 // The Diaspora handle must always be lowercase
1381 if (!empty($data["addr"])) {
1382 $data["addr"] = strtolower($data["addr"]);
1385 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1386 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1387 $data["batch"] = $data["baseurl"] . "/receive/public";
1396 * Check for OStatus contact
1398 * @param array $webfinger Webfinger data
1399 * @param bool $short Short detection mode
1401 * @return array|bool OStatus data or "false" on error or "true" on short mode
1402 * @throws HTTPException\InternalServerErrorException
1404 private static function ostatus($webfinger, $short = false)
1408 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1409 foreach ($webfinger["aliases"] as $alias) {
1410 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1411 $data["addr"] = str_replace('acct:', '', $alias);
1416 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1417 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1419 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1422 if (is_array($webfinger["links"])) {
1423 // The array is reversed to take into account the order of preference for same-rel links
1424 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1425 foreach (array_reverse($webfinger["links"]) as $link) {
1426 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1427 && (($link["type"] ?? "") == "text/html")
1428 && ($link["href"] != "")
1430 $data["url"] = $link["href"];
1431 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1432 $data["notify"] = $link["href"];
1433 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1434 $data["poll"] = $link["href"];
1435 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1436 $pubkey = $link["href"];
1438 if (substr($pubkey, 0, 5) === 'data:') {
1439 if (strstr($pubkey, ',')) {
1440 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1442 $pubkey = substr($pubkey, 5);
1444 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1445 $curlResult = Network::curl($pubkey);
1446 if ($curlResult->isTimeout()) {
1447 self::$istimeout = true;
1450 $pubkey = $curlResult->getBody();
1453 $key = explode(".", $pubkey);
1455 if (sizeof($key) >= 3) {
1456 $m = Strings::base64UrlDecode($key[1]);
1457 $e = Strings::base64UrlDecode($key[2]);
1458 $data["pubkey"] = Crypto::meToPem($m, $e);
1464 if (isset($data["notify"]) && isset($data["pubkey"])
1465 && isset($data["poll"])
1466 && isset($data["url"])
1468 $data["network"] = Protocol::OSTATUS;
1477 // Fetch all additional data from the feed
1478 $curlResult = Network::curl($data["poll"]);
1479 if ($curlResult->isTimeout()) {
1480 self::$istimeout = true;
1483 $feed = $curlResult->getBody();
1484 $feed_data = Feed::import($feed);
1489 if (!empty($feed_data["header"]["author-name"])) {
1490 $data["name"] = $feed_data["header"]["author-name"];
1492 if (!empty($feed_data["header"]["author-nick"])) {
1493 $data["nick"] = $feed_data["header"]["author-nick"];
1495 if (!empty($feed_data["header"]["author-avatar"])) {
1496 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1498 if (!empty($feed_data["header"]["author-id"])) {
1499 $data["alias"] = $feed_data["header"]["author-id"];
1501 if (!empty($feed_data["header"]["author-location"])) {
1502 $data["location"] = $feed_data["header"]["author-location"];
1504 if (!empty($feed_data["header"]["author-about"])) {
1505 $data["about"] = $feed_data["header"]["author-about"];
1507 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1508 // So we take the value that we just fetched, although the other one worked as well
1509 if (!empty($feed_data["header"]["author-link"])) {
1510 $data["url"] = $feed_data["header"]["author-link"];
1513 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1514 $data['url'] = $data["alias"];
1515 $data["alias"] = '';
1518 /// @todo Fetch location and "about" from the feed as well
1523 * Fetch data from a pump.io profile page
1525 * @param string $profile_link Link to the profile page
1527 * @return array profile data
1529 private static function pumpioProfileData($profile_link)
1531 $curlResult = Network::curl($profile_link);
1532 if (!$curlResult->isSuccess()) {
1536 $doc = new DOMDocument();
1537 if (!@$doc->loadHTML($curlResult->getBody())) {
1541 $xpath = new DomXPath($doc);
1545 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1547 if ($data["name"] == '') {
1548 // This is ugly - but pump.io doesn't seem to know a better way for it
1549 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1550 $pos = strpos($data["name"], chr(10));
1552 $data["name"] = trim(substr($data["name"], 0, $pos));
1556 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1558 if ($data["location"] == '') {
1559 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1562 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1564 if ($data["about"] == '') {
1565 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1568 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1570 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1573 foreach ($avatar->attributes as $attribute) {
1574 if ($attribute->name == "src") {
1575 $data["photo"] = trim($attribute->value);
1584 * Check for pump.io contact
1586 * @param array $webfinger Webfinger data
1587 * @param string $addr
1588 * @return array pump.io data
1590 private static function pumpio($webfinger, $addr)
1593 // The array is reversed to take into account the order of preference for same-rel links
1594 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1595 foreach (array_reverse($webfinger["links"]) as $link) {
1596 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1597 && (($link["type"] ?? "") == "text/html")
1598 && ($link["href"] != "")
1600 $data["url"] = $link["href"];
1601 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1602 $data["notify"] = $link["href"];
1603 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1604 $data["poll"] = $link["href"];
1605 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1606 $data["dialback"] = $link["href"];
1609 if (isset($data["poll"]) && isset($data["notify"])
1610 && isset($data["dialback"])
1611 && isset($data["url"])
1613 // by now we use these fields only for the network type detection
1614 // So we unset all data that isn't used at the moment
1615 unset($data["dialback"]);
1617 $data["network"] = Protocol::PUMPIO;
1622 $profile_data = self::pumpioProfileData($data["url"]);
1624 if (!$profile_data) {
1628 $data = array_merge($data, $profile_data);
1630 if (($addr != '') && ($data['name'] != '')) {
1631 $name = trim(str_replace($addr, '', $data['name']));
1633 $data['name'] = $name;
1641 * Check for twitter contact
1643 * @param string $uri
1645 * @return array twitter data
1647 private static function twitter($uri)
1649 if (preg_match('=(.*)@twitter.com=i', $uri, $matches)) {
1650 $nick = $matches[1];
1651 } elseif (preg_match('=https?://twitter.com/(.*)=i', $uri, $matches)) {
1652 $nick = $matches[1];
1658 $data['url'] = 'https://twitter.com/' . $nick;
1659 $data['addr'] = $nick . '@twitter.com';
1660 $data['nick'] = $data['name'] = $nick;
1661 $data['network'] = Protocol::TWITTER;
1662 $data['baseurl'] = 'https://twitter.com';
1664 $curlResult = Network::curl($data['url'], false);
1665 if (!$curlResult->isSuccess()) {
1669 $body = $curlResult->getBody();
1670 $doc = new DOMDocument();
1671 @$doc->loadHTML($body);
1672 $xpath = new DOMXPath($doc);
1674 $list = $xpath->query('//img[@class]');
1675 foreach ($list as $node) {
1677 if ($node->attributes->length) {
1678 foreach ($node->attributes as $attribute) {
1679 $img_attr[$attribute->name] = $attribute->value;
1683 if (empty($img_attr['class'])) {
1687 if (strpos($img_attr['class'], 'ProfileAvatar-image') !== false) {
1688 if (!empty($img_attr['src'])) {
1689 $data['photo'] = $img_attr['src'];
1691 if (!empty($img_attr['alt'])) {
1692 $data['name'] = $img_attr['alt'];
1701 * Check page for feed link
1703 * @param string $url Page link
1705 * @return string feed link
1707 private static function getFeedLink($url)
1709 $curlResult = Network::curl($url);
1710 if (!$curlResult->isSuccess()) {
1714 $doc = new DOMDocument();
1715 if (!@$doc->loadHTML($curlResult->getBody())) {
1719 $xpath = new DomXPath($doc);
1721 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1722 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1723 if (!is_object($feeds)) {
1727 if ($feeds->length == 0) {
1733 foreach ($feeds as $feed) {
1735 foreach ($feed->attributes as $attribute) {
1736 $attr[$attribute->name] = trim($attribute->value);
1739 if (empty($feed_url) && !empty($attr['href'])) {
1740 $feed_url = $attr["href"];
1748 * Check for feed contact
1750 * @param string $url Profile link
1751 * @param boolean $probe Do a probe if the page contains a feed link
1753 * @return array feed data
1754 * @throws HTTPException\InternalServerErrorException
1756 private static function feed($url, $probe = true)
1758 $curlResult = Network::curl($url);
1759 if ($curlResult->isTimeout()) {
1760 self::$istimeout = true;
1763 $feed = $curlResult->getBody();
1764 $feed_data = Feed::import($feed);
1771 $feed_url = self::getFeedLink($url);
1777 return self::feed($feed_url, false);
1780 if (!empty($feed_data["header"]["author-name"])) {
1781 $data["name"] = $feed_data["header"]["author-name"];
1784 if (!empty($feed_data["header"]["author-nick"])) {
1785 $data["nick"] = $feed_data["header"]["author-nick"];
1788 if (!empty($feed_data["header"]["author-avatar"])) {
1789 $data["photo"] = $feed_data["header"]["author-avatar"];
1792 if (!empty($feed_data["header"]["author-id"])) {
1793 $data["alias"] = $feed_data["header"]["author-id"];
1796 $data["url"] = $url;
1797 $data["poll"] = $url;
1799 if (!empty($feed_data["header"]["author-link"])) {
1800 $data["baseurl"] = $feed_data["header"]["author-link"];
1802 $data["baseurl"] = $data["url"];
1805 $data["network"] = Protocol::FEED;
1811 * Check for mail contact
1813 * @param string $uri Profile link
1814 * @param integer $uid User ID
1816 * @return array mail data
1817 * @throws \Exception
1819 private static function mail($uri, $uid)
1821 if (!Network::isEmailDomainValid($uri)) {
1829 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1831 $condition = ["`uid` = ? AND `server` != ''", $uid];
1832 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1833 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1835 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1839 $mailbox = Email::constructMailboxName($mailacct);
1841 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1842 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1847 $msgs = Email::poll($mbox, $uri);
1848 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1850 if (!count($msgs)) {
1854 $phost = substr($uri, strpos($uri, '@') + 1);
1857 $data["addr"] = $uri;
1858 $data["network"] = Protocol::MAIL;
1859 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1860 $data["nick"] = $data["name"];
1861 $data["photo"] = Network::lookupAvatarByEmail($uri);
1862 $data["url"] = 'mailto:'.$uri;
1863 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1864 $data["poll"] = 'email ' . Strings::getRandomHex();
1866 $x = Email::messageMeta($mbox, $msgs[0]);
1867 if (stristr($x[0]->from, $uri)) {
1868 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1869 } elseif (stristr($x[0]->to, $uri)) {
1870 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1873 foreach ($adr as $feadr) {
1874 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1875 &&(strcasecmp($feadr->host, $phost) == 0)
1876 && (strlen($feadr->personal))
1878 $personal = imap_mime_header_decode($feadr->personal);
1880 foreach ($personal as $perspart) {
1881 if ($perspart->charset != "default") {
1882 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1884 $data["name"] .= $perspart->text;
1888 $data["name"] = Strings::escapeTags($data["name"]);
1892 if (!empty($mbox)) {
1899 * Mix two paths together to possibly fix missing parts
1901 * @param string $avatar Path to the avatar
1902 * @param string $base Another path that is hopefully complete
1904 * @return string fixed avatar path
1905 * @throws \Exception
1907 public static function fixAvatar($avatar, $base)
1909 $base_parts = parse_url($base);
1911 // Remove all parts that could create a problem
1912 unset($base_parts['path']);
1913 unset($base_parts['query']);
1914 unset($base_parts['fragment']);
1916 $avatar_parts = parse_url($avatar);
1919 $parts = array_merge($base_parts, $avatar_parts);
1921 // And put them together again
1922 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1923 $host = isset($parts['host']) ? $parts['host'] : '';
1924 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1925 $path = isset($parts['path']) ? $parts['path'] : '';
1926 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1927 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1929 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1931 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);