3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Network;
26 use Friendica\Core\Cache\Duration;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\System;
30 use Friendica\Database\DBA;
32 use Friendica\Model\Contact;
33 use Friendica\Model\GServer;
34 use Friendica\Model\Profile;
35 use Friendica\Protocol\ActivityNamespace;
36 use Friendica\Protocol\ActivityPub;
37 use Friendica\Protocol\Email;
38 use Friendica\Protocol\Feed;
39 use Friendica\Util\Crypto;
40 use Friendica\Util\Network;
41 use Friendica\Util\Strings;
42 use Friendica\Util\XML;
45 * This class contain functions for probing URL
49 private static $baseurl;
50 private static $istimeout;
53 * Remove stuff from an URI that doesn't belong there
56 * @return string Cleaned URI
58 public static function cleanURI(string $URI)
60 // At first remove leading and trailing junk
61 $URI = trim($URI, "@#?:/ \t\n\r\0\x0B");
63 $parts = parse_url($URI);
65 if (empty($parts['scheme'])) {
69 // Remove the URL fragment, since these shouldn't be part of any profile URL
70 unset($parts['fragment']);
72 $URI = Network::unparseURL($parts);
78 * Rearrange the array so that it always has the same order
80 * @param array $data Unordered data
82 * @return array Ordered data
84 private static function rearrangeData($data)
86 $fields = ["name", "nick", "guid", "url", "addr", "alias", "photo", "account-type",
87 "community", "keywords", "location", "about", "hide",
88 "batch", "notify", "poll", "request", "confirm", "poco",
89 "following", "followers", "inbox", "outbox", "sharedinbox",
90 "priority", "network", "pubkey", "baseurl", "gsid"];
93 foreach ($fields as $field) {
94 if (isset($data[$field])) {
95 $newdata[$field] = $data[$field];
96 } elseif ($field != "gsid") {
97 $newdata[$field] = "";
99 $newdata[$field] = null;
103 // We don't use the "priority" field anymore and replace it with a dummy.
104 $newdata["priority"] = 0;
110 * Check if the hostname belongs to the own server
112 * @param string $host The hostname that is to be checked
114 * @return bool Does the testes hostname belongs to the own server?
116 private static function ownHost($host)
118 $own_host = DI::baseUrl()->getHostname();
120 $parts = parse_url($host);
122 if (!isset($parts['scheme'])) {
123 $parts = parse_url('http://'.$host);
126 if (!isset($parts['host'])) {
129 return $parts['host'] == $own_host;
133 * Probes for webfinger path via "host-meta"
135 * We have to check if the servers in the future still will offer this.
136 * It seems as if it was dropped from the standard.
138 * @param string $host The host part of an url
140 * @return array with template and type of the webfinger template for JSON or XML
141 * @throws HTTPException\InternalServerErrorException
143 private static function hostMeta($host)
145 // Reset the static variable
148 // Handles the case when the hostname contains the scheme
149 if (!parse_url($host, PHP_URL_SCHEME)) {
150 $ssl_url = "https://" . $host . "/.well-known/host-meta";
151 $url = "http://" . $host . "/.well-known/host-meta";
153 $ssl_url = $host . "/.well-known/host-meta";
157 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
159 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
162 $curlResult = Network::curl($ssl_url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
163 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
164 if ($curlResult->isSuccess()) {
165 $xml = $curlResult->getBody();
166 $xrd = XML::parseString($xml, true);
168 $host_url = 'https://' . $host;
172 } elseif ($curlResult->isTimeout()) {
173 Logger::info('Probing timeout', ['url' => $ssl_url], Logger::DEBUG);
174 self::$istimeout = true;
178 if (!is_object($xrd) && !empty($url)) {
179 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
180 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
181 if ($curlResult->isTimeout()) {
182 Logger::info('Probing timeout', ['url' => $url], Logger::DEBUG);
183 self::$istimeout = true;
185 } elseif ($connection_error && $ssl_connection_error) {
186 self::$istimeout = true;
190 $xml = $curlResult->getBody();
191 $xrd = XML::parseString($xml, true);
192 $host_url = 'http://'.$host;
194 if (!is_object($xrd)) {
195 Logger::log("No xrd object found for ".$host, Logger::DEBUG);
199 $links = XML::elementToArray($xrd);
200 if (!isset($links["xrd"]["link"])) {
201 Logger::log("No xrd data found for ".$host, Logger::DEBUG);
205 $lrdd = ['application/jrd+json' => $host_url . '/.well-known/webfinger?resource={uri}'];
207 foreach ($links["xrd"]["link"] as $value => $link) {
208 if (!empty($link["@attributes"])) {
209 $attributes = $link["@attributes"];
210 } elseif ($value == "@attributes") {
216 if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
217 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
219 $lrdd[$type] = $attributes["template"];
223 self::$baseurl = $host_url;
225 Logger::log("Probing successful for ".$host, Logger::DEBUG);
231 * Perform Webfinger lookup and return DFRN data
233 * Given an email style address, perform webfinger lookup and
234 * return the resulting DFRN profile URL, or if no DFRN profile URL
235 * is located, returns an OStatus subscription template (prefixed
236 * with the string 'stat:' to identify it as on OStatus template).
237 * If this isn't an email style address just return $webbie.
238 * Return an empty string if email-style addresses but webfinger fails,
239 * or if the resultant personal XRD doesn't contain a supported
240 * subscription/friend-request attribute.
242 * amended 7/9/2011 to return an hcard which could save potentially loading
243 * a lengthy content page to scrape dfrn attributes
245 * @param string $webbie Address that should be probed
246 * @param string $hcard_url Link to the hcard - is returned by reference
248 * @return string profile link
249 * @throws HTTPException\InternalServerErrorException
251 public static function webfingerDfrn($webbie, &$hcard_url)
255 $links = self::lrdd($webbie);
256 Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA);
257 if (!empty($links) && is_array($links)) {
258 foreach ($links as $link) {
259 if ($link['@attributes']['rel'] === ActivityNamespace::DFRN) {
260 $profile_link = $link['@attributes']['href'];
262 if (($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) && ($profile_link == "")) {
263 $profile_link = 'stat:'.$link['@attributes']['template'];
265 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
266 $hcard_url = $link['@attributes']['href'];
270 return $profile_link;
274 * Get the link for the remote follow page for a given profile link
276 * @param sting $profile
277 * @return string Remote follow page link
279 public static function getRemoteFollowLink(string $profile)
283 $links = self::lrdd($profile);
285 if (!empty($links) && is_array($links)) {
286 foreach ($links as $link) {
287 if ($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) {
288 $follow_link = $link['@attributes']['template'];
296 * Check an URI for LRDD data
298 * @param string $uri Address that should be probed
300 * @return array uri data
301 * @throws HTTPException\InternalServerErrorException
303 public static function lrdd($uri)
305 $lrdd = self::hostMeta($uri);
308 if (is_bool($lrdd)) {
313 $parts = @parse_url($uri);
314 if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
318 $host = $parts['scheme'] . '://' . $parts["host"];
319 if (!empty($parts["port"])) {
320 $host .= ':'.$parts["port"];
323 $path_parts = explode("/", trim($parts["path"], "/"));
325 $nick = array_pop($path_parts);
328 $lrdd = self::hostMeta($host);
329 $host .= "/".array_shift($path_parts);
330 } while (!$lrdd && (sizeof($path_parts) > 0));
334 Logger::log("No lrdd data found for ".$uri, Logger::DEBUG);
338 foreach ($lrdd as $type => $template) {
343 $path = str_replace('{uri}', urlencode($uri), $template);
344 $webfinger = self::webfinger($path, $type);
346 if (!$webfinger && (strstr($uri, "@"))) {
347 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
348 $webfinger = self::webfinger($path, $type);
351 // Special treatment for Mastodon
352 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
353 // But the webfinger for this format fails.
354 if (!$webfinger && !empty($nick)) {
355 // Mastodon uses a "@" as prefix for usernames in their url format
356 $nick = ltrim($nick, '@');
358 $addr = $nick."@".$host;
360 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
361 $webfinger = self::webfinger($path, $type);
365 if (!is_array($webfinger["links"])) {
366 Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
372 foreach ($webfinger["links"] as $link) {
373 $data[] = ["@attributes" => $link];
376 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
377 foreach ($webfinger["aliases"] as $alias) {
378 $data[] = ["@attributes" =>
388 * Fetch information (protocol endpoints and user information) about a given uri
390 * @param string $uri Address that should be probed
391 * @param string $network Test for this specific network
392 * @param integer $uid User ID for the probe (only used for mails)
393 * @param boolean $cache Use cached values?
395 * @return array uri data
396 * @throws HTTPException\InternalServerErrorException
397 * @throws \ImagickException
399 public static function uri($uri, $network = '', $uid = -1, $cache = true)
402 $result = DI::cache()->get('Probe::uri:' . $network . ':' . $uri);
403 if (!is_null($result)) {
412 self::$istimeout = false;
414 if ($network != Protocol::ACTIVITYPUB) {
415 $data = self::detect($uri, $network, $uid);
420 // When the previous detection process had got a time out
421 // we could falsely detect a Friendica profile as AP profile.
422 if (!self::$istimeout) {
423 $ap_profile = ActivityPub::probeProfile($uri);
425 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
427 } elseif (!empty($ap_profile)) {
428 $ap_profile['batch'] = '';
429 $data = array_merge($ap_profile, $data);
432 Logger::notice('Time out detected. AP will not be probed.', ['uri' => $uri]);
435 if (!isset($data['url'])) {
439 if (!empty($data['photo']) && !empty($data['baseurl'])) {
440 $data['baseurl'] = Network::getUrlMatch(Strings::normaliseLink($data['baseurl']), Strings::normaliseLink($data['photo']));
441 } elseif (empty($data['photo'])) {
442 $data['photo'] = DI::baseUrl() . '/images/person-300.jpg';
445 if (empty($data['name'])) {
446 if (!empty($data['nick'])) {
447 $data['name'] = $data['nick'];
450 if (empty($data['name'])) {
451 $data['name'] = $data['url'];
455 if (empty($data['nick'])) {
456 $data['nick'] = strtolower($data['name']);
458 if (strpos($data['nick'], ' ')) {
459 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
463 if (!empty(self::$baseurl)) {
464 $data['baseurl'] = self::$baseurl;
467 if (!empty($data['baseurl']) && empty($data['gsid'])) {
468 $data['gsid'] = GServer::getID($data['baseurl']);
471 if (empty($data['network'])) {
472 $data['network'] = Protocol::PHANTOM;
475 // Ensure that local connections always are DFRN
476 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
477 $data['network'] = Protocol::DFRN;
480 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
481 $data['hide'] = self::getHideStatus($data['url']);
484 $data = self::rearrangeData($data);
486 // Only store into the cache if the value seems to be valid
487 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
488 DI::cache()->set('Probe::uri:' . $network . ':' . $uri, $data, Duration::DAY);
496 * Fetches the "hide" status from the profile
498 * @param string $url URL of the profile
500 * @return boolean "hide" status
502 private static function getHideStatus($url)
504 $curlResult = Network::curl($url);
505 if (!$curlResult->isSuccess()) {
509 // If the file is too large then exit
510 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
514 // If it isn't a HTML file then exit
515 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
519 $body = $curlResult->getBody();
521 $doc = new DOMDocument();
522 @$doc->loadHTML($body);
524 $xpath = new DOMXPath($doc);
526 $list = $xpath->query('//meta[@name]');
527 foreach ($list as $node) {
529 if ($node->attributes->length) {
530 foreach ($node->attributes as $attribute) {
531 $meta_tag[$attribute->name] = $attribute->value;
535 if (empty($meta_tag['content'])) {
539 $content = strtolower(trim($meta_tag['content']));
541 switch (strtolower(trim($meta_tag['name']))) {
542 case 'dfrn-global-visibility':
543 if ($content == 'false') {
548 if (strpos($content, 'noindex') !== false) {
559 * Checks if a profile url should be OStatus but only provides partial information
561 * @param array $webfinger Webfinger data
562 * @param string $lrdd Path template for webfinger request
563 * @param string $type type
565 * @return array fixed webfinger data
566 * @throws HTTPException\InternalServerErrorException
568 private static function fixOStatus($webfinger, $lrdd, $type)
570 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
577 foreach ($webfinger['links'] as $link) {
578 if ($link['rel'] == ActivityNamespace::OSTATUSSUB) {
581 if ($link['rel'] == 'magic-public-key') {
586 if (!$is_ostatus || $has_key) {
590 $url = Network::switchScheme($webfinger['subject']);
591 $path = str_replace('{uri}', urlencode($url), $lrdd);
592 $webfinger2 = self::webfinger($path, $type);
594 // Is the new webfinger detectable as OStatus?
595 if (self::ostatus($webfinger2, true)) {
596 $webfinger = $webfinger2;
603 * Fetch information (protocol endpoints and user information) about a given uri
605 * This function is only called by the "uri" function that adds caching and rearranging of data.
607 * @param string $uri Address that should be probed
608 * @param string $network Test for this specific network
609 * @param integer $uid User ID for the probe (only used for mails)
611 * @return array uri data
612 * @throws HTTPException\InternalServerErrorException
614 private static function detect($uri, $network, $uid)
616 $parts = parse_url($uri);
618 if (!empty($parts["scheme"]) && !empty($parts["host"])) {
619 $host = $parts["host"];
620 if (!empty($parts["port"])) {
621 $host .= ':'.$parts["port"];
624 if ($host == 'twitter.com') {
625 return self::twitter($uri);
627 $lrdd = self::hostMeta($host);
629 if (is_bool($lrdd)) {
633 $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
635 while (!$lrdd && (sizeof($path_parts) > 1)) {
636 $host .= "/".array_shift($path_parts);
637 $lrdd = self::hostMeta($host);
640 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
641 return self::feed($uri);
643 $nick = array_pop($path_parts);
645 // Mastodon uses a "@" as prefix for usernames in their url format
646 $nick = ltrim($nick, '@');
648 $addr = $nick."@".$host;
649 } elseif (strstr($uri, '@')) {
650 // If the URI starts with "mailto:" then jump directly to the mail detection
651 if (strpos($uri, 'mailto:') !== false) {
652 $uri = str_replace('mailto:', '', $uri);
653 return self::mail($uri, $uid);
656 if ($network == Protocol::MAIL) {
657 return self::mail($uri, $uid);
659 // Remove "acct:" from the URI
660 $uri = str_replace('acct:', '', $uri);
662 $host = substr($uri, strpos($uri, '@') + 1);
663 $nick = substr($uri, 0, strpos($uri, '@'));
665 if (strpos($uri, '@twitter.com')) {
666 return self::twitter($uri);
668 $lrdd = self::hostMeta($host);
670 if (is_bool($lrdd)) {
675 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
676 return self::mail($uri, $uid);
680 Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
686 /// @todo Do we need the prefix "acct:" or "acct://"?
688 foreach ($lrdd as $type => $template) {
693 // At first try it with the given uri
694 $path = str_replace('{uri}', urlencode($uri), $template);
695 $webfinger = self::webfinger($path, $type);
697 // Fix possible problems with GNU Social probing to wrong scheme
698 $webfinger = self::fixOStatus($webfinger, $template, $type);
700 // We cannot be sure that the detected address was correct, so we don't use the values
701 if ($webfinger && ($uri != $addr)) {
706 // Try webfinger with the address (user@domain.tld)
708 $path = str_replace('{uri}', urlencode($addr), $template);
709 $webfinger = self::webfinger($path, $type);
712 // Mastodon needs to have it with "acct:"
714 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
715 $webfinger = self::webfinger($path, $type);
720 return self::feed($uri);
725 Logger::log("Probing ".$uri, Logger::DEBUG);
727 if (in_array($network, ["", Protocol::DFRN])) {
728 $result = self::dfrn($webfinger);
730 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
731 $result = self::diaspora($webfinger);
733 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
734 $result = self::ostatus($webfinger);
736 if (in_array($network, ['', Protocol::ZOT])) {
737 $result = self::zot($webfinger, $result);
739 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
740 $result = self::pumpio($webfinger, $addr);
742 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
743 $result = self::feed($uri);
745 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
746 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
747 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
748 $result["nick"] = $nick;
751 if (empty($result["addr"]) && ($addr != "")) {
752 $result["addr"] = $addr;
756 if (empty($result["network"])) {
757 $result["network"] = Protocol::PHANTOM;
760 if (empty($result["url"])) {
761 $result["url"] = $uri;
764 Logger::log($uri." is ".$result["network"], Logger::DEBUG);
766 if (empty($result["baseurl"]) && ($result["network"] != Protocol::PHANTOM)) {
767 $pos = strpos($result["url"], $host);
769 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
776 * Check for Zot contact
778 * @param array $webfinger Webfinger data
779 * @param array $data previously probed data
781 * @return array Zot data
782 * @throws HTTPException\InternalServerErrorException
784 private static function zot($webfinger, $data)
786 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
787 foreach ($webfinger["aliases"] as $alias) {
788 if (substr($alias, 0, 5) == 'acct:') {
789 $data["addr"] = substr($alias, 5);
794 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
795 $data["addr"] = substr($webfinger["subject"], 5);
799 foreach ($webfinger['links'] as $link) {
800 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
801 $zot_url = $link['href'];
805 if (empty($zot_url) && !empty($data['addr']) && !empty(self::$baseurl)) {
806 $condition = ['nurl' => Strings::normaliseLink(self::$baseurl), 'platform' => ['hubzilla']];
807 if (!DBA::exists('gserver', $condition)) {
810 $zot_url = self::$baseurl . '/.well-known/zot-info?address=' . $data['addr'];
813 if (empty($zot_url)) {
817 $data = self::pollZot($zot_url, $data);
819 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
820 foreach ($webfinger['aliases'] as $alias) {
821 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
822 $data['alias'] = $alias;
830 public static function pollZot($url, $data)
832 $curlResult = Network::curl($url);
833 if ($curlResult->isTimeout()) {
836 $content = $curlResult->getBody();
841 $json = json_decode($content, true);
842 if (!is_array($json)) {
846 if (empty($data['network'])) {
847 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
848 $data['network'] = Protocol::ZOT;
849 } elseif (!isset($json['protocols'])) {
850 $data['network'] = Protocol::ZOT;
854 if (!empty($json['guid']) && empty($data['guid'])) {
855 $data['guid'] = $json['guid'];
857 if (!empty($json['key']) && empty($data['pubkey'])) {
858 $data['pubkey'] = $json['key'];
860 if (!empty($json['name'])) {
861 $data['name'] = $json['name'];
863 if (!empty($json['photo'])) {
864 $data['photo'] = $json['photo'];
865 if (!empty($json['photo_updated'])) {
866 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
869 if (!empty($json['address'])) {
870 $data['addr'] = $json['address'];
872 if (!empty($json['url'])) {
873 $data['url'] = $json['url'];
875 if (!empty($json['connections_url'])) {
876 $data['poco'] = $json['connections_url'];
878 if (isset($json['searchable'])) {
879 $data['hide'] = !$json['searchable'];
881 if (!empty($json['public_forum'])) {
882 $data['community'] = $json['public_forum'];
883 $data['account-type'] = Contact::PAGE_COMMUNITY;
886 if (!empty($json['profile'])) {
887 $profile = $json['profile'];
888 if (!empty($profile['description'])) {
889 $data['about'] = $profile['description'];
891 if (!empty($profile['keywords'])) {
892 $keywords = implode(', ', $profile['keywords']);
893 if (!empty($keywords)) {
894 $data['keywords'] = $keywords;
899 if (!empty($profile['region'])) {
900 $loc['region'] = $profile['region'];
902 if (!empty($profile['country'])) {
903 $loc['country-name'] = $profile['country'];
905 $location = Profile::formatLocation($loc);
906 if (!empty($location)) {
907 $data['location'] = $location;
915 * Perform a webfinger request.
917 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
919 * @param string $url Address that should be probed
920 * @param string $type type
922 * @return array webfinger data
923 * @throws HTTPException\InternalServerErrorException
925 private static function webfinger($url, $type)
927 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
929 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
930 if ($curlResult->isTimeout()) {
931 self::$istimeout = true;
934 $data = $curlResult->getBody();
936 $webfinger = json_decode($data, true);
937 if (is_array($webfinger)) {
938 if (!isset($webfinger["links"])) {
939 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
945 // If it is not JSON, maybe it is XML
946 $xrd = XML::parseString($data, true);
947 if (!is_object($xrd)) {
948 Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
952 $xrd_arr = XML::elementToArray($xrd);
953 if (!isset($xrd_arr["xrd"]["link"])) {
954 Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
960 if (!empty($xrd_arr["xrd"]["subject"])) {
961 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
964 if (!empty($xrd_arr["xrd"]["alias"])) {
965 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
968 $webfinger["links"] = [];
970 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
971 if (!empty($data["@attributes"])) {
972 $attributes = $data["@attributes"];
973 } elseif ($value == "@attributes") {
979 $webfinger["links"][] = $attributes;
985 * Poll the Friendica specific noscrape page.
987 * "noscrape" is a faster alternative to fetch the data from the hcard.
988 * This functionality was originally created for the directory.
990 * @param string $noscrape_url Link to the noscrape page
991 * @param array $data The already fetched data
993 * @return array noscrape data
994 * @throws HTTPException\InternalServerErrorException
996 private static function pollNoscrape($noscrape_url, $data)
998 $curlResult = Network::curl($noscrape_url);
999 if ($curlResult->isTimeout()) {
1000 self::$istimeout = true;
1003 $content = $curlResult->getBody();
1005 Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
1009 $json = json_decode($content, true);
1010 if (!is_array($json)) {
1011 Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
1015 if (!empty($json["fn"])) {
1016 $data["name"] = $json["fn"];
1019 if (!empty($json["addr"])) {
1020 $data["addr"] = $json["addr"];
1023 if (!empty($json["nick"])) {
1024 $data["nick"] = $json["nick"];
1027 if (!empty($json["guid"])) {
1028 $data["guid"] = $json["guid"];
1031 if (!empty($json["comm"])) {
1032 $data["community"] = $json["comm"];
1035 if (!empty($json["tags"])) {
1036 $keywords = implode(", ", $json["tags"]);
1037 if ($keywords != "") {
1038 $data["keywords"] = $keywords;
1042 $location = Profile::formatLocation($json);
1044 $data["location"] = $location;
1047 if (!empty($json["about"])) {
1048 $data["about"] = $json["about"];
1051 if (!empty($json["key"])) {
1052 $data["pubkey"] = $json["key"];
1055 if (!empty($json["photo"])) {
1056 $data["photo"] = $json["photo"];
1059 if (!empty($json["dfrn-request"])) {
1060 $data["request"] = $json["dfrn-request"];
1063 if (!empty($json["dfrn-confirm"])) {
1064 $data["confirm"] = $json["dfrn-confirm"];
1067 if (!empty($json["dfrn-notify"])) {
1068 $data["notify"] = $json["dfrn-notify"];
1071 if (!empty($json["dfrn-poll"])) {
1072 $data["poll"] = $json["dfrn-poll"];
1075 if (isset($json["hide"])) {
1076 $data["hide"] = (bool)$json["hide"];
1078 $data["hide"] = false;
1085 * Check for valid DFRN data
1087 * @param array $data DFRN data
1089 * @return int Number of errors
1091 public static function validDfrn($data)
1094 if (!isset($data['key'])) {
1097 if (!isset($data['dfrn-request'])) {
1100 if (!isset($data['dfrn-confirm'])) {
1103 if (!isset($data['dfrn-notify'])) {
1106 if (!isset($data['dfrn-poll'])) {
1113 * Fetch data from a DFRN profile page and via "noscrape"
1115 * @param string $profile_link Link to the profile page
1117 * @return array profile data
1118 * @throws HTTPException\InternalServerErrorException
1119 * @throws \ImagickException
1121 public static function profile($profile_link)
1125 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
1127 // Fetch data via noscrape - this is faster
1128 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1129 $data = self::pollNoscrape($noscrape_url, $data);
1131 if (!isset($data["notify"])
1132 || !isset($data["confirm"])
1133 || !isset($data["request"])
1134 || !isset($data["poll"])
1135 || !isset($data["name"])
1136 || !isset($data["photo"])
1138 $data = self::pollHcard($profile_link, $data, true);
1143 if (empty($data["addr"]) || empty($data["nick"])) {
1144 $probe_data = self::uri($profile_link);
1145 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1146 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1149 $prof_data["addr"] = $data["addr"];
1150 $prof_data["nick"] = $data["nick"];
1151 $prof_data["dfrn-request"] = $data['request'] ?? null;
1152 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1153 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1154 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1155 $prof_data["photo"] = $data['photo'] ?? null;
1156 $prof_data["fn"] = $data['name'] ?? null;
1157 $prof_data["key"] = $data['pubkey'] ?? null;
1159 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
1165 * Check for DFRN contact
1167 * @param array $webfinger Webfinger data
1169 * @return array DFRN data
1170 * @throws HTTPException\InternalServerErrorException
1172 private static function dfrn($webfinger)
1176 // The array is reversed to take into account the order of preference for same-rel links
1177 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1178 foreach (array_reverse($webfinger["links"]) as $link) {
1179 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1180 $data["network"] = Protocol::DFRN;
1181 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1182 $data["poll"] = $link["href"];
1183 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1184 $data["url"] = $link["href"];
1185 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1186 $hcard_url = $link["href"];
1187 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1188 $data["poco"] = $link["href"];
1189 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1190 $data["photo"] = $link["href"];
1191 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1192 $data["baseurl"] = trim($link["href"], '/');
1193 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1194 $data["guid"] = $link["href"];
1195 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1196 $data["pubkey"] = base64_decode($link["href"]);
1198 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1199 if (strstr($data["pubkey"], 'RSA ')) {
1200 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1205 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1206 foreach ($webfinger["aliases"] as $alias) {
1207 if (empty($data["url"]) && !strstr($alias, "@")) {
1208 $data["url"] = $alias;
1209 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1210 $data["alias"] = $alias;
1211 } elseif (substr($alias, 0, 5) == 'acct:') {
1212 $data["addr"] = substr($alias, 5);
1217 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1218 $data["addr"] = substr($webfinger["subject"], 5);
1221 if (!isset($data["network"]) || ($hcard_url == "")) {
1225 // Fetch data via noscrape - this is faster
1226 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1227 $data = self::pollNoscrape($noscrape_url, $data);
1229 if (isset($data["notify"])
1230 && isset($data["confirm"])
1231 && isset($data["request"])
1232 && isset($data["poll"])
1233 && isset($data["name"])
1234 && isset($data["photo"])
1239 $data = self::pollHcard($hcard_url, $data, true);
1245 * Poll the hcard page (Diaspora and Friendica specific)
1247 * @param string $hcard_url Link to the hcard page
1248 * @param array $data The already fetched data
1249 * @param boolean $dfrn Poll DFRN specific data
1251 * @return array hcard data
1252 * @throws HTTPException\InternalServerErrorException
1254 private static function pollHcard($hcard_url, $data, $dfrn = false)
1256 $curlResult = Network::curl($hcard_url);
1257 if ($curlResult->isTimeout()) {
1258 self::$istimeout = true;
1261 $content = $curlResult->getBody();
1266 $doc = new DOMDocument();
1267 if (!@$doc->loadHTML($content)) {
1271 $xpath = new DomXPath($doc);
1273 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1274 if (!is_object($vcards)) {
1278 if (!isset($data["baseurl"])) {
1279 $data["baseurl"] = "";
1282 if ($vcards->length > 0) {
1283 $vcard = $vcards->item(0);
1285 // We have to discard the guid from the hcard in favour of the guid from lrdd
1286 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1287 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1288 if (($search->length > 0) && empty($data["guid"])) {
1289 $data["guid"] = $search->item(0)->nodeValue;
1292 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1293 if ($search->length > 0) {
1294 $data["nick"] = $search->item(0)->nodeValue;
1297 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1298 if ($search->length > 0) {
1299 $data["name"] = $search->item(0)->nodeValue;
1302 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1303 if ($search->length > 0) {
1304 $data["searchable"] = $search->item(0)->nodeValue;
1307 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1308 if ($search->length > 0) {
1309 $data["pubkey"] = $search->item(0)->nodeValue;
1310 if (strstr($data["pubkey"], 'RSA ')) {
1311 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1315 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1316 if ($search->length > 0) {
1317 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1322 if (!empty($vcard)) {
1323 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1324 foreach ($photos as $photo) {
1326 foreach ($photo->attributes as $attribute) {
1327 $attr[$attribute->name] = trim($attribute->value);
1330 if (isset($attr["src"]) && isset($attr["width"])) {
1331 $avatar[$attr["width"]] = $attr["src"];
1334 // We don't have a width. So we just take everything that we got.
1335 // This is a Hubzilla workaround which doesn't send a width.
1336 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1337 $avatar[] = $attr["src"];
1342 if (sizeof($avatar)) {
1344 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1348 // Poll DFRN specific data
1349 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1350 if ($search->length > 0) {
1351 foreach ($search as $link) {
1352 //$data["request"] = $search->item(0)->nodeValue;
1354 foreach ($link->attributes as $attribute) {
1355 $attr[$attribute->name] = trim($attribute->value);
1358 $data[substr($attr["rel"], 5)] = $attr["href"];
1362 // Older Friendica versions had used the "uid" field differently than newer versions
1363 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1364 unset($data["guid"]);
1373 * Check for Diaspora contact
1375 * @param array $webfinger Webfinger data
1377 * @return array Diaspora data
1378 * @throws HTTPException\InternalServerErrorException
1380 private static function diaspora($webfinger)
1385 // The array is reversed to take into account the order of preference for same-rel links
1386 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1387 foreach (array_reverse($webfinger["links"]) as $link) {
1388 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1389 $hcard_url = $link["href"];
1390 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1391 $data["baseurl"] = trim($link["href"], '/');
1392 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1393 $data["guid"] = $link["href"];
1394 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1395 $data["url"] = $link["href"];
1396 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1397 $data["poll"] = $link["href"];
1398 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1399 $data["poco"] = $link["href"];
1400 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1401 $data["notify"] = $link["href"];
1402 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1403 $data["pubkey"] = base64_decode($link["href"]);
1405 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1406 if (strstr($data["pubkey"], 'RSA ')) {
1407 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1412 if (empty($data["url"]) || empty($hcard_url)) {
1416 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1417 foreach ($webfinger["aliases"] as $alias) {
1418 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1419 $data["alias"] = $alias;
1420 } elseif (substr($alias, 0, 5) == 'acct:') {
1421 $data["addr"] = substr($alias, 5);
1426 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1427 $data["addr"] = substr($webfinger["subject"], 5);
1430 // Fetch further information from the hcard
1431 $data = self::pollHcard($hcard_url, $data);
1437 if (!empty($data["url"])
1438 && !empty($data["guid"])
1439 && !empty($data["baseurl"])
1440 && !empty($data["pubkey"])
1441 && !empty($hcard_url)
1443 $data["network"] = Protocol::DIASPORA;
1445 // The Diaspora handle must always be lowercase
1446 if (!empty($data["addr"])) {
1447 $data["addr"] = strtolower($data["addr"]);
1450 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1451 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1452 $data["batch"] = $data["baseurl"] . "/receive/public";
1461 * Check for OStatus contact
1463 * @param array $webfinger Webfinger data
1464 * @param bool $short Short detection mode
1466 * @return array|bool OStatus data or "false" on error or "true" on short mode
1467 * @throws HTTPException\InternalServerErrorException
1469 private static function ostatus($webfinger, $short = false)
1473 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1474 foreach ($webfinger["aliases"] as $alias) {
1475 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1476 $data["addr"] = str_replace('acct:', '', $alias);
1481 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1482 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1484 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1487 if (is_array($webfinger["links"])) {
1488 // The array is reversed to take into account the order of preference for same-rel links
1489 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1490 foreach (array_reverse($webfinger["links"]) as $link) {
1491 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1492 && (($link["type"] ?? "") == "text/html")
1493 && ($link["href"] != "")
1495 $data["url"] = $link["href"];
1496 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1497 $data["notify"] = $link["href"];
1498 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1499 $data["poll"] = $link["href"];
1500 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1501 $pubkey = $link["href"];
1503 if (substr($pubkey, 0, 5) === 'data:') {
1504 if (strstr($pubkey, ',')) {
1505 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1507 $pubkey = substr($pubkey, 5);
1509 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1510 $curlResult = Network::curl($pubkey);
1511 if ($curlResult->isTimeout()) {
1512 self::$istimeout = true;
1515 $pubkey = $curlResult->getBody();
1518 $key = explode(".", $pubkey);
1520 if (sizeof($key) >= 3) {
1521 $m = Strings::base64UrlDecode($key[1]);
1522 $e = Strings::base64UrlDecode($key[2]);
1523 $data["pubkey"] = Crypto::meToPem($m, $e);
1529 if (isset($data["notify"]) && isset($data["pubkey"])
1530 && isset($data["poll"])
1531 && isset($data["url"])
1533 $data["network"] = Protocol::OSTATUS;
1542 // Fetch all additional data from the feed
1543 $curlResult = Network::curl($data["poll"]);
1544 if ($curlResult->isTimeout()) {
1545 self::$istimeout = true;
1548 $feed = $curlResult->getBody();
1549 $feed_data = Feed::import($feed);
1554 if (!empty($feed_data["header"]["author-name"])) {
1555 $data["name"] = $feed_data["header"]["author-name"];
1557 if (!empty($feed_data["header"]["author-nick"])) {
1558 $data["nick"] = $feed_data["header"]["author-nick"];
1560 if (!empty($feed_data["header"]["author-avatar"])) {
1561 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1563 if (!empty($feed_data["header"]["author-id"])) {
1564 $data["alias"] = $feed_data["header"]["author-id"];
1566 if (!empty($feed_data["header"]["author-location"])) {
1567 $data["location"] = $feed_data["header"]["author-location"];
1569 if (!empty($feed_data["header"]["author-about"])) {
1570 $data["about"] = $feed_data["header"]["author-about"];
1572 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1573 // So we take the value that we just fetched, although the other one worked as well
1574 if (!empty($feed_data["header"]["author-link"])) {
1575 $data["url"] = $feed_data["header"]["author-link"];
1578 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1579 $data['url'] = $data["alias"];
1580 $data["alias"] = '';
1583 /// @todo Fetch location and "about" from the feed as well
1588 * Fetch data from a pump.io profile page
1590 * @param string $profile_link Link to the profile page
1592 * @return array profile data
1594 private static function pumpioProfileData($profile_link)
1596 $curlResult = Network::curl($profile_link);
1597 if (!$curlResult->isSuccess()) {
1601 $doc = new DOMDocument();
1602 if (!@$doc->loadHTML($curlResult->getBody())) {
1606 $xpath = new DomXPath($doc);
1610 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1612 if ($data["name"] == '') {
1613 // This is ugly - but pump.io doesn't seem to know a better way for it
1614 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1615 $pos = strpos($data["name"], chr(10));
1617 $data["name"] = trim(substr($data["name"], 0, $pos));
1621 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1623 if ($data["location"] == '') {
1624 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1627 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1629 if ($data["about"] == '') {
1630 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1633 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1635 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1638 foreach ($avatar->attributes as $attribute) {
1639 if ($attribute->name == "src") {
1640 $data["photo"] = trim($attribute->value);
1649 * Check for pump.io contact
1651 * @param array $webfinger Webfinger data
1652 * @param string $addr
1653 * @return array pump.io data
1655 private static function pumpio($webfinger, $addr)
1658 // The array is reversed to take into account the order of preference for same-rel links
1659 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1660 foreach (array_reverse($webfinger["links"]) as $link) {
1661 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1662 && (($link["type"] ?? "") == "text/html")
1663 && ($link["href"] != "")
1665 $data["url"] = $link["href"];
1666 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1667 $data["notify"] = $link["href"];
1668 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1669 $data["poll"] = $link["href"];
1670 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1671 $data["dialback"] = $link["href"];
1674 if (isset($data["poll"]) && isset($data["notify"])
1675 && isset($data["dialback"])
1676 && isset($data["url"])
1678 // by now we use these fields only for the network type detection
1679 // So we unset all data that isn't used at the moment
1680 unset($data["dialback"]);
1682 $data["network"] = Protocol::PUMPIO;
1687 $profile_data = self::pumpioProfileData($data["url"]);
1689 if (!$profile_data) {
1693 $data = array_merge($data, $profile_data);
1695 if (($addr != '') && ($data['name'] != '')) {
1696 $name = trim(str_replace($addr, '', $data['name']));
1698 $data['name'] = $name;
1706 * Check for twitter contact
1708 * @param string $uri
1710 * @return array twitter data
1712 private static function twitter($uri)
1714 if (preg_match('=(.*)@twitter.com=i', $uri, $matches)) {
1715 $nick = $matches[1];
1716 } elseif (preg_match('=https?://twitter.com/(.*)=i', $uri, $matches)) {
1717 $nick = $matches[1];
1723 $data['url'] = 'https://twitter.com/' . $nick;
1724 $data['addr'] = $nick . '@twitter.com';
1725 $data['nick'] = $data['name'] = $nick;
1726 $data['network'] = Protocol::TWITTER;
1727 $data['baseurl'] = 'https://twitter.com';
1729 $curlResult = Network::curl($data['url'], false);
1730 if (!$curlResult->isSuccess()) {
1734 $body = $curlResult->getBody();
1735 $doc = new DOMDocument();
1736 @$doc->loadHTML($body);
1737 $xpath = new DOMXPath($doc);
1739 $list = $xpath->query('//img[@class]');
1740 foreach ($list as $node) {
1742 if ($node->attributes->length) {
1743 foreach ($node->attributes as $attribute) {
1744 $img_attr[$attribute->name] = $attribute->value;
1748 if (empty($img_attr['class'])) {
1752 if (strpos($img_attr['class'], 'ProfileAvatar-image') !== false) {
1753 if (!empty($img_attr['src'])) {
1754 $data['photo'] = $img_attr['src'];
1756 if (!empty($img_attr['alt'])) {
1757 $data['name'] = $img_attr['alt'];
1766 * Checks HTML page for RSS feed link
1768 * @param string $url Page link
1769 * @param string $body Page body string
1770 * @return string|false Feed link or false if body was invalid HTML document
1772 public static function getFeedLink(string $url, string $body)
1774 $doc = new DOMDocument();
1775 if (!@$doc->loadHTML($body)) {
1779 $xpath = new DOMXPath($doc);
1781 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1783 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1789 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1791 * Loosely based on RFC 1808
1793 * @see https://tools.ietf.org/html/rfc1808
1795 * @param string $href The potential relative href found in the HTML document
1796 * @param string $base The HTML document URL
1797 * @param DOMXPath $xpath The HTML document XPath
1800 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath)
1802 if (filter_var($href, FILTER_VALIDATE_URL)) {
1806 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1808 $baseParts = parse_url($base);
1810 // Naked domain case (scheme://basehost)
1811 $path = $baseParts['path'] ?? '/';
1813 // Remove the filename part of the path if it exists (/base/path/file)
1814 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1816 $hrefParts = parse_url($href);
1818 // Root path case (/path) including relative scheme case (//host/path)
1819 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1820 $path = $hrefParts['path'];
1822 $path = $path . '/' . $hrefParts['path'];
1824 // Resolve arbitrary relative path
1825 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1826 $parts = array_filter(explode('/', $path), 'strlen');
1827 $absolutes = array();
1828 foreach ($parts as $part) {
1829 if ('.' == $part) continue;
1830 if ('..' == $part) {
1831 array_pop($absolutes);
1833 $absolutes[] = $part;
1837 $path = '/' . implode('/', $absolutes);
1840 // Relative scheme case (//host/path)
1841 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1842 $baseParts['path'] = $path;
1843 unset($baseParts['query']);
1844 unset($baseParts['fragment']);
1846 return Network::unparseURL($baseParts);
1850 * Check for feed contact
1852 * @param string $url Profile link
1853 * @param boolean $probe Do a probe if the page contains a feed link
1855 * @return array feed data
1856 * @throws HTTPException\InternalServerErrorException
1858 private static function feed($url, $probe = true)
1860 $curlResult = Network::curl($url);
1861 if ($curlResult->isTimeout()) {
1862 self::$istimeout = true;
1865 $feed = $curlResult->getBody();
1866 $feed_data = Feed::import($feed);
1873 $feed_url = self::getFeedLink($url, $feed);
1879 return self::feed($feed_url, false);
1882 if (!empty($feed_data["header"]["author-name"])) {
1883 $data["name"] = $feed_data["header"]["author-name"];
1886 if (!empty($feed_data["header"]["author-nick"])) {
1887 $data["nick"] = $feed_data["header"]["author-nick"];
1890 if (!empty($feed_data["header"]["author-avatar"])) {
1891 $data["photo"] = $feed_data["header"]["author-avatar"];
1894 if (!empty($feed_data["header"]["author-id"])) {
1895 $data["alias"] = $feed_data["header"]["author-id"];
1898 $data["url"] = $url;
1899 $data["poll"] = $url;
1901 if (!empty($feed_data["header"]["author-link"])) {
1902 $data["baseurl"] = $feed_data["header"]["author-link"];
1904 $data["baseurl"] = $data["url"];
1907 $data["network"] = Protocol::FEED;
1913 * Check for mail contact
1915 * @param string $uri Profile link
1916 * @param integer $uid User ID
1918 * @return array mail data
1919 * @throws \Exception
1921 private static function mail($uri, $uid)
1923 if (!Network::isEmailDomainValid($uri)) {
1931 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1933 $condition = ["`uid` = ? AND `server` != ''", $uid];
1934 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1935 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1937 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1941 $mailbox = Email::constructMailboxName($mailacct);
1943 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1944 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1949 $msgs = Email::poll($mbox, $uri);
1950 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1952 if (!count($msgs)) {
1956 $phost = substr($uri, strpos($uri, '@') + 1);
1959 $data["addr"] = $uri;
1960 $data["network"] = Protocol::MAIL;
1961 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1962 $data["nick"] = $data["name"];
1963 $data["photo"] = Network::lookupAvatarByEmail($uri);
1964 $data["url"] = 'mailto:'.$uri;
1965 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1966 $data["poll"] = 'email ' . Strings::getRandomHex();
1968 $x = Email::messageMeta($mbox, $msgs[0]);
1969 if (stristr($x[0]->from, $uri)) {
1970 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1971 } elseif (stristr($x[0]->to, $uri)) {
1972 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1975 foreach ($adr as $feadr) {
1976 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1977 &&(strcasecmp($feadr->host, $phost) == 0)
1978 && (strlen($feadr->personal))
1980 $personal = imap_mime_header_decode($feadr->personal);
1982 foreach ($personal as $perspart) {
1983 if ($perspart->charset != "default") {
1984 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1986 $data["name"] .= $perspart->text;
1990 $data["name"] = Strings::escapeTags($data["name"]);
1994 if (!empty($mbox)) {
2001 * Mix two paths together to possibly fix missing parts
2003 * @param string $avatar Path to the avatar
2004 * @param string $base Another path that is hopefully complete
2006 * @return string fixed avatar path
2007 * @throws \Exception
2009 public static function fixAvatar($avatar, $base)
2011 $base_parts = parse_url($base);
2013 // Remove all parts that could create a problem
2014 unset($base_parts['path']);
2015 unset($base_parts['query']);
2016 unset($base_parts['fragment']);
2018 $avatar_parts = parse_url($avatar);
2021 $parts = array_merge($base_parts, $avatar_parts);
2023 // And put them together again
2024 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
2025 $host = isset($parts['host']) ? $parts['host'] : '';
2026 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
2027 $path = isset($parts['path']) ? $parts['path'] : '';
2028 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
2029 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
2031 $fixed = $scheme.$host.$port.$path.$query.$fragment;
2033 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);