3 * @file src/Network/Probe.php
5 namespace Friendica\Network;
8 * @file src/Network/Probe.php
9 * @brief Functions for probing URL
14 use Friendica\Core\Cache\Cache;
15 use Friendica\Core\Config;
16 use Friendica\Core\Logger;
17 use Friendica\Core\Protocol;
18 use Friendica\Database\DBA;
20 use Friendica\Model\Contact;
21 use Friendica\Model\Profile;
22 use Friendica\Protocol\ActivityNamespace;
23 use Friendica\Protocol\ActivityPub;
24 use Friendica\Protocol\Email;
25 use Friendica\Protocol\Feed;
26 use Friendica\Util\Crypto;
27 use Friendica\Util\Network;
28 use Friendica\Util\Strings;
29 use Friendica\Util\XML;
32 * @brief This class contain functions for probing URL
37 private static $baseurl;
38 private static $istimeout;
41 * @brief Rearrange the array so that it always has the same order
43 * @param array $data Unordered data
45 * @return array Ordered data
47 private static function rearrangeData($data)
49 $fields = ["name", "nick", "guid", "url", "addr", "alias", "photo", "account-type",
50 "community", "keywords", "location", "about", "gender", "hide",
51 "batch", "notify", "poll", "request", "confirm", "poco",
52 "following", "followers", "inbox", "outbox", "sharedinbox",
53 "priority", "network", "pubkey", "baseurl"];
56 foreach ($fields as $field) {
57 if (isset($data[$field])) {
58 $newdata[$field] = $data[$field];
60 $newdata[$field] = "";
64 // We don't use the "priority" field anymore and replace it with a dummy.
65 $newdata["priority"] = 0;
71 * @brief Check if the hostname belongs to the own server
73 * @param string $host The hostname that is to be checked
75 * @return bool Does the testes hostname belongs to the own server?
77 private static function ownHost($host)
79 $own_host = DI::baseUrl()->getHostname();
81 $parts = parse_url($host);
83 if (!isset($parts['scheme'])) {
84 $parts = parse_url('http://'.$host);
87 if (!isset($parts['host'])) {
90 return $parts['host'] == $own_host;
94 * @brief Probes for webfinger path via "host-meta"
96 * We have to check if the servers in the future still will offer this.
97 * It seems as if it was dropped from the standard.
99 * @param string $host The host part of an url
101 * @return array with template and type of the webfinger template for JSON or XML
102 * @throws HTTPException\InternalServerErrorException
104 private static function hostMeta($host)
106 // Reset the static variable
109 $ssl_url = "https://".$host."/.well-known/host-meta";
110 $url = "http://".$host."/.well-known/host-meta";
112 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
114 Logger::log("Probing for ".$host, Logger::DEBUG);
117 $curlResult = Network::curl($ssl_url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
118 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
119 if ($curlResult->isSuccess()) {
120 $xml = $curlResult->getBody();
121 $xrd = XML::parseString($xml, false);
122 $host_url = 'https://'.$host;
123 } elseif ($curlResult->isTimeout()) {
124 Logger::info('Probing timeout', ['url' => $ssl_url], Logger::DEBUG);
125 self::$istimeout = true;
129 if (!is_object($xrd)) {
130 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
131 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
132 if ($curlResult->isTimeout()) {
133 Logger::info('Probing timeout', ['url' => $url], Logger::DEBUG);
134 self::$istimeout = true;
136 } elseif ($connection_error && $ssl_connection_error) {
137 self::$istimeout = true;
141 $xml = $curlResult->getBody();
142 $xrd = XML::parseString($xml, false);
143 $host_url = 'http://'.$host;
145 if (!is_object($xrd)) {
146 Logger::log("No xrd object found for ".$host, Logger::DEBUG);
150 $links = XML::elementToArray($xrd);
151 if (!isset($links["xrd"]["link"])) {
152 Logger::log("No xrd data found for ".$host, Logger::DEBUG);
156 $lrdd = ['application/jrd+json' => $host_url . '/.well-known/webfinger?resource={uri}'];
158 foreach ($links["xrd"]["link"] as $value => $link) {
159 if (!empty($link["@attributes"])) {
160 $attributes = $link["@attributes"];
161 } elseif ($value == "@attributes") {
167 if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
168 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
170 $lrdd[$type] = $attributes["template"];
174 self::$baseurl = $host_url;
176 Logger::log("Probing successful for ".$host, Logger::DEBUG);
182 * @brief Perform Webfinger lookup and return DFRN data
184 * Given an email style address, perform webfinger lookup and
185 * return the resulting DFRN profile URL, or if no DFRN profile URL
186 * is located, returns an OStatus subscription template (prefixed
187 * with the string 'stat:' to identify it as on OStatus template).
188 * If this isn't an email style address just return $webbie.
189 * Return an empty string if email-style addresses but webfinger fails,
190 * or if the resultant personal XRD doesn't contain a supported
191 * subscription/friend-request attribute.
193 * amended 7/9/2011 to return an hcard which could save potentially loading
194 * a lengthy content page to scrape dfrn attributes
196 * @param string $webbie Address that should be probed
197 * @param string $hcard_url Link to the hcard - is returned by reference
199 * @return string profile link
200 * @throws HTTPException\InternalServerErrorException
202 public static function webfingerDfrn($webbie, &$hcard_url)
206 $links = self::lrdd($webbie);
207 Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA);
208 if (!empty($links) && is_array($links)) {
209 foreach ($links as $link) {
210 if ($link['@attributes']['rel'] === ActivityNamespace::DFRN) {
211 $profile_link = $link['@attributes']['href'];
213 if (($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) && ($profile_link == "")) {
214 $profile_link = 'stat:'.$link['@attributes']['template'];
216 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
217 $hcard_url = $link['@attributes']['href'];
221 return $profile_link;
225 * @brief Check an URI for LRDD data
227 * this is a replacement for the "lrdd" function.
228 * It isn't used in this class and has some redundancies in the code.
229 * When time comes we can check the existing calls for "lrdd" if we can rework them.
231 * @param string $uri Address that should be probed
233 * @return array uri data
234 * @throws HTTPException\InternalServerErrorException
236 public static function lrdd($uri)
238 $lrdd = self::hostMeta($uri);
241 if (is_bool($lrdd)) {
246 $parts = @parse_url($uri);
247 if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
251 $host = $parts["host"];
252 if (!empty($parts["port"])) {
253 $host .= ':'.$parts["port"];
256 $path_parts = explode("/", trim($parts["path"], "/"));
258 $nick = array_pop($path_parts);
261 $lrdd = self::hostMeta($host);
262 $host .= "/".array_shift($path_parts);
263 } while (!$lrdd && (sizeof($path_parts) > 0));
267 Logger::log("No lrdd data found for ".$uri, Logger::DEBUG);
271 foreach ($lrdd as $type => $template) {
276 $path = str_replace('{uri}', urlencode($uri), $template);
277 $webfinger = self::webfinger($path, $type);
279 if (!$webfinger && (strstr($uri, "@"))) {
280 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
281 $webfinger = self::webfinger($path, $type);
284 // Special treatment for Mastodon
285 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
286 // But the webfinger for this format fails.
287 if (!$webfinger && !empty($nick)) {
288 // Mastodon uses a "@" as prefix for usernames in their url format
289 $nick = ltrim($nick, '@');
291 $addr = $nick."@".$host;
293 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
294 $webfinger = self::webfinger($path, $type);
298 if (!is_array($webfinger["links"])) {
299 Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
305 foreach ($webfinger["links"] as $link) {
306 $data[] = ["@attributes" => $link];
309 if (is_array($webfinger["aliases"])) {
310 foreach ($webfinger["aliases"] as $alias) {
311 $data[] = ["@attributes" =>
321 * @brief Fetch information (protocol endpoints and user information) about a given uri
323 * @param string $uri Address that should be probed
324 * @param string $network Test for this specific network
325 * @param integer $uid User ID for the probe (only used for mails)
326 * @param boolean $cache Use cached values?
328 * @return array uri data
329 * @throws HTTPException\InternalServerErrorException
330 * @throws \ImagickException
332 public static function uri($uri, $network = '', $uid = -1, $cache = true)
335 $result = DI::cache()->get('Probe::uri:' . $network . ':' . $uri);
336 if (!is_null($result)) {
345 self::$istimeout = false;
347 if ($network != Protocol::ACTIVITYPUB) {
348 $data = self::detect($uri, $network, $uid);
353 // When the previous detection process had got a time out
354 // we could falsely detect a Friendica profile as AP profile.
355 if (!self::$istimeout) {
356 $ap_profile = ActivityPub::probeProfile($uri);
358 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
360 } elseif (!empty($ap_profile)) {
361 $ap_profile['batch'] = '';
362 $data = array_merge($ap_profile, $data);
365 Logger::notice('Time out detected. AP will not be probed.', ['uri' => $uri]);
368 if (!isset($data['url'])) {
372 if (!empty($data['photo']) && !empty($data['baseurl'])) {
373 $data['baseurl'] = Network::getUrlMatch(Strings::normaliseLink($data['baseurl']), Strings::normaliseLink($data['photo']));
374 } elseif (empty($data['photo'])) {
375 $data['photo'] = DI::baseUrl() . '/images/person-300.jpg';
378 if (empty($data['name'])) {
379 if (!empty($data['nick'])) {
380 $data['name'] = $data['nick'];
383 if (empty($data['name'])) {
384 $data['name'] = $data['url'];
388 if (empty($data['nick'])) {
389 $data['nick'] = strtolower($data['name']);
391 if (strpos($data['nick'], ' ')) {
392 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
396 if (!empty(self::$baseurl)) {
397 $data['baseurl'] = self::$baseurl;
400 if (empty($data['network'])) {
401 $data['network'] = Protocol::PHANTOM;
404 // Ensure that local connections always are DFRN
405 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
406 $data['network'] = Protocol::DFRN;
409 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
410 $data['hide'] = self::getHideStatus($data['url']);
413 $data = self::rearrangeData($data);
415 // Only store into the cache if the value seems to be valid
416 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
417 DI::cache()->set('Probe::uri:' . $network . ':' . $uri, $data, Cache::DAY);
425 * Fetches the "hide" status from the profile
427 * @param string $url URL of the profile
429 * @return boolean "hide" status
431 private static function getHideStatus($url)
433 $curlResult = Network::curl($url);
434 if (!$curlResult->isSuccess()) {
438 // If the file is too large then exit
439 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
443 // If it isn't a HTML file then exit
444 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
448 $body = $curlResult->getBody();
450 $doc = new DOMDocument();
451 @$doc->loadHTML($body);
453 $xpath = new DOMXPath($doc);
455 $list = $xpath->query('//meta[@name]');
456 foreach ($list as $node) {
458 if ($node->attributes->length) {
459 foreach ($node->attributes as $attribute) {
460 $meta_tag[$attribute->name] = $attribute->value;
464 if (empty($meta_tag['content'])) {
468 $content = strtolower(trim($meta_tag['content']));
470 switch (strtolower(trim($meta_tag['name']))) {
471 case 'dfrn-global-visibility':
472 if ($content == 'false') {
477 if (strpos($content, 'noindex') !== false) {
488 * @brief Checks if a profile url should be OStatus but only provides partial information
490 * @param array $webfinger Webfinger data
491 * @param string $lrdd Path template for webfinger request
492 * @param string $type type
494 * @return array fixed webfinger data
495 * @throws HTTPException\InternalServerErrorException
497 private static function fixOStatus($webfinger, $lrdd, $type)
499 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
506 foreach ($webfinger['links'] as $link) {
507 if ($link['rel'] == ActivityNamespace::OSTATUSSUB) {
510 if ($link['rel'] == 'magic-public-key') {
515 if (!$is_ostatus || $has_key) {
519 $url = Network::switchScheme($webfinger['subject']);
520 $path = str_replace('{uri}', urlencode($url), $lrdd);
521 $webfinger2 = self::webfinger($path, $type);
523 // Is the new webfinger detectable as OStatus?
524 if (self::ostatus($webfinger2, true)) {
525 $webfinger = $webfinger2;
532 * @brief Fetch information (protocol endpoints and user information) about a given uri
534 * This function is only called by the "uri" function that adds caching and rearranging of data.
536 * @param string $uri Address that should be probed
537 * @param string $network Test for this specific network
538 * @param integer $uid User ID for the probe (only used for mails)
540 * @return array uri data
541 * @throws HTTPException\InternalServerErrorException
543 private static function detect($uri, $network, $uid)
545 $parts = parse_url($uri);
547 if (!empty($parts["scheme"]) && !empty($parts["host"])) {
548 $host = $parts["host"];
549 if (!empty($parts["port"])) {
550 $host .= ':'.$parts["port"];
553 if ($host == 'twitter.com') {
554 return self::twitter($uri);
556 $lrdd = self::hostMeta($host);
558 if (is_bool($lrdd)) {
562 $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
564 while (!$lrdd && (sizeof($path_parts) > 1)) {
565 $host .= "/".array_shift($path_parts);
566 $lrdd = self::hostMeta($host);
569 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
570 return self::feed($uri);
572 $nick = array_pop($path_parts);
574 // Mastodon uses a "@" as prefix for usernames in their url format
575 $nick = ltrim($nick, '@');
577 $addr = $nick."@".$host;
578 } elseif (strstr($uri, '@')) {
579 // If the URI starts with "mailto:" then jump directly to the mail detection
580 if (strpos($uri, 'mailto:') !== false) {
581 $uri = str_replace('mailto:', '', $uri);
582 return self::mail($uri, $uid);
585 if ($network == Protocol::MAIL) {
586 return self::mail($uri, $uid);
588 // Remove "acct:" from the URI
589 $uri = str_replace('acct:', '', $uri);
591 $host = substr($uri, strpos($uri, '@') + 1);
592 $nick = substr($uri, 0, strpos($uri, '@'));
594 if (strpos($uri, '@twitter.com')) {
595 return self::twitter($uri);
597 $lrdd = self::hostMeta($host);
599 if (is_bool($lrdd)) {
604 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
605 return self::mail($uri, $uid);
609 Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
615 /// @todo Do we need the prefix "acct:" or "acct://"?
617 foreach ($lrdd as $type => $template) {
622 // At first try it with the given uri
623 $path = str_replace('{uri}', urlencode($uri), $template);
624 $webfinger = self::webfinger($path, $type);
626 // Fix possible problems with GNU Social probing to wrong scheme
627 $webfinger = self::fixOStatus($webfinger, $template, $type);
629 // We cannot be sure that the detected address was correct, so we don't use the values
630 if ($webfinger && ($uri != $addr)) {
635 // Try webfinger with the address (user@domain.tld)
637 $path = str_replace('{uri}', urlencode($addr), $template);
638 $webfinger = self::webfinger($path, $type);
641 // Mastodon needs to have it with "acct:"
643 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
644 $webfinger = self::webfinger($path, $type);
649 return self::feed($uri);
654 Logger::log("Probing ".$uri, Logger::DEBUG);
656 if (in_array($network, ["", Protocol::DFRN])) {
657 $result = self::dfrn($webfinger);
659 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
660 $result = self::diaspora($webfinger);
662 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
663 $result = self::ostatus($webfinger);
665 if (in_array($network, ['', Protocol::ZOT])) {
666 $result = self::zot($webfinger, $result);
668 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
669 $result = self::pumpio($webfinger, $addr);
671 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
672 $result = self::feed($uri);
674 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
675 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
676 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
677 $result["nick"] = $nick;
680 if (empty($result["addr"]) && ($addr != "")) {
681 $result["addr"] = $addr;
685 if (empty($result["network"])) {
686 $result["network"] = Protocol::PHANTOM;
689 if (empty($result["url"])) {
690 $result["url"] = $uri;
693 Logger::log($uri." is ".$result["network"], Logger::DEBUG);
695 if (empty($result["baseurl"]) && ($result["network"] != Protocol::PHANTOM)) {
696 $pos = strpos($result["url"], $host);
698 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
705 * Check for Zot contact
707 * @param array $webfinger Webfinger data
708 * @param array $data previously probed data
710 * @return array Zot data
711 * @throws HTTPException\InternalServerErrorException
713 private static function zot($webfinger, $data)
715 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
716 foreach ($webfinger["aliases"] as $alias) {
717 if (substr($alias, 0, 5) == 'acct:') {
718 $data["addr"] = substr($alias, 5);
723 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
724 $data["addr"] = substr($webfinger["subject"], 5);
728 foreach ($webfinger['links'] as $link) {
729 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
730 $zot_url = $link['href'];
734 if (empty($zot_url) && !empty($data['addr']) && !empty(self::$baseurl)) {
735 $condition = ['nurl' => Strings::normaliseLink(self::$baseurl), 'platform' => ['hubzilla']];
736 if (!DBA::exists('gserver', $condition)) {
739 $zot_url = self::$baseurl . '/.well-known/zot-info?address=' . $data['addr'];
742 if (empty($zot_url)) {
746 $data = self::pollZot($zot_url, $data);
748 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
749 foreach ($webfinger['aliases'] as $alias) {
750 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
751 $data['alias'] = $alias;
759 public static function pollZot($url, $data)
761 $curlResult = Network::curl($url);
762 if ($curlResult->isTimeout()) {
765 $content = $curlResult->getBody();
770 $json = json_decode($content, true);
771 if (!is_array($json)) {
775 if (empty($data['network'])) {
776 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
777 $data['network'] = Protocol::ZOT;
778 } elseif (!isset($json['protocols'])) {
779 $data['network'] = Protocol::ZOT;
783 if (!empty($json['guid']) && empty($data['guid'])) {
784 $data['guid'] = $json['guid'];
786 if (!empty($json['key']) && empty($data['pubkey'])) {
787 $data['pubkey'] = $json['key'];
789 if (!empty($json['name'])) {
790 $data['name'] = $json['name'];
792 if (!empty($json['photo'])) {
793 $data['photo'] = $json['photo'];
794 if (!empty($json['photo_updated'])) {
795 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
798 if (!empty($json['address'])) {
799 $data['addr'] = $json['address'];
801 if (!empty($json['url'])) {
802 $data['url'] = $json['url'];
804 if (!empty($json['connections_url'])) {
805 $data['poco'] = $json['connections_url'];
807 if (isset($json['searchable'])) {
808 $data['hide'] = !$json['searchable'];
810 if (!empty($json['public_forum'])) {
811 $data['community'] = $json['public_forum'];
812 $data['account-type'] = Contact::PAGE_COMMUNITY;
815 if (!empty($json['profile'])) {
816 $profile = $json['profile'];
817 if (!empty($profile['description'])) {
818 $data['about'] = $profile['description'];
820 if (!empty($profile['gender'])) {
821 $data['gender'] = $profile['gender'];
823 if (!empty($profile['keywords'])) {
824 $keywords = implode(', ', $profile['keywords']);
825 if (!empty($keywords)) {
826 $data['keywords'] = $keywords;
831 if (!empty($profile['region'])) {
832 $loc['region'] = $profile['region'];
834 if (!empty($profile['country'])) {
835 $loc['country-name'] = $profile['country'];
837 if (!empty($profile['hometown'])) {
838 $loc['locality'] = $profile['hometown'];
840 $location = Profile::formatLocation($loc);
841 if (!empty($location)) {
842 $data['location'] = $location;
850 * @brief Perform a webfinger request.
852 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
854 * @param string $url Address that should be probed
855 * @param string $type type
857 * @return array webfinger data
858 * @throws HTTPException\InternalServerErrorException
860 private static function webfinger($url, $type)
862 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
864 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
865 if ($curlResult->isTimeout()) {
866 self::$istimeout = true;
869 $data = $curlResult->getBody();
871 $webfinger = json_decode($data, true);
872 if (is_array($webfinger)) {
873 if (!isset($webfinger["links"])) {
874 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
880 // If it is not JSON, maybe it is XML
881 $xrd = XML::parseString($data, false);
882 if (!is_object($xrd)) {
883 Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
887 $xrd_arr = XML::elementToArray($xrd);
888 if (!isset($xrd_arr["xrd"]["link"])) {
889 Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
895 if (!empty($xrd_arr["xrd"]["subject"])) {
896 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
899 if (!empty($xrd_arr["xrd"]["alias"])) {
900 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
903 $webfinger["links"] = [];
905 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
906 if (!empty($data["@attributes"])) {
907 $attributes = $data["@attributes"];
908 } elseif ($value == "@attributes") {
914 $webfinger["links"][] = $attributes;
920 * @brief Poll the Friendica specific noscrape page.
922 * "noscrape" is a faster alternative to fetch the data from the hcard.
923 * This functionality was originally created for the directory.
925 * @param string $noscrape_url Link to the noscrape page
926 * @param array $data The already fetched data
928 * @return array noscrape data
929 * @throws HTTPException\InternalServerErrorException
931 private static function pollNoscrape($noscrape_url, $data)
933 $curlResult = Network::curl($noscrape_url);
934 if ($curlResult->isTimeout()) {
935 self::$istimeout = true;
938 $content = $curlResult->getBody();
940 Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
944 $json = json_decode($content, true);
945 if (!is_array($json)) {
946 Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
950 if (!empty($json["fn"])) {
951 $data["name"] = $json["fn"];
954 if (!empty($json["addr"])) {
955 $data["addr"] = $json["addr"];
958 if (!empty($json["nick"])) {
959 $data["nick"] = $json["nick"];
962 if (!empty($json["guid"])) {
963 $data["guid"] = $json["guid"];
966 if (!empty($json["comm"])) {
967 $data["community"] = $json["comm"];
970 if (!empty($json["tags"])) {
971 $keywords = implode(", ", $json["tags"]);
972 if ($keywords != "") {
973 $data["keywords"] = $keywords;
977 $location = Profile::formatLocation($json);
979 $data["location"] = $location;
982 if (!empty($json["about"])) {
983 $data["about"] = $json["about"];
986 if (!empty($json["gender"])) {
987 $data["gender"] = $json["gender"];
990 if (!empty($json["key"])) {
991 $data["pubkey"] = $json["key"];
994 if (!empty($json["photo"])) {
995 $data["photo"] = $json["photo"];
998 if (!empty($json["dfrn-request"])) {
999 $data["request"] = $json["dfrn-request"];
1002 if (!empty($json["dfrn-confirm"])) {
1003 $data["confirm"] = $json["dfrn-confirm"];
1006 if (!empty($json["dfrn-notify"])) {
1007 $data["notify"] = $json["dfrn-notify"];
1010 if (!empty($json["dfrn-poll"])) {
1011 $data["poll"] = $json["dfrn-poll"];
1014 if (isset($json["hide"])) {
1015 $data["hide"] = (bool)$json["hide"];
1017 $data["hide"] = false;
1024 * @brief Check for valid DFRN data
1026 * @param array $data DFRN data
1028 * @return int Number of errors
1030 public static function validDfrn($data)
1033 if (!isset($data['key'])) {
1036 if (!isset($data['dfrn-request'])) {
1039 if (!isset($data['dfrn-confirm'])) {
1042 if (!isset($data['dfrn-notify'])) {
1045 if (!isset($data['dfrn-poll'])) {
1052 * @brief Fetch data from a DFRN profile page and via "noscrape"
1054 * @param string $profile_link Link to the profile page
1056 * @return array profile data
1057 * @throws HTTPException\InternalServerErrorException
1058 * @throws \ImagickException
1060 public static function profile($profile_link)
1064 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
1066 // Fetch data via noscrape - this is faster
1067 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1068 $data = self::pollNoscrape($noscrape_url, $data);
1070 if (!isset($data["notify"])
1071 || !isset($data["confirm"])
1072 || !isset($data["request"])
1073 || !isset($data["poll"])
1074 || !isset($data["name"])
1075 || !isset($data["photo"])
1077 $data = self::pollHcard($profile_link, $data, true);
1082 if (empty($data["addr"]) || empty($data["nick"])) {
1083 $probe_data = self::uri($profile_link);
1084 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1085 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1088 $prof_data["addr"] = $data["addr"];
1089 $prof_data["nick"] = $data["nick"];
1090 $prof_data["dfrn-request"] = $data['request'] ?? null;
1091 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1092 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1093 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1094 $prof_data["photo"] = $data['photo'] ?? null;
1095 $prof_data["fn"] = $data['name'] ?? null;
1096 $prof_data["key"] = $data['pubkey'] ?? null;
1098 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
1104 * @brief Check for DFRN contact
1106 * @param array $webfinger Webfinger data
1108 * @return array DFRN data
1109 * @throws HTTPException\InternalServerErrorException
1111 private static function dfrn($webfinger)
1115 // The array is reversed to take into account the order of preference for same-rel links
1116 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1117 foreach (array_reverse($webfinger["links"]) as $link) {
1118 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1119 $data["network"] = Protocol::DFRN;
1120 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1121 $data["poll"] = $link["href"];
1122 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1123 $data["url"] = $link["href"];
1124 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1125 $hcard_url = $link["href"];
1126 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1127 $data["poco"] = $link["href"];
1128 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1129 $data["photo"] = $link["href"];
1130 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1131 $data["baseurl"] = trim($link["href"], '/');
1132 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1133 $data["guid"] = $link["href"];
1134 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1135 $data["pubkey"] = base64_decode($link["href"]);
1137 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1138 if (strstr($data["pubkey"], 'RSA ')) {
1139 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1144 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1145 foreach ($webfinger["aliases"] as $alias) {
1146 if (empty($data["url"]) && !strstr($alias, "@")) {
1147 $data["url"] = $alias;
1148 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1149 $data["alias"] = $alias;
1150 } elseif (substr($alias, 0, 5) == 'acct:') {
1151 $data["addr"] = substr($alias, 5);
1156 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1157 $data["addr"] = substr($webfinger["subject"], 5);
1160 if (!isset($data["network"]) || ($hcard_url == "")) {
1164 // Fetch data via noscrape - this is faster
1165 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1166 $data = self::pollNoscrape($noscrape_url, $data);
1168 if (isset($data["notify"])
1169 && isset($data["confirm"])
1170 && isset($data["request"])
1171 && isset($data["poll"])
1172 && isset($data["name"])
1173 && isset($data["photo"])
1178 $data = self::pollHcard($hcard_url, $data, true);
1184 * @brief Poll the hcard page (Diaspora and Friendica specific)
1186 * @param string $hcard_url Link to the hcard page
1187 * @param array $data The already fetched data
1188 * @param boolean $dfrn Poll DFRN specific data
1190 * @return array hcard data
1191 * @throws HTTPException\InternalServerErrorException
1193 private static function pollHcard($hcard_url, $data, $dfrn = false)
1195 $curlResult = Network::curl($hcard_url);
1196 if ($curlResult->isTimeout()) {
1197 self::$istimeout = true;
1200 $content = $curlResult->getBody();
1205 $doc = new DOMDocument();
1206 if (!@$doc->loadHTML($content)) {
1210 $xpath = new DomXPath($doc);
1212 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1213 if (!is_object($vcards)) {
1217 if (!isset($data["baseurl"])) {
1218 $data["baseurl"] = "";
1221 if ($vcards->length > 0) {
1222 $vcard = $vcards->item(0);
1224 // We have to discard the guid from the hcard in favour of the guid from lrdd
1225 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1226 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1227 if (($search->length > 0) && empty($data["guid"])) {
1228 $data["guid"] = $search->item(0)->nodeValue;
1231 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1232 if ($search->length > 0) {
1233 $data["nick"] = $search->item(0)->nodeValue;
1236 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1237 if ($search->length > 0) {
1238 $data["name"] = $search->item(0)->nodeValue;
1241 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1242 if ($search->length > 0) {
1243 $data["searchable"] = $search->item(0)->nodeValue;
1246 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1247 if ($search->length > 0) {
1248 $data["pubkey"] = $search->item(0)->nodeValue;
1249 if (strstr($data["pubkey"], 'RSA ')) {
1250 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1254 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1255 if ($search->length > 0) {
1256 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1261 if (!empty($vcard)) {
1262 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1263 foreach ($photos as $photo) {
1265 foreach ($photo->attributes as $attribute) {
1266 $attr[$attribute->name] = trim($attribute->value);
1269 if (isset($attr["src"]) && isset($attr["width"])) {
1270 $avatar[$attr["width"]] = $attr["src"];
1273 // We don't have a width. So we just take everything that we got.
1274 // This is a Hubzilla workaround which doesn't send a width.
1275 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1276 $avatar[] = $attr["src"];
1281 if (sizeof($avatar)) {
1283 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1287 // Poll DFRN specific data
1288 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1289 if ($search->length > 0) {
1290 foreach ($search as $link) {
1291 //$data["request"] = $search->item(0)->nodeValue;
1293 foreach ($link->attributes as $attribute) {
1294 $attr[$attribute->name] = trim($attribute->value);
1297 $data[substr($attr["rel"], 5)] = $attr["href"];
1301 // Older Friendica versions had used the "uid" field differently than newer versions
1302 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1303 unset($data["guid"]);
1312 * @brief Check for Diaspora contact
1314 * @param array $webfinger Webfinger data
1316 * @return array Diaspora data
1317 * @throws HTTPException\InternalServerErrorException
1319 private static function diaspora($webfinger)
1324 // The array is reversed to take into account the order of preference for same-rel links
1325 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1326 foreach (array_reverse($webfinger["links"]) as $link) {
1327 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1328 $hcard_url = $link["href"];
1329 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1330 $data["baseurl"] = trim($link["href"], '/');
1331 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1332 $data["guid"] = $link["href"];
1333 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1334 $data["url"] = $link["href"];
1335 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1336 $data["poll"] = $link["href"];
1337 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1338 $data["poco"] = $link["href"];
1339 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1340 $data["notify"] = $link["href"];
1341 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1342 $data["pubkey"] = base64_decode($link["href"]);
1344 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1345 if (strstr($data["pubkey"], 'RSA ')) {
1346 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1351 if (empty($data["url"]) || empty($hcard_url)) {
1355 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1356 foreach ($webfinger["aliases"] as $alias) {
1357 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1358 $data["alias"] = $alias;
1359 } elseif (substr($alias, 0, 5) == 'acct:') {
1360 $data["addr"] = substr($alias, 5);
1365 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1366 $data["addr"] = substr($webfinger["subject"], 5);
1369 // Fetch further information from the hcard
1370 $data = self::pollHcard($hcard_url, $data);
1376 if (!empty($data["url"])
1377 && !empty($data["guid"])
1378 && !empty($data["baseurl"])
1379 && !empty($data["pubkey"])
1380 && !empty($hcard_url)
1382 $data["network"] = Protocol::DIASPORA;
1384 // The Diaspora handle must always be lowercase
1385 if (!empty($data["addr"])) {
1386 $data["addr"] = strtolower($data["addr"]);
1389 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1390 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1391 $data["batch"] = $data["baseurl"] . "/receive/public";
1400 * @brief Check for OStatus contact
1402 * @param array $webfinger Webfinger data
1403 * @param bool $short Short detection mode
1405 * @return array|bool OStatus data or "false" on error or "true" on short mode
1406 * @throws HTTPException\InternalServerErrorException
1408 private static function ostatus($webfinger, $short = false)
1412 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1413 foreach ($webfinger["aliases"] as $alias) {
1414 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1415 $data["addr"] = str_replace('acct:', '', $alias);
1420 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1421 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1423 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1426 if (is_array($webfinger["links"])) {
1427 // The array is reversed to take into account the order of preference for same-rel links
1428 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1429 foreach (array_reverse($webfinger["links"]) as $link) {
1430 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1431 && (($link["type"] ?? "") == "text/html")
1432 && ($link["href"] != "")
1434 $data["url"] = $link["href"];
1435 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1436 $data["notify"] = $link["href"];
1437 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1438 $data["poll"] = $link["href"];
1439 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1440 $pubkey = $link["href"];
1442 if (substr($pubkey, 0, 5) === 'data:') {
1443 if (strstr($pubkey, ',')) {
1444 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1446 $pubkey = substr($pubkey, 5);
1448 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1449 $curlResult = Network::curl($pubkey);
1450 if ($curlResult->isTimeout()) {
1451 self::$istimeout = true;
1454 $pubkey = $curlResult->getBody();
1457 $key = explode(".", $pubkey);
1459 if (sizeof($key) >= 3) {
1460 $m = Strings::base64UrlDecode($key[1]);
1461 $e = Strings::base64UrlDecode($key[2]);
1462 $data["pubkey"] = Crypto::meToPem($m, $e);
1468 if (isset($data["notify"]) && isset($data["pubkey"])
1469 && isset($data["poll"])
1470 && isset($data["url"])
1472 $data["network"] = Protocol::OSTATUS;
1481 // Fetch all additional data from the feed
1482 $curlResult = Network::curl($data["poll"]);
1483 if ($curlResult->isTimeout()) {
1484 self::$istimeout = true;
1487 $feed = $curlResult->getBody();
1488 $feed_data = Feed::import($feed);
1493 if (!empty($feed_data["header"]["author-name"])) {
1494 $data["name"] = $feed_data["header"]["author-name"];
1496 if (!empty($feed_data["header"]["author-nick"])) {
1497 $data["nick"] = $feed_data["header"]["author-nick"];
1499 if (!empty($feed_data["header"]["author-avatar"])) {
1500 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1502 if (!empty($feed_data["header"]["author-id"])) {
1503 $data["alias"] = $feed_data["header"]["author-id"];
1505 if (!empty($feed_data["header"]["author-location"])) {
1506 $data["location"] = $feed_data["header"]["author-location"];
1508 if (!empty($feed_data["header"]["author-about"])) {
1509 $data["about"] = $feed_data["header"]["author-about"];
1511 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1512 // So we take the value that we just fetched, although the other one worked as well
1513 if (!empty($feed_data["header"]["author-link"])) {
1514 $data["url"] = $feed_data["header"]["author-link"];
1517 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1518 $data['url'] = $data["alias"];
1519 $data["alias"] = '';
1522 /// @todo Fetch location and "about" from the feed as well
1527 * @brief Fetch data from a pump.io profile page
1529 * @param string $profile_link Link to the profile page
1531 * @return array profile data
1533 private static function pumpioProfileData($profile_link)
1535 $curlResult = Network::curl($profile_link);
1536 if (!$curlResult->isSuccess()) {
1540 $doc = new DOMDocument();
1541 if (!@$doc->loadHTML($curlResult->getBody())) {
1545 $xpath = new DomXPath($doc);
1549 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1551 if ($data["name"] == '') {
1552 // This is ugly - but pump.io doesn't seem to know a better way for it
1553 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1554 $pos = strpos($data["name"], chr(10));
1556 $data["name"] = trim(substr($data["name"], 0, $pos));
1560 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1562 if ($data["location"] == '') {
1563 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1566 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1568 if ($data["about"] == '') {
1569 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1572 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1574 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1577 foreach ($avatar->attributes as $attribute) {
1578 if ($attribute->name == "src") {
1579 $data["photo"] = trim($attribute->value);
1588 * @brief Check for pump.io contact
1590 * @param array $webfinger Webfinger data
1591 * @param string $addr
1592 * @return array pump.io data
1594 private static function pumpio($webfinger, $addr)
1597 // The array is reversed to take into account the order of preference for same-rel links
1598 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1599 foreach (array_reverse($webfinger["links"]) as $link) {
1600 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1601 && (($link["type"] ?? "") == "text/html")
1602 && ($link["href"] != "")
1604 $data["url"] = $link["href"];
1605 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1606 $data["notify"] = $link["href"];
1607 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1608 $data["poll"] = $link["href"];
1609 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1610 $data["dialback"] = $link["href"];
1613 if (isset($data["poll"]) && isset($data["notify"])
1614 && isset($data["dialback"])
1615 && isset($data["url"])
1617 // by now we use these fields only for the network type detection
1618 // So we unset all data that isn't used at the moment
1619 unset($data["dialback"]);
1621 $data["network"] = Protocol::PUMPIO;
1626 $profile_data = self::pumpioProfileData($data["url"]);
1628 if (!$profile_data) {
1632 $data = array_merge($data, $profile_data);
1634 if (($addr != '') && ($data['name'] != '')) {
1635 $name = trim(str_replace($addr, '', $data['name']));
1637 $data['name'] = $name;
1645 * @brief Check for twitter contact
1647 * @param string $uri
1649 * @return array twitter data
1651 private static function twitter($uri)
1653 if (preg_match('=(.*)@twitter.com=i', $uri, $matches)) {
1654 $nick = $matches[1];
1655 } elseif (preg_match('=https?://twitter.com/(.*)=i', $uri, $matches)) {
1656 $nick = $matches[1];
1662 $data['url'] = 'https://twitter.com/' . $nick;
1663 $data['addr'] = $nick . '@twitter.com';
1664 $data['nick'] = $data['name'] = $nick;
1665 $data['network'] = Protocol::TWITTER;
1666 $data['baseurl'] = 'https://twitter.com';
1668 $curlResult = Network::curl($data['url'], false);
1669 if (!$curlResult->isSuccess()) {
1673 $body = $curlResult->getBody();
1674 $doc = new DOMDocument();
1675 @$doc->loadHTML($body);
1676 $xpath = new DOMXPath($doc);
1678 $list = $xpath->query('//img[@class]');
1679 foreach ($list as $node) {
1681 if ($node->attributes->length) {
1682 foreach ($node->attributes as $attribute) {
1683 $img_attr[$attribute->name] = $attribute->value;
1687 if (empty($img_attr['class'])) {
1691 if (strpos($img_attr['class'], 'ProfileAvatar-image') !== false) {
1692 if (!empty($img_attr['src'])) {
1693 $data['photo'] = $img_attr['src'];
1695 if (!empty($img_attr['alt'])) {
1696 $data['name'] = $img_attr['alt'];
1705 * @brief Check page for feed link
1707 * @param string $url Page link
1709 * @return string feed link
1711 private static function getFeedLink($url)
1713 $curlResult = Network::curl($url);
1714 if (!$curlResult->isSuccess()) {
1718 $doc = new DOMDocument();
1719 if (!@$doc->loadHTML($curlResult->getBody())) {
1723 $xpath = new DomXPath($doc);
1725 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1726 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1727 if (!is_object($feeds)) {
1731 if ($feeds->length == 0) {
1737 foreach ($feeds as $feed) {
1739 foreach ($feed->attributes as $attribute) {
1740 $attr[$attribute->name] = trim($attribute->value);
1743 if (empty($feed_url) && !empty($attr['href'])) {
1744 $feed_url = $attr["href"];
1752 * @brief Check for feed contact
1754 * @param string $url Profile link
1755 * @param boolean $probe Do a probe if the page contains a feed link
1757 * @return array feed data
1758 * @throws HTTPException\InternalServerErrorException
1760 private static function feed($url, $probe = true)
1762 $curlResult = Network::curl($url);
1763 if ($curlResult->isTimeout()) {
1764 self::$istimeout = true;
1767 $feed = $curlResult->getBody();
1768 $feed_data = Feed::import($feed);
1775 $feed_url = self::getFeedLink($url);
1781 return self::feed($feed_url, false);
1784 if (!empty($feed_data["header"]["author-name"])) {
1785 $data["name"] = $feed_data["header"]["author-name"];
1788 if (!empty($feed_data["header"]["author-nick"])) {
1789 $data["nick"] = $feed_data["header"]["author-nick"];
1792 if (!empty($feed_data["header"]["author-avatar"])) {
1793 $data["photo"] = $feed_data["header"]["author-avatar"];
1796 if (!empty($feed_data["header"]["author-id"])) {
1797 $data["alias"] = $feed_data["header"]["author-id"];
1800 $data["url"] = $url;
1801 $data["poll"] = $url;
1803 if (!empty($feed_data["header"]["author-link"])) {
1804 $data["baseurl"] = $feed_data["header"]["author-link"];
1806 $data["baseurl"] = $data["url"];
1809 $data["network"] = Protocol::FEED;
1815 * @brief Check for mail contact
1817 * @param string $uri Profile link
1818 * @param integer $uid User ID
1820 * @return array mail data
1821 * @throws \Exception
1823 private static function mail($uri, $uid)
1825 if (!Network::isEmailDomainValid($uri)) {
1833 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1835 $condition = ["`uid` = ? AND `server` != ''", $uid];
1836 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1837 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1839 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1843 $mailbox = Email::constructMailboxName($mailacct);
1845 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1846 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1851 $msgs = Email::poll($mbox, $uri);
1852 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1854 if (!count($msgs)) {
1858 $phost = substr($uri, strpos($uri, '@') + 1);
1861 $data["addr"] = $uri;
1862 $data["network"] = Protocol::MAIL;
1863 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1864 $data["nick"] = $data["name"];
1865 $data["photo"] = Network::lookupAvatarByEmail($uri);
1866 $data["url"] = 'mailto:'.$uri;
1867 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1868 $data["poll"] = 'email ' . Strings::getRandomHex();
1870 $x = Email::messageMeta($mbox, $msgs[0]);
1871 if (stristr($x[0]->from, $uri)) {
1872 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1873 } elseif (stristr($x[0]->to, $uri)) {
1874 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1877 foreach ($adr as $feadr) {
1878 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1879 &&(strcasecmp($feadr->host, $phost) == 0)
1880 && (strlen($feadr->personal))
1882 $personal = imap_mime_header_decode($feadr->personal);
1884 foreach ($personal as $perspart) {
1885 if ($perspart->charset != "default") {
1886 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1888 $data["name"] .= $perspart->text;
1892 $data["name"] = Strings::escapeTags($data["name"]);
1896 if (!empty($mbox)) {
1903 * @brief Mix two paths together to possibly fix missing parts
1905 * @param string $avatar Path to the avatar
1906 * @param string $base Another path that is hopefully complete
1908 * @return string fixed avatar path
1909 * @throws \Exception
1911 public static function fixAvatar($avatar, $base)
1913 $base_parts = parse_url($base);
1915 // Remove all parts that could create a problem
1916 unset($base_parts['path']);
1917 unset($base_parts['query']);
1918 unset($base_parts['fragment']);
1920 $avatar_parts = parse_url($avatar);
1923 $parts = array_merge($base_parts, $avatar_parts);
1925 // And put them together again
1926 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1927 $host = isset($parts['host']) ? $parts['host'] : '';
1928 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1929 $path = isset($parts['path']) ? $parts['path'] : '';
1930 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1931 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1933 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1935 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);