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 * Get the link for the remote follow page for a given profile link
226 * @param sting $profile
227 * @return string Remote follow page link
229 public static function getRemoteFollowLink(string $profile)
233 $links = self::lrdd($profile);
235 if (!empty($links) && is_array($links)) {
236 foreach ($links as $link) {
237 if ($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) {
238 $follow_link = $link['@attributes']['template'];
246 * Check an URI for LRDD data
248 * this is a replacement for the "lrdd" function.
249 * It isn't used in this class and has some redundancies in the code.
250 * When time comes we can check the existing calls for "lrdd" if we can rework them.
252 * @param string $uri Address that should be probed
254 * @return array uri data
255 * @throws HTTPException\InternalServerErrorException
257 public static function lrdd($uri)
259 $lrdd = self::hostMeta($uri);
262 if (is_bool($lrdd)) {
267 $parts = @parse_url($uri);
268 if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
272 $host = $parts["host"];
273 if (!empty($parts["port"])) {
274 $host .= ':'.$parts["port"];
277 $path_parts = explode("/", trim($parts["path"], "/"));
279 $nick = array_pop($path_parts);
282 $lrdd = self::hostMeta($host);
283 $host .= "/".array_shift($path_parts);
284 } while (!$lrdd && (sizeof($path_parts) > 0));
288 Logger::log("No lrdd data found for ".$uri, Logger::DEBUG);
292 foreach ($lrdd as $type => $template) {
297 $path = str_replace('{uri}', urlencode($uri), $template);
298 $webfinger = self::webfinger($path, $type);
300 if (!$webfinger && (strstr($uri, "@"))) {
301 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
302 $webfinger = self::webfinger($path, $type);
305 // Special treatment for Mastodon
306 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
307 // But the webfinger for this format fails.
308 if (!$webfinger && !empty($nick)) {
309 // Mastodon uses a "@" as prefix for usernames in their url format
310 $nick = ltrim($nick, '@');
312 $addr = $nick."@".$host;
314 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
315 $webfinger = self::webfinger($path, $type);
319 if (!is_array($webfinger["links"])) {
320 Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
326 foreach ($webfinger["links"] as $link) {
327 $data[] = ["@attributes" => $link];
330 if (is_array($webfinger["aliases"])) {
331 foreach ($webfinger["aliases"] as $alias) {
332 $data[] = ["@attributes" =>
342 * Fetch information (protocol endpoints and user information) about a given uri
344 * @param string $uri Address that should be probed
345 * @param string $network Test for this specific network
346 * @param integer $uid User ID for the probe (only used for mails)
347 * @param boolean $cache Use cached values?
349 * @return array uri data
350 * @throws HTTPException\InternalServerErrorException
351 * @throws \ImagickException
353 public static function uri($uri, $network = '', $uid = -1, $cache = true)
356 $result = DI::cache()->get('Probe::uri:' . $network . ':' . $uri);
357 if (!is_null($result)) {
366 self::$istimeout = false;
368 if ($network != Protocol::ACTIVITYPUB) {
369 $data = self::detect($uri, $network, $uid);
374 // When the previous detection process had got a time out
375 // we could falsely detect a Friendica profile as AP profile.
376 if (!self::$istimeout) {
377 $ap_profile = ActivityPub::probeProfile($uri);
379 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
381 } elseif (!empty($ap_profile)) {
382 $ap_profile['batch'] = '';
383 $data = array_merge($ap_profile, $data);
386 Logger::notice('Time out detected. AP will not be probed.', ['uri' => $uri]);
389 if (!isset($data['url'])) {
393 if (!empty($data['photo']) && !empty($data['baseurl'])) {
394 $data['baseurl'] = Network::getUrlMatch(Strings::normaliseLink($data['baseurl']), Strings::normaliseLink($data['photo']));
395 } elseif (empty($data['photo'])) {
396 $data['photo'] = DI::baseUrl() . '/images/person-300.jpg';
399 if (empty($data['name'])) {
400 if (!empty($data['nick'])) {
401 $data['name'] = $data['nick'];
404 if (empty($data['name'])) {
405 $data['name'] = $data['url'];
409 if (empty($data['nick'])) {
410 $data['nick'] = strtolower($data['name']);
412 if (strpos($data['nick'], ' ')) {
413 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
417 if (!empty(self::$baseurl)) {
418 $data['baseurl'] = self::$baseurl;
421 if (empty($data['network'])) {
422 $data['network'] = Protocol::PHANTOM;
425 // Ensure that local connections always are DFRN
426 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
427 $data['network'] = Protocol::DFRN;
430 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
431 $data['hide'] = self::getHideStatus($data['url']);
434 $data = self::rearrangeData($data);
436 // Only store into the cache if the value seems to be valid
437 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
438 DI::cache()->set('Probe::uri:' . $network . ':' . $uri, $data, Duration::DAY);
446 * Fetches the "hide" status from the profile
448 * @param string $url URL of the profile
450 * @return boolean "hide" status
452 private static function getHideStatus($url)
454 $curlResult = Network::curl($url);
455 if (!$curlResult->isSuccess()) {
459 // If the file is too large then exit
460 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
464 // If it isn't a HTML file then exit
465 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
469 $body = $curlResult->getBody();
471 $doc = new DOMDocument();
472 @$doc->loadHTML($body);
474 $xpath = new DOMXPath($doc);
476 $list = $xpath->query('//meta[@name]');
477 foreach ($list as $node) {
479 if ($node->attributes->length) {
480 foreach ($node->attributes as $attribute) {
481 $meta_tag[$attribute->name] = $attribute->value;
485 if (empty($meta_tag['content'])) {
489 $content = strtolower(trim($meta_tag['content']));
491 switch (strtolower(trim($meta_tag['name']))) {
492 case 'dfrn-global-visibility':
493 if ($content == 'false') {
498 if (strpos($content, 'noindex') !== false) {
509 * Checks if a profile url should be OStatus but only provides partial information
511 * @param array $webfinger Webfinger data
512 * @param string $lrdd Path template for webfinger request
513 * @param string $type type
515 * @return array fixed webfinger data
516 * @throws HTTPException\InternalServerErrorException
518 private static function fixOStatus($webfinger, $lrdd, $type)
520 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
527 foreach ($webfinger['links'] as $link) {
528 if ($link['rel'] == ActivityNamespace::OSTATUSSUB) {
531 if ($link['rel'] == 'magic-public-key') {
536 if (!$is_ostatus || $has_key) {
540 $url = Network::switchScheme($webfinger['subject']);
541 $path = str_replace('{uri}', urlencode($url), $lrdd);
542 $webfinger2 = self::webfinger($path, $type);
544 // Is the new webfinger detectable as OStatus?
545 if (self::ostatus($webfinger2, true)) {
546 $webfinger = $webfinger2;
553 * Fetch information (protocol endpoints and user information) about a given uri
555 * This function is only called by the "uri" function that adds caching and rearranging of data.
557 * @param string $uri Address that should be probed
558 * @param string $network Test for this specific network
559 * @param integer $uid User ID for the probe (only used for mails)
561 * @return array uri data
562 * @throws HTTPException\InternalServerErrorException
564 private static function detect($uri, $network, $uid)
566 $parts = parse_url($uri);
568 if (!empty($parts["scheme"]) && !empty($parts["host"])) {
569 $host = $parts["host"];
570 if (!empty($parts["port"])) {
571 $host .= ':'.$parts["port"];
574 if ($host == 'twitter.com') {
575 return self::twitter($uri);
577 $lrdd = self::hostMeta($host);
579 if (is_bool($lrdd)) {
583 $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
585 while (!$lrdd && (sizeof($path_parts) > 1)) {
586 $host .= "/".array_shift($path_parts);
587 $lrdd = self::hostMeta($host);
590 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
591 return self::feed($uri);
593 $nick = array_pop($path_parts);
595 // Mastodon uses a "@" as prefix for usernames in their url format
596 $nick = ltrim($nick, '@');
598 $addr = $nick."@".$host;
599 } elseif (strstr($uri, '@')) {
600 // If the URI starts with "mailto:" then jump directly to the mail detection
601 if (strpos($uri, 'mailto:') !== false) {
602 $uri = str_replace('mailto:', '', $uri);
603 return self::mail($uri, $uid);
606 if ($network == Protocol::MAIL) {
607 return self::mail($uri, $uid);
609 // Remove "acct:" from the URI
610 $uri = str_replace('acct:', '', $uri);
612 $host = substr($uri, strpos($uri, '@') + 1);
613 $nick = substr($uri, 0, strpos($uri, '@'));
615 if (strpos($uri, '@twitter.com')) {
616 return self::twitter($uri);
618 $lrdd = self::hostMeta($host);
620 if (is_bool($lrdd)) {
625 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
626 return self::mail($uri, $uid);
630 Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
636 /// @todo Do we need the prefix "acct:" or "acct://"?
638 foreach ($lrdd as $type => $template) {
643 // At first try it with the given uri
644 $path = str_replace('{uri}', urlencode($uri), $template);
645 $webfinger = self::webfinger($path, $type);
647 // Fix possible problems with GNU Social probing to wrong scheme
648 $webfinger = self::fixOStatus($webfinger, $template, $type);
650 // We cannot be sure that the detected address was correct, so we don't use the values
651 if ($webfinger && ($uri != $addr)) {
656 // Try webfinger with the address (user@domain.tld)
658 $path = str_replace('{uri}', urlencode($addr), $template);
659 $webfinger = self::webfinger($path, $type);
662 // Mastodon needs to have it with "acct:"
664 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
665 $webfinger = self::webfinger($path, $type);
670 return self::feed($uri);
675 Logger::log("Probing ".$uri, Logger::DEBUG);
677 if (in_array($network, ["", Protocol::DFRN])) {
678 $result = self::dfrn($webfinger);
680 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
681 $result = self::diaspora($webfinger);
683 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
684 $result = self::ostatus($webfinger);
686 if (in_array($network, ['', Protocol::ZOT])) {
687 $result = self::zot($webfinger, $result);
689 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
690 $result = self::pumpio($webfinger, $addr);
692 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
693 $result = self::feed($uri);
695 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
696 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
697 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
698 $result["nick"] = $nick;
701 if (empty($result["addr"]) && ($addr != "")) {
702 $result["addr"] = $addr;
706 if (empty($result["network"])) {
707 $result["network"] = Protocol::PHANTOM;
710 if (empty($result["url"])) {
711 $result["url"] = $uri;
714 Logger::log($uri." is ".$result["network"], Logger::DEBUG);
716 if (empty($result["baseurl"]) && ($result["network"] != Protocol::PHANTOM)) {
717 $pos = strpos($result["url"], $host);
719 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
726 * Check for Zot contact
728 * @param array $webfinger Webfinger data
729 * @param array $data previously probed data
731 * @return array Zot data
732 * @throws HTTPException\InternalServerErrorException
734 private static function zot($webfinger, $data)
736 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
737 foreach ($webfinger["aliases"] as $alias) {
738 if (substr($alias, 0, 5) == 'acct:') {
739 $data["addr"] = substr($alias, 5);
744 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
745 $data["addr"] = substr($webfinger["subject"], 5);
749 foreach ($webfinger['links'] as $link) {
750 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
751 $zot_url = $link['href'];
755 if (empty($zot_url) && !empty($data['addr']) && !empty(self::$baseurl)) {
756 $condition = ['nurl' => Strings::normaliseLink(self::$baseurl), 'platform' => ['hubzilla']];
757 if (!DBA::exists('gserver', $condition)) {
760 $zot_url = self::$baseurl . '/.well-known/zot-info?address=' . $data['addr'];
763 if (empty($zot_url)) {
767 $data = self::pollZot($zot_url, $data);
769 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
770 foreach ($webfinger['aliases'] as $alias) {
771 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
772 $data['alias'] = $alias;
780 public static function pollZot($url, $data)
782 $curlResult = Network::curl($url);
783 if ($curlResult->isTimeout()) {
786 $content = $curlResult->getBody();
791 $json = json_decode($content, true);
792 if (!is_array($json)) {
796 if (empty($data['network'])) {
797 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
798 $data['network'] = Protocol::ZOT;
799 } elseif (!isset($json['protocols'])) {
800 $data['network'] = Protocol::ZOT;
804 if (!empty($json['guid']) && empty($data['guid'])) {
805 $data['guid'] = $json['guid'];
807 if (!empty($json['key']) && empty($data['pubkey'])) {
808 $data['pubkey'] = $json['key'];
810 if (!empty($json['name'])) {
811 $data['name'] = $json['name'];
813 if (!empty($json['photo'])) {
814 $data['photo'] = $json['photo'];
815 if (!empty($json['photo_updated'])) {
816 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
819 if (!empty($json['address'])) {
820 $data['addr'] = $json['address'];
822 if (!empty($json['url'])) {
823 $data['url'] = $json['url'];
825 if (!empty($json['connections_url'])) {
826 $data['poco'] = $json['connections_url'];
828 if (isset($json['searchable'])) {
829 $data['hide'] = !$json['searchable'];
831 if (!empty($json['public_forum'])) {
832 $data['community'] = $json['public_forum'];
833 $data['account-type'] = Contact::PAGE_COMMUNITY;
836 if (!empty($json['profile'])) {
837 $profile = $json['profile'];
838 if (!empty($profile['description'])) {
839 $data['about'] = $profile['description'];
841 if (!empty($profile['gender'])) {
842 $data['gender'] = $profile['gender'];
844 if (!empty($profile['keywords'])) {
845 $keywords = implode(', ', $profile['keywords']);
846 if (!empty($keywords)) {
847 $data['keywords'] = $keywords;
852 if (!empty($profile['region'])) {
853 $loc['region'] = $profile['region'];
855 if (!empty($profile['country'])) {
856 $loc['country-name'] = $profile['country'];
858 $location = Profile::formatLocation($loc);
859 if (!empty($location)) {
860 $data['location'] = $location;
868 * Perform a webfinger request.
870 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
872 * @param string $url Address that should be probed
873 * @param string $type type
875 * @return array webfinger data
876 * @throws HTTPException\InternalServerErrorException
878 private static function webfinger($url, $type)
880 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
882 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
883 if ($curlResult->isTimeout()) {
884 self::$istimeout = true;
887 $data = $curlResult->getBody();
889 $webfinger = json_decode($data, true);
890 if (is_array($webfinger)) {
891 if (!isset($webfinger["links"])) {
892 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
898 // If it is not JSON, maybe it is XML
899 $xrd = XML::parseString($data, false);
900 if (!is_object($xrd)) {
901 Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
905 $xrd_arr = XML::elementToArray($xrd);
906 if (!isset($xrd_arr["xrd"]["link"])) {
907 Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
913 if (!empty($xrd_arr["xrd"]["subject"])) {
914 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
917 if (!empty($xrd_arr["xrd"]["alias"])) {
918 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
921 $webfinger["links"] = [];
923 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
924 if (!empty($data["@attributes"])) {
925 $attributes = $data["@attributes"];
926 } elseif ($value == "@attributes") {
932 $webfinger["links"][] = $attributes;
938 * Poll the Friendica specific noscrape page.
940 * "noscrape" is a faster alternative to fetch the data from the hcard.
941 * This functionality was originally created for the directory.
943 * @param string $noscrape_url Link to the noscrape page
944 * @param array $data The already fetched data
946 * @return array noscrape data
947 * @throws HTTPException\InternalServerErrorException
949 private static function pollNoscrape($noscrape_url, $data)
951 $curlResult = Network::curl($noscrape_url);
952 if ($curlResult->isTimeout()) {
953 self::$istimeout = true;
956 $content = $curlResult->getBody();
958 Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
962 $json = json_decode($content, true);
963 if (!is_array($json)) {
964 Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
968 if (!empty($json["fn"])) {
969 $data["name"] = $json["fn"];
972 if (!empty($json["addr"])) {
973 $data["addr"] = $json["addr"];
976 if (!empty($json["nick"])) {
977 $data["nick"] = $json["nick"];
980 if (!empty($json["guid"])) {
981 $data["guid"] = $json["guid"];
984 if (!empty($json["comm"])) {
985 $data["community"] = $json["comm"];
988 if (!empty($json["tags"])) {
989 $keywords = implode(", ", $json["tags"]);
990 if ($keywords != "") {
991 $data["keywords"] = $keywords;
995 $location = Profile::formatLocation($json);
997 $data["location"] = $location;
1000 if (!empty($json["about"])) {
1001 $data["about"] = $json["about"];
1004 if (!empty($json["gender"])) {
1005 $data["gender"] = $json["gender"];
1008 if (!empty($json["key"])) {
1009 $data["pubkey"] = $json["key"];
1012 if (!empty($json["photo"])) {
1013 $data["photo"] = $json["photo"];
1016 if (!empty($json["dfrn-request"])) {
1017 $data["request"] = $json["dfrn-request"];
1020 if (!empty($json["dfrn-confirm"])) {
1021 $data["confirm"] = $json["dfrn-confirm"];
1024 if (!empty($json["dfrn-notify"])) {
1025 $data["notify"] = $json["dfrn-notify"];
1028 if (!empty($json["dfrn-poll"])) {
1029 $data["poll"] = $json["dfrn-poll"];
1032 if (isset($json["hide"])) {
1033 $data["hide"] = (bool)$json["hide"];
1035 $data["hide"] = false;
1042 * Check for valid DFRN data
1044 * @param array $data DFRN data
1046 * @return int Number of errors
1048 public static function validDfrn($data)
1051 if (!isset($data['key'])) {
1054 if (!isset($data['dfrn-request'])) {
1057 if (!isset($data['dfrn-confirm'])) {
1060 if (!isset($data['dfrn-notify'])) {
1063 if (!isset($data['dfrn-poll'])) {
1070 * Fetch data from a DFRN profile page and via "noscrape"
1072 * @param string $profile_link Link to the profile page
1074 * @return array profile data
1075 * @throws HTTPException\InternalServerErrorException
1076 * @throws \ImagickException
1078 public static function profile($profile_link)
1082 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
1084 // Fetch data via noscrape - this is faster
1085 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1086 $data = self::pollNoscrape($noscrape_url, $data);
1088 if (!isset($data["notify"])
1089 || !isset($data["confirm"])
1090 || !isset($data["request"])
1091 || !isset($data["poll"])
1092 || !isset($data["name"])
1093 || !isset($data["photo"])
1095 $data = self::pollHcard($profile_link, $data, true);
1100 if (empty($data["addr"]) || empty($data["nick"])) {
1101 $probe_data = self::uri($profile_link);
1102 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1103 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1106 $prof_data["addr"] = $data["addr"];
1107 $prof_data["nick"] = $data["nick"];
1108 $prof_data["dfrn-request"] = $data['request'] ?? null;
1109 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1110 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1111 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1112 $prof_data["photo"] = $data['photo'] ?? null;
1113 $prof_data["fn"] = $data['name'] ?? null;
1114 $prof_data["key"] = $data['pubkey'] ?? null;
1116 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
1122 * Check for DFRN contact
1124 * @param array $webfinger Webfinger data
1126 * @return array DFRN data
1127 * @throws HTTPException\InternalServerErrorException
1129 private static function dfrn($webfinger)
1133 // The array is reversed to take into account the order of preference for same-rel links
1134 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1135 foreach (array_reverse($webfinger["links"]) as $link) {
1136 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1137 $data["network"] = Protocol::DFRN;
1138 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1139 $data["poll"] = $link["href"];
1140 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1141 $data["url"] = $link["href"];
1142 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1143 $hcard_url = $link["href"];
1144 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1145 $data["poco"] = $link["href"];
1146 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1147 $data["photo"] = $link["href"];
1148 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1149 $data["baseurl"] = trim($link["href"], '/');
1150 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1151 $data["guid"] = $link["href"];
1152 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1153 $data["pubkey"] = base64_decode($link["href"]);
1155 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1156 if (strstr($data["pubkey"], 'RSA ')) {
1157 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1162 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1163 foreach ($webfinger["aliases"] as $alias) {
1164 if (empty($data["url"]) && !strstr($alias, "@")) {
1165 $data["url"] = $alias;
1166 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1167 $data["alias"] = $alias;
1168 } elseif (substr($alias, 0, 5) == 'acct:') {
1169 $data["addr"] = substr($alias, 5);
1174 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1175 $data["addr"] = substr($webfinger["subject"], 5);
1178 if (!isset($data["network"]) || ($hcard_url == "")) {
1182 // Fetch data via noscrape - this is faster
1183 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1184 $data = self::pollNoscrape($noscrape_url, $data);
1186 if (isset($data["notify"])
1187 && isset($data["confirm"])
1188 && isset($data["request"])
1189 && isset($data["poll"])
1190 && isset($data["name"])
1191 && isset($data["photo"])
1196 $data = self::pollHcard($hcard_url, $data, true);
1202 * Poll the hcard page (Diaspora and Friendica specific)
1204 * @param string $hcard_url Link to the hcard page
1205 * @param array $data The already fetched data
1206 * @param boolean $dfrn Poll DFRN specific data
1208 * @return array hcard data
1209 * @throws HTTPException\InternalServerErrorException
1211 private static function pollHcard($hcard_url, $data, $dfrn = false)
1213 $curlResult = Network::curl($hcard_url);
1214 if ($curlResult->isTimeout()) {
1215 self::$istimeout = true;
1218 $content = $curlResult->getBody();
1223 $doc = new DOMDocument();
1224 if (!@$doc->loadHTML($content)) {
1228 $xpath = new DomXPath($doc);
1230 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1231 if (!is_object($vcards)) {
1235 if (!isset($data["baseurl"])) {
1236 $data["baseurl"] = "";
1239 if ($vcards->length > 0) {
1240 $vcard = $vcards->item(0);
1242 // We have to discard the guid from the hcard in favour of the guid from lrdd
1243 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1244 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1245 if (($search->length > 0) && empty($data["guid"])) {
1246 $data["guid"] = $search->item(0)->nodeValue;
1249 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1250 if ($search->length > 0) {
1251 $data["nick"] = $search->item(0)->nodeValue;
1254 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1255 if ($search->length > 0) {
1256 $data["name"] = $search->item(0)->nodeValue;
1259 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1260 if ($search->length > 0) {
1261 $data["searchable"] = $search->item(0)->nodeValue;
1264 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1265 if ($search->length > 0) {
1266 $data["pubkey"] = $search->item(0)->nodeValue;
1267 if (strstr($data["pubkey"], 'RSA ')) {
1268 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1272 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1273 if ($search->length > 0) {
1274 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1279 if (!empty($vcard)) {
1280 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1281 foreach ($photos as $photo) {
1283 foreach ($photo->attributes as $attribute) {
1284 $attr[$attribute->name] = trim($attribute->value);
1287 if (isset($attr["src"]) && isset($attr["width"])) {
1288 $avatar[$attr["width"]] = $attr["src"];
1291 // We don't have a width. So we just take everything that we got.
1292 // This is a Hubzilla workaround which doesn't send a width.
1293 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1294 $avatar[] = $attr["src"];
1299 if (sizeof($avatar)) {
1301 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1305 // Poll DFRN specific data
1306 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1307 if ($search->length > 0) {
1308 foreach ($search as $link) {
1309 //$data["request"] = $search->item(0)->nodeValue;
1311 foreach ($link->attributes as $attribute) {
1312 $attr[$attribute->name] = trim($attribute->value);
1315 $data[substr($attr["rel"], 5)] = $attr["href"];
1319 // Older Friendica versions had used the "uid" field differently than newer versions
1320 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1321 unset($data["guid"]);
1330 * Check for Diaspora contact
1332 * @param array $webfinger Webfinger data
1334 * @return array Diaspora data
1335 * @throws HTTPException\InternalServerErrorException
1337 private static function diaspora($webfinger)
1342 // The array is reversed to take into account the order of preference for same-rel links
1343 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1344 foreach (array_reverse($webfinger["links"]) as $link) {
1345 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1346 $hcard_url = $link["href"];
1347 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1348 $data["baseurl"] = trim($link["href"], '/');
1349 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1350 $data["guid"] = $link["href"];
1351 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1352 $data["url"] = $link["href"];
1353 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1354 $data["poll"] = $link["href"];
1355 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1356 $data["poco"] = $link["href"];
1357 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1358 $data["notify"] = $link["href"];
1359 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1360 $data["pubkey"] = base64_decode($link["href"]);
1362 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1363 if (strstr($data["pubkey"], 'RSA ')) {
1364 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1369 if (empty($data["url"]) || empty($hcard_url)) {
1373 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1374 foreach ($webfinger["aliases"] as $alias) {
1375 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1376 $data["alias"] = $alias;
1377 } elseif (substr($alias, 0, 5) == 'acct:') {
1378 $data["addr"] = substr($alias, 5);
1383 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1384 $data["addr"] = substr($webfinger["subject"], 5);
1387 // Fetch further information from the hcard
1388 $data = self::pollHcard($hcard_url, $data);
1394 if (!empty($data["url"])
1395 && !empty($data["guid"])
1396 && !empty($data["baseurl"])
1397 && !empty($data["pubkey"])
1398 && !empty($hcard_url)
1400 $data["network"] = Protocol::DIASPORA;
1402 // The Diaspora handle must always be lowercase
1403 if (!empty($data["addr"])) {
1404 $data["addr"] = strtolower($data["addr"]);
1407 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1408 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1409 $data["batch"] = $data["baseurl"] . "/receive/public";
1418 * Check for OStatus contact
1420 * @param array $webfinger Webfinger data
1421 * @param bool $short Short detection mode
1423 * @return array|bool OStatus data or "false" on error or "true" on short mode
1424 * @throws HTTPException\InternalServerErrorException
1426 private static function ostatus($webfinger, $short = false)
1430 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1431 foreach ($webfinger["aliases"] as $alias) {
1432 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1433 $data["addr"] = str_replace('acct:', '', $alias);
1438 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1439 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1441 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1444 if (is_array($webfinger["links"])) {
1445 // The array is reversed to take into account the order of preference for same-rel links
1446 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1447 foreach (array_reverse($webfinger["links"]) as $link) {
1448 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1449 && (($link["type"] ?? "") == "text/html")
1450 && ($link["href"] != "")
1452 $data["url"] = $link["href"];
1453 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1454 $data["notify"] = $link["href"];
1455 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1456 $data["poll"] = $link["href"];
1457 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1458 $pubkey = $link["href"];
1460 if (substr($pubkey, 0, 5) === 'data:') {
1461 if (strstr($pubkey, ',')) {
1462 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1464 $pubkey = substr($pubkey, 5);
1466 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1467 $curlResult = Network::curl($pubkey);
1468 if ($curlResult->isTimeout()) {
1469 self::$istimeout = true;
1472 $pubkey = $curlResult->getBody();
1475 $key = explode(".", $pubkey);
1477 if (sizeof($key) >= 3) {
1478 $m = Strings::base64UrlDecode($key[1]);
1479 $e = Strings::base64UrlDecode($key[2]);
1480 $data["pubkey"] = Crypto::meToPem($m, $e);
1486 if (isset($data["notify"]) && isset($data["pubkey"])
1487 && isset($data["poll"])
1488 && isset($data["url"])
1490 $data["network"] = Protocol::OSTATUS;
1499 // Fetch all additional data from the feed
1500 $curlResult = Network::curl($data["poll"]);
1501 if ($curlResult->isTimeout()) {
1502 self::$istimeout = true;
1505 $feed = $curlResult->getBody();
1506 $feed_data = Feed::import($feed);
1511 if (!empty($feed_data["header"]["author-name"])) {
1512 $data["name"] = $feed_data["header"]["author-name"];
1514 if (!empty($feed_data["header"]["author-nick"])) {
1515 $data["nick"] = $feed_data["header"]["author-nick"];
1517 if (!empty($feed_data["header"]["author-avatar"])) {
1518 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1520 if (!empty($feed_data["header"]["author-id"])) {
1521 $data["alias"] = $feed_data["header"]["author-id"];
1523 if (!empty($feed_data["header"]["author-location"])) {
1524 $data["location"] = $feed_data["header"]["author-location"];
1526 if (!empty($feed_data["header"]["author-about"])) {
1527 $data["about"] = $feed_data["header"]["author-about"];
1529 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1530 // So we take the value that we just fetched, although the other one worked as well
1531 if (!empty($feed_data["header"]["author-link"])) {
1532 $data["url"] = $feed_data["header"]["author-link"];
1535 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1536 $data['url'] = $data["alias"];
1537 $data["alias"] = '';
1540 /// @todo Fetch location and "about" from the feed as well
1545 * Fetch data from a pump.io profile page
1547 * @param string $profile_link Link to the profile page
1549 * @return array profile data
1551 private static function pumpioProfileData($profile_link)
1553 $curlResult = Network::curl($profile_link);
1554 if (!$curlResult->isSuccess()) {
1558 $doc = new DOMDocument();
1559 if (!@$doc->loadHTML($curlResult->getBody())) {
1563 $xpath = new DomXPath($doc);
1567 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1569 if ($data["name"] == '') {
1570 // This is ugly - but pump.io doesn't seem to know a better way for it
1571 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1572 $pos = strpos($data["name"], chr(10));
1574 $data["name"] = trim(substr($data["name"], 0, $pos));
1578 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1580 if ($data["location"] == '') {
1581 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1584 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1586 if ($data["about"] == '') {
1587 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1590 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1592 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1595 foreach ($avatar->attributes as $attribute) {
1596 if ($attribute->name == "src") {
1597 $data["photo"] = trim($attribute->value);
1606 * Check for pump.io contact
1608 * @param array $webfinger Webfinger data
1609 * @param string $addr
1610 * @return array pump.io data
1612 private static function pumpio($webfinger, $addr)
1615 // The array is reversed to take into account the order of preference for same-rel links
1616 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1617 foreach (array_reverse($webfinger["links"]) as $link) {
1618 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1619 && (($link["type"] ?? "") == "text/html")
1620 && ($link["href"] != "")
1622 $data["url"] = $link["href"];
1623 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1624 $data["notify"] = $link["href"];
1625 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1626 $data["poll"] = $link["href"];
1627 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1628 $data["dialback"] = $link["href"];
1631 if (isset($data["poll"]) && isset($data["notify"])
1632 && isset($data["dialback"])
1633 && isset($data["url"])
1635 // by now we use these fields only for the network type detection
1636 // So we unset all data that isn't used at the moment
1637 unset($data["dialback"]);
1639 $data["network"] = Protocol::PUMPIO;
1644 $profile_data = self::pumpioProfileData($data["url"]);
1646 if (!$profile_data) {
1650 $data = array_merge($data, $profile_data);
1652 if (($addr != '') && ($data['name'] != '')) {
1653 $name = trim(str_replace($addr, '', $data['name']));
1655 $data['name'] = $name;
1663 * Check for twitter contact
1665 * @param string $uri
1667 * @return array twitter data
1669 private static function twitter($uri)
1671 if (preg_match('=(.*)@twitter.com=i', $uri, $matches)) {
1672 $nick = $matches[1];
1673 } elseif (preg_match('=https?://twitter.com/(.*)=i', $uri, $matches)) {
1674 $nick = $matches[1];
1680 $data['url'] = 'https://twitter.com/' . $nick;
1681 $data['addr'] = $nick . '@twitter.com';
1682 $data['nick'] = $data['name'] = $nick;
1683 $data['network'] = Protocol::TWITTER;
1684 $data['baseurl'] = 'https://twitter.com';
1686 $curlResult = Network::curl($data['url'], false);
1687 if (!$curlResult->isSuccess()) {
1691 $body = $curlResult->getBody();
1692 $doc = new DOMDocument();
1693 @$doc->loadHTML($body);
1694 $xpath = new DOMXPath($doc);
1696 $list = $xpath->query('//img[@class]');
1697 foreach ($list as $node) {
1699 if ($node->attributes->length) {
1700 foreach ($node->attributes as $attribute) {
1701 $img_attr[$attribute->name] = $attribute->value;
1705 if (empty($img_attr['class'])) {
1709 if (strpos($img_attr['class'], 'ProfileAvatar-image') !== false) {
1710 if (!empty($img_attr['src'])) {
1711 $data['photo'] = $img_attr['src'];
1713 if (!empty($img_attr['alt'])) {
1714 $data['name'] = $img_attr['alt'];
1723 * Check page for feed link
1725 * @param string $url Page link
1727 * @return string feed link
1729 private static function getFeedLink($url)
1731 $curlResult = Network::curl($url);
1732 if (!$curlResult->isSuccess()) {
1736 $doc = new DOMDocument();
1737 if (!@$doc->loadHTML($curlResult->getBody())) {
1741 $xpath = new DomXPath($doc);
1743 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1744 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1745 if (!is_object($feeds)) {
1749 if ($feeds->length == 0) {
1755 foreach ($feeds as $feed) {
1757 foreach ($feed->attributes as $attribute) {
1758 $attr[$attribute->name] = trim($attribute->value);
1761 if (empty($feed_url) && !empty($attr['href'])) {
1762 $feed_url = $attr["href"];
1770 * Check for feed contact
1772 * @param string $url Profile link
1773 * @param boolean $probe Do a probe if the page contains a feed link
1775 * @return array feed data
1776 * @throws HTTPException\InternalServerErrorException
1778 private static function feed($url, $probe = true)
1780 $curlResult = Network::curl($url);
1781 if ($curlResult->isTimeout()) {
1782 self::$istimeout = true;
1785 $feed = $curlResult->getBody();
1786 $feed_data = Feed::import($feed);
1793 $feed_url = self::getFeedLink($url);
1799 return self::feed($feed_url, false);
1802 if (!empty($feed_data["header"]["author-name"])) {
1803 $data["name"] = $feed_data["header"]["author-name"];
1806 if (!empty($feed_data["header"]["author-nick"])) {
1807 $data["nick"] = $feed_data["header"]["author-nick"];
1810 if (!empty($feed_data["header"]["author-avatar"])) {
1811 $data["photo"] = $feed_data["header"]["author-avatar"];
1814 if (!empty($feed_data["header"]["author-id"])) {
1815 $data["alias"] = $feed_data["header"]["author-id"];
1818 $data["url"] = $url;
1819 $data["poll"] = $url;
1821 if (!empty($feed_data["header"]["author-link"])) {
1822 $data["baseurl"] = $feed_data["header"]["author-link"];
1824 $data["baseurl"] = $data["url"];
1827 $data["network"] = Protocol::FEED;
1833 * Check for mail contact
1835 * @param string $uri Profile link
1836 * @param integer $uid User ID
1838 * @return array mail data
1839 * @throws \Exception
1841 private static function mail($uri, $uid)
1843 if (!Network::isEmailDomainValid($uri)) {
1851 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1853 $condition = ["`uid` = ? AND `server` != ''", $uid];
1854 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1855 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1857 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1861 $mailbox = Email::constructMailboxName($mailacct);
1863 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1864 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1869 $msgs = Email::poll($mbox, $uri);
1870 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1872 if (!count($msgs)) {
1876 $phost = substr($uri, strpos($uri, '@') + 1);
1879 $data["addr"] = $uri;
1880 $data["network"] = Protocol::MAIL;
1881 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1882 $data["nick"] = $data["name"];
1883 $data["photo"] = Network::lookupAvatarByEmail($uri);
1884 $data["url"] = 'mailto:'.$uri;
1885 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1886 $data["poll"] = 'email ' . Strings::getRandomHex();
1888 $x = Email::messageMeta($mbox, $msgs[0]);
1889 if (stristr($x[0]->from, $uri)) {
1890 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1891 } elseif (stristr($x[0]->to, $uri)) {
1892 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1895 foreach ($adr as $feadr) {
1896 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1897 &&(strcasecmp($feadr->host, $phost) == 0)
1898 && (strlen($feadr->personal))
1900 $personal = imap_mime_header_decode($feadr->personal);
1902 foreach ($personal as $perspart) {
1903 if ($perspart->charset != "default") {
1904 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1906 $data["name"] .= $perspart->text;
1910 $data["name"] = Strings::escapeTags($data["name"]);
1914 if (!empty($mbox)) {
1921 * Mix two paths together to possibly fix missing parts
1923 * @param string $avatar Path to the avatar
1924 * @param string $base Another path that is hopefully complete
1926 * @return string fixed avatar path
1927 * @throws \Exception
1929 public static function fixAvatar($avatar, $base)
1931 $base_parts = parse_url($base);
1933 // Remove all parts that could create a problem
1934 unset($base_parts['path']);
1935 unset($base_parts['query']);
1936 unset($base_parts['fragment']);
1938 $avatar_parts = parse_url($avatar);
1941 $parts = array_merge($base_parts, $avatar_parts);
1943 // And put them together again
1944 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1945 $host = isset($parts['host']) ? $parts['host'] : '';
1946 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1947 $path = isset($parts['path']) ? $parts['path'] : '';
1948 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1949 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1951 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1953 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);