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", "subscribe", "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 * Check an URI for LRDD data
276 * @param string $uri Address that should be probed
278 * @return array uri data
279 * @throws HTTPException\InternalServerErrorException
281 public static function lrdd(string $uri)
283 $lrdd = self::hostMeta($uri);
286 if (is_bool($lrdd)) {
291 $parts = @parse_url($uri);
292 if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
296 $host = $parts['scheme'] . '://' . $parts["host"];
297 if (!empty($parts["port"])) {
298 $host .= ':'.$parts["port"];
301 $path_parts = explode("/", trim($parts["path"], "/"));
303 $nick = array_pop($path_parts);
306 $lrdd = self::hostMeta($host);
307 $host .= "/".array_shift($path_parts);
308 } while (!$lrdd && (sizeof($path_parts) > 0));
312 Logger::log("No lrdd data found for ".$uri, Logger::DEBUG);
316 foreach ($lrdd as $type => $template) {
321 $path = str_replace('{uri}', urlencode($uri), $template);
322 $webfinger = self::webfinger($path, $type);
324 if (!$webfinger && (strstr($uri, "@"))) {
325 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
326 $webfinger = self::webfinger($path, $type);
329 // Special treatment for Mastodon
330 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
331 // But the webfinger for this format fails.
332 if (!$webfinger && !empty($nick)) {
333 // Mastodon uses a "@" as prefix for usernames in their url format
334 $nick = ltrim($nick, '@');
336 $addr = $nick."@".$host;
338 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
339 $webfinger = self::webfinger($path, $type);
343 if (empty($webfinger["links"])) {
344 Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
350 foreach ($webfinger["links"] as $link) {
351 $data[] = ["@attributes" => $link];
354 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
355 foreach ($webfinger["aliases"] as $alias) {
356 $data[] = ["@attributes" =>
366 * Fetch information (protocol endpoints and user information) about a given uri
368 * @param string $uri Address that should be probed
369 * @param string $network Test for this specific network
370 * @param integer $uid User ID for the probe (only used for mails)
371 * @param boolean $cache Use cached values?
373 * @return array uri data
374 * @throws HTTPException\InternalServerErrorException
375 * @throws \ImagickException
377 public static function uri($uri, $network = '', $uid = -1, $cache = true)
380 $result = DI::cache()->get('Probe::uri:' . $network . ':' . $uri);
381 if (!is_null($result)) {
390 self::$istimeout = false;
392 if ($network != Protocol::ACTIVITYPUB) {
393 $data = self::detect($uri, $network, $uid);
398 // When the previous detection process had got a time out
399 // we could falsely detect a Friendica profile as AP profile.
400 if (!self::$istimeout) {
401 $ap_profile = ActivityPub::probeProfile($uri);
403 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
405 } elseif (!empty($ap_profile)) {
406 $ap_profile['batch'] = '';
407 $data = array_merge($ap_profile, $data);
410 Logger::notice('Time out detected. AP will not be probed.', ['uri' => $uri]);
413 if (!isset($data['url'])) {
417 if (empty($data['photo'])) {
418 $data['photo'] = DI::baseUrl() . '/images/person-300.jpg';
421 if (empty($data['name'])) {
422 if (!empty($data['nick'])) {
423 $data['name'] = $data['nick'];
426 if (empty($data['name'])) {
427 $data['name'] = $data['url'];
431 if (empty($data['nick'])) {
432 $data['nick'] = strtolower($data['name']);
434 if (strpos($data['nick'], ' ')) {
435 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
439 if (!empty(self::$baseurl)) {
440 $data['baseurl'] = self::$baseurl;
443 if (!empty($data['baseurl']) && empty($data['gsid'])) {
444 $data['gsid'] = GServer::getID($data['baseurl']);
447 if (empty($data['network'])) {
448 $data['network'] = Protocol::PHANTOM;
451 // Ensure that local connections always are DFRN
452 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
453 $data['network'] = Protocol::DFRN;
456 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
457 $data['hide'] = self::getHideStatus($data['url']);
460 $data = self::rearrangeData($data);
462 // Only store into the cache if the value seems to be valid
463 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
464 DI::cache()->set('Probe::uri:' . $network . ':' . $uri, $data, Duration::DAY);
472 * Fetches the "hide" status from the profile
474 * @param string $url URL of the profile
476 * @return boolean "hide" status
478 private static function getHideStatus($url)
480 $curlResult = Network::curl($url);
481 if (!$curlResult->isSuccess()) {
485 // If the file is too large then exit
486 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
490 // If it isn't a HTML file then exit
491 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
495 $body = $curlResult->getBody();
497 $doc = new DOMDocument();
498 @$doc->loadHTML($body);
500 $xpath = new DOMXPath($doc);
502 $list = $xpath->query('//meta[@name]');
503 foreach ($list as $node) {
505 if ($node->attributes->length) {
506 foreach ($node->attributes as $attribute) {
507 $meta_tag[$attribute->name] = $attribute->value;
511 if (empty($meta_tag['content'])) {
515 $content = strtolower(trim($meta_tag['content']));
517 switch (strtolower(trim($meta_tag['name']))) {
518 case 'dfrn-global-visibility':
519 if ($content == 'false') {
524 if (strpos($content, 'noindex') !== false) {
535 * Checks if a profile url should be OStatus but only provides partial information
537 * @param array $webfinger Webfinger data
538 * @param string $lrdd Path template for webfinger request
539 * @param string $type type
541 * @return array fixed webfinger data
542 * @throws HTTPException\InternalServerErrorException
544 private static function fixOStatus($webfinger, $lrdd, $type)
546 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
553 foreach ($webfinger['links'] as $link) {
554 if ($link['rel'] == ActivityNamespace::OSTATUSSUB) {
557 if ($link['rel'] == 'magic-public-key') {
562 if (!$is_ostatus || $has_key) {
566 $url = Network::switchScheme($webfinger['subject']);
567 $path = str_replace('{uri}', urlencode($url), $lrdd);
568 $webfinger2 = self::webfinger($path, $type);
570 // Is the new webfinger detectable as OStatus?
571 if (self::ostatus($webfinger2, true)) {
572 $webfinger = $webfinger2;
579 * Fetch the "subscribe" and add it to the result
581 * @param array $result
582 * @param array $webfinger
583 * @return array result
585 private static function getSubscribeLink(array $result, array $webfinger)
587 if (empty($webfinger['links'])) {
591 foreach ($webfinger['links'] as $link) {
592 if ($link['rel'] === ActivityNamespace::OSTATUSSUB) {
593 $result['subscribe'] = $link['template'];
601 * Fetch information (protocol endpoints and user information) about a given uri
603 * This function is only called by the "uri" function that adds caching and rearranging of data.
605 * @param string $uri Address that should be probed
606 * @param string $network Test for this specific network
607 * @param integer $uid User ID for the probe (only used for mails)
609 * @return array uri data
610 * @throws HTTPException\InternalServerErrorException
612 private static function detect($uri, $network, $uid)
614 $parts = parse_url($uri);
616 if (!empty($parts["scheme"]) && !empty($parts["host"])) {
617 $host = $parts["host"];
618 if (!empty($parts["port"])) {
619 $host .= ':'.$parts["port"];
622 if ($host == 'twitter.com') {
623 return self::twitter($uri);
625 $lrdd = self::hostMeta($host);
627 if (is_bool($lrdd)) {
631 $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
633 while (!$lrdd && (sizeof($path_parts) > 1)) {
634 $host .= "/".array_shift($path_parts);
635 $lrdd = self::hostMeta($host);
638 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
639 return self::feed($uri);
641 $nick = array_pop($path_parts);
643 // Mastodon uses a "@" as prefix for usernames in their url format
644 $nick = ltrim($nick, '@');
646 $addr = $nick."@".$host;
647 } elseif (strstr($uri, '@')) {
648 // If the URI starts with "mailto:" then jump directly to the mail detection
649 if (strpos($uri, 'mailto:') !== false) {
650 $uri = str_replace('mailto:', '', $uri);
651 return self::mail($uri, $uid);
654 if ($network == Protocol::MAIL) {
655 return self::mail($uri, $uid);
657 // Remove "acct:" from the URI
658 $uri = str_replace('acct:', '', $uri);
660 $host = substr($uri, strpos($uri, '@') + 1);
661 $nick = substr($uri, 0, strpos($uri, '@'));
663 if (strpos($uri, '@twitter.com')) {
664 return self::twitter($uri);
666 $lrdd = self::hostMeta($host);
668 if (is_bool($lrdd)) {
673 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
674 return self::mail($uri, $uid);
678 Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
684 /// @todo Do we need the prefix "acct:" or "acct://"?
686 foreach ($lrdd as $type => $template) {
691 // At first try it with the given uri
692 $path = str_replace('{uri}', urlencode($uri), $template);
693 $webfinger = self::webfinger($path, $type);
695 // Fix possible problems with GNU Social probing to wrong scheme
696 $webfinger = self::fixOStatus($webfinger, $template, $type);
698 // We cannot be sure that the detected address was correct, so we don't use the values
699 if ($webfinger && ($uri != $addr)) {
704 // Try webfinger with the address (user@domain.tld)
706 $path = str_replace('{uri}', urlencode($addr), $template);
707 $webfinger = self::webfinger($path, $type);
710 // Mastodon needs to have it with "acct:"
712 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
713 $webfinger = self::webfinger($path, $type);
718 return self::feed($uri);
723 Logger::info("Probing", ['uri' => $uri]);
725 if (in_array($network, ["", Protocol::DFRN])) {
726 $result = self::dfrn($webfinger);
728 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
729 $result = self::diaspora($webfinger);
731 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
732 $result = self::ostatus($webfinger);
734 if (in_array($network, ['', Protocol::ZOT])) {
735 $result = self::zot($webfinger, $result);
737 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
738 $result = self::pumpio($webfinger, $addr);
740 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
741 $result = self::feed($uri);
743 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
744 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
745 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
746 $result["nick"] = $nick;
749 if (empty($result["addr"]) && ($addr != "")) {
750 $result["addr"] = $addr;
754 $result = self::getSubscribeLink($result, $webfinger);
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;
777 * Check for Zot contact
779 * @param array $webfinger Webfinger data
780 * @param array $data previously probed data
782 * @return array Zot data
783 * @throws HTTPException\InternalServerErrorException
785 private static function zot($webfinger, $data)
787 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
788 foreach ($webfinger["aliases"] as $alias) {
789 if (substr($alias, 0, 5) == 'acct:') {
790 $data["addr"] = substr($alias, 5);
795 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
796 $data["addr"] = substr($webfinger["subject"], 5);
800 foreach ($webfinger['links'] as $link) {
801 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
802 $zot_url = $link['href'];
806 if (empty($zot_url) && !empty($data['addr']) && !empty(self::$baseurl)) {
807 $condition = ['nurl' => Strings::normaliseLink(self::$baseurl), 'platform' => ['hubzilla']];
808 if (!DBA::exists('gserver', $condition)) {
811 $zot_url = self::$baseurl . '/.well-known/zot-info?address=' . $data['addr'];
814 if (empty($zot_url)) {
818 $data = self::pollZot($zot_url, $data);
820 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
821 foreach ($webfinger['aliases'] as $alias) {
822 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
823 $data['alias'] = $alias;
831 public static function pollZot($url, $data)
833 $curlResult = Network::curl($url);
834 if ($curlResult->isTimeout()) {
837 $content = $curlResult->getBody();
842 $json = json_decode($content, true);
843 if (!is_array($json)) {
847 if (empty($data['network'])) {
848 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
849 $data['network'] = Protocol::ZOT;
850 } elseif (!isset($json['protocols'])) {
851 $data['network'] = Protocol::ZOT;
855 if (!empty($json['guid']) && empty($data['guid'])) {
856 $data['guid'] = $json['guid'];
858 if (!empty($json['key']) && empty($data['pubkey'])) {
859 $data['pubkey'] = $json['key'];
861 if (!empty($json['name'])) {
862 $data['name'] = $json['name'];
864 if (!empty($json['photo'])) {
865 $data['photo'] = $json['photo'];
866 if (!empty($json['photo_updated'])) {
867 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
870 if (!empty($json['address'])) {
871 $data['addr'] = $json['address'];
873 if (!empty($json['url'])) {
874 $data['url'] = $json['url'];
876 if (!empty($json['connections_url'])) {
877 $data['poco'] = $json['connections_url'];
879 if (isset($json['searchable'])) {
880 $data['hide'] = !$json['searchable'];
882 if (!empty($json['public_forum'])) {
883 $data['community'] = $json['public_forum'];
884 $data['account-type'] = Contact::PAGE_COMMUNITY;
887 if (!empty($json['profile'])) {
888 $profile = $json['profile'];
889 if (!empty($profile['description'])) {
890 $data['about'] = $profile['description'];
892 if (!empty($profile['keywords'])) {
893 $keywords = implode(', ', $profile['keywords']);
894 if (!empty($keywords)) {
895 $data['keywords'] = $keywords;
900 if (!empty($profile['region'])) {
901 $loc['region'] = $profile['region'];
903 if (!empty($profile['country'])) {
904 $loc['country-name'] = $profile['country'];
906 $location = Profile::formatLocation($loc);
907 if (!empty($location)) {
908 $data['location'] = $location;
916 * Perform a webfinger request.
918 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
920 * @param string $url Address that should be probed
921 * @param string $type type
923 * @return array webfinger data
924 * @throws HTTPException\InternalServerErrorException
926 public static function webfinger($url, $type)
928 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
930 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
931 if ($curlResult->isTimeout()) {
932 self::$istimeout = true;
935 $data = $curlResult->getBody();
937 $webfinger = json_decode($data, true);
938 if (!empty($webfinger)) {
939 if (!isset($webfinger["links"])) {
940 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
946 // If it is not JSON, maybe it is XML
947 $xrd = XML::parseString($data, true);
948 if (!is_object($xrd)) {
949 Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
953 $xrd_arr = XML::elementToArray($xrd);
954 if (!isset($xrd_arr["xrd"]["link"])) {
955 Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
961 if (!empty($xrd_arr["xrd"]["subject"])) {
962 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
965 if (!empty($xrd_arr["xrd"]["alias"])) {
966 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
969 $webfinger["links"] = [];
971 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
972 if (!empty($data["@attributes"])) {
973 $attributes = $data["@attributes"];
974 } elseif ($value == "@attributes") {
980 $webfinger["links"][] = $attributes;
986 * Poll the Friendica specific noscrape page.
988 * "noscrape" is a faster alternative to fetch the data from the hcard.
989 * This functionality was originally created for the directory.
991 * @param string $noscrape_url Link to the noscrape page
992 * @param array $data The already fetched data
994 * @return array noscrape data
995 * @throws HTTPException\InternalServerErrorException
997 private static function pollNoscrape($noscrape_url, $data)
999 $curlResult = Network::curl($noscrape_url);
1000 if ($curlResult->isTimeout()) {
1001 self::$istimeout = true;
1004 $content = $curlResult->getBody();
1006 Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
1010 $json = json_decode($content, true);
1011 if (!is_array($json)) {
1012 Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
1016 if (!empty($json["fn"])) {
1017 $data["name"] = $json["fn"];
1020 if (!empty($json["addr"])) {
1021 $data["addr"] = $json["addr"];
1024 if (!empty($json["nick"])) {
1025 $data["nick"] = $json["nick"];
1028 if (!empty($json["guid"])) {
1029 $data["guid"] = $json["guid"];
1032 if (!empty($json["comm"])) {
1033 $data["community"] = $json["comm"];
1036 if (!empty($json["tags"])) {
1037 $keywords = implode(", ", $json["tags"]);
1038 if ($keywords != "") {
1039 $data["keywords"] = $keywords;
1043 $location = Profile::formatLocation($json);
1045 $data["location"] = $location;
1048 if (!empty($json["about"])) {
1049 $data["about"] = $json["about"];
1052 if (!empty($json["key"])) {
1053 $data["pubkey"] = $json["key"];
1056 if (!empty($json["photo"])) {
1057 $data["photo"] = $json["photo"];
1060 if (!empty($json["dfrn-request"])) {
1061 $data["request"] = $json["dfrn-request"];
1064 if (!empty($json["dfrn-confirm"])) {
1065 $data["confirm"] = $json["dfrn-confirm"];
1068 if (!empty($json["dfrn-notify"])) {
1069 $data["notify"] = $json["dfrn-notify"];
1072 if (!empty($json["dfrn-poll"])) {
1073 $data["poll"] = $json["dfrn-poll"];
1076 if (isset($json["hide"])) {
1077 $data["hide"] = (bool)$json["hide"];
1079 $data["hide"] = false;
1086 * Check for valid DFRN data
1088 * @param array $data DFRN data
1090 * @return int Number of errors
1092 public static function validDfrn($data)
1095 if (!isset($data['key'])) {
1098 if (!isset($data['dfrn-request'])) {
1101 if (!isset($data['dfrn-confirm'])) {
1104 if (!isset($data['dfrn-notify'])) {
1107 if (!isset($data['dfrn-poll'])) {
1114 * Fetch data from a DFRN profile page and via "noscrape"
1116 * @param string $profile_link Link to the profile page
1118 * @return array profile data
1119 * @throws HTTPException\InternalServerErrorException
1120 * @throws \ImagickException
1122 public static function profile($profile_link)
1126 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
1128 // Fetch data via noscrape - this is faster
1129 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1130 $data = self::pollNoscrape($noscrape_url, $data);
1132 if (!isset($data["notify"])
1133 || !isset($data["confirm"])
1134 || !isset($data["request"])
1135 || !isset($data["poll"])
1136 || !isset($data["name"])
1137 || !isset($data["photo"])
1139 $data = self::pollHcard($profile_link, $data, true);
1144 if (empty($data["addr"]) || empty($data["nick"])) {
1145 $probe_data = self::uri($profile_link);
1146 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1147 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1150 $prof_data["addr"] = $data["addr"];
1151 $prof_data["nick"] = $data["nick"];
1152 $prof_data["dfrn-request"] = $data['request'] ?? null;
1153 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1154 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1155 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1156 $prof_data["photo"] = $data['photo'] ?? null;
1157 $prof_data["fn"] = $data['name'] ?? null;
1158 $prof_data["key"] = $data['pubkey'] ?? null;
1160 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
1166 * Check for DFRN contact
1168 * @param array $webfinger Webfinger data
1170 * @return array DFRN data
1171 * @throws HTTPException\InternalServerErrorException
1173 private static function dfrn($webfinger)
1177 // The array is reversed to take into account the order of preference for same-rel links
1178 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1179 foreach (array_reverse($webfinger["links"]) as $link) {
1180 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1181 $data["network"] = Protocol::DFRN;
1182 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1183 $data["poll"] = $link["href"];
1184 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1185 $data["url"] = $link["href"];
1186 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1187 $hcard_url = $link["href"];
1188 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1189 $data["poco"] = $link["href"];
1190 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1191 $data["photo"] = $link["href"];
1192 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1193 $data["baseurl"] = trim($link["href"], '/');
1194 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1195 $data["guid"] = $link["href"];
1196 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1197 $data["pubkey"] = base64_decode($link["href"]);
1199 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1200 if (strstr($data["pubkey"], 'RSA ')) {
1201 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1206 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1207 foreach ($webfinger["aliases"] as $alias) {
1208 if (empty($data["url"]) && !strstr($alias, "@")) {
1209 $data["url"] = $alias;
1210 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1211 $data["alias"] = $alias;
1212 } elseif (substr($alias, 0, 5) == 'acct:') {
1213 $data["addr"] = substr($alias, 5);
1218 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1219 $data["addr"] = substr($webfinger["subject"], 5);
1222 if (!isset($data["network"]) || ($hcard_url == "")) {
1226 // Fetch data via noscrape - this is faster
1227 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1228 $data = self::pollNoscrape($noscrape_url, $data);
1230 if (isset($data["notify"])
1231 && isset($data["confirm"])
1232 && isset($data["request"])
1233 && isset($data["poll"])
1234 && isset($data["name"])
1235 && isset($data["photo"])
1240 $data = self::pollHcard($hcard_url, $data, true);
1246 * Poll the hcard page (Diaspora and Friendica specific)
1248 * @param string $hcard_url Link to the hcard page
1249 * @param array $data The already fetched data
1250 * @param boolean $dfrn Poll DFRN specific data
1252 * @return array hcard data
1253 * @throws HTTPException\InternalServerErrorException
1255 private static function pollHcard($hcard_url, $data, $dfrn = false)
1257 $curlResult = Network::curl($hcard_url);
1258 if ($curlResult->isTimeout()) {
1259 self::$istimeout = true;
1262 $content = $curlResult->getBody();
1267 $doc = new DOMDocument();
1268 if (!@$doc->loadHTML($content)) {
1272 $xpath = new DomXPath($doc);
1274 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1275 if (!is_object($vcards)) {
1279 if (!isset($data["baseurl"])) {
1280 $data["baseurl"] = "";
1283 if ($vcards->length > 0) {
1284 $vcard = $vcards->item(0);
1286 // We have to discard the guid from the hcard in favour of the guid from lrdd
1287 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1288 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1289 if (($search->length > 0) && empty($data["guid"])) {
1290 $data["guid"] = $search->item(0)->nodeValue;
1293 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1294 if ($search->length > 0) {
1295 $data["nick"] = $search->item(0)->nodeValue;
1298 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1299 if ($search->length > 0) {
1300 $data["name"] = $search->item(0)->nodeValue;
1303 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1304 if ($search->length > 0) {
1305 $data["searchable"] = $search->item(0)->nodeValue;
1308 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1309 if ($search->length > 0) {
1310 $data["pubkey"] = $search->item(0)->nodeValue;
1311 if (strstr($data["pubkey"], 'RSA ')) {
1312 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1316 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1317 if ($search->length > 0) {
1318 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1323 if (!empty($vcard)) {
1324 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1325 foreach ($photos as $photo) {
1327 foreach ($photo->attributes as $attribute) {
1328 $attr[$attribute->name] = trim($attribute->value);
1331 if (isset($attr["src"]) && isset($attr["width"])) {
1332 $avatar[$attr["width"]] = $attr["src"];
1335 // We don't have a width. So we just take everything that we got.
1336 // This is a Hubzilla workaround which doesn't send a width.
1337 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1338 $avatar[] = $attr["src"];
1343 if (sizeof($avatar)) {
1345 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1349 // Poll DFRN specific data
1350 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1351 if ($search->length > 0) {
1352 foreach ($search as $link) {
1353 //$data["request"] = $search->item(0)->nodeValue;
1355 foreach ($link->attributes as $attribute) {
1356 $attr[$attribute->name] = trim($attribute->value);
1359 $data[substr($attr["rel"], 5)] = $attr["href"];
1363 // Older Friendica versions had used the "uid" field differently than newer versions
1364 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1365 unset($data["guid"]);
1374 * Check for Diaspora contact
1376 * @param array $webfinger Webfinger data
1378 * @return array Diaspora data
1379 * @throws HTTPException\InternalServerErrorException
1381 private static function diaspora($webfinger)
1386 // The array is reversed to take into account the order of preference for same-rel links
1387 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1388 foreach (array_reverse($webfinger["links"]) as $link) {
1389 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1390 $hcard_url = $link["href"];
1391 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1392 $data["baseurl"] = trim($link["href"], '/');
1393 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1394 $data["guid"] = $link["href"];
1395 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1396 $data["url"] = $link["href"];
1397 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1398 $data["poll"] = $link["href"];
1399 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1400 $data["poco"] = $link["href"];
1401 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1402 $data["notify"] = $link["href"];
1403 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1404 $data["pubkey"] = base64_decode($link["href"]);
1406 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1407 if (strstr($data["pubkey"], 'RSA ')) {
1408 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1413 if (empty($data["url"]) || empty($hcard_url)) {
1417 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1418 foreach ($webfinger["aliases"] as $alias) {
1419 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1420 $data["alias"] = $alias;
1421 } elseif (substr($alias, 0, 5) == 'acct:') {
1422 $data["addr"] = substr($alias, 5);
1427 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1428 $data["addr"] = substr($webfinger["subject"], 5);
1431 // Fetch further information from the hcard
1432 $data = self::pollHcard($hcard_url, $data);
1438 if (!empty($data["url"])
1439 && !empty($data["guid"])
1440 && !empty($data["baseurl"])
1441 && !empty($data["pubkey"])
1442 && !empty($hcard_url)
1444 $data["network"] = Protocol::DIASPORA;
1446 // The Diaspora handle must always be lowercase
1447 if (!empty($data["addr"])) {
1448 $data["addr"] = strtolower($data["addr"]);
1451 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1452 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1453 $data["batch"] = $data["baseurl"] . "/receive/public";
1462 * Check for OStatus contact
1464 * @param array $webfinger Webfinger data
1465 * @param bool $short Short detection mode
1467 * @return array|bool OStatus data or "false" on error or "true" on short mode
1468 * @throws HTTPException\InternalServerErrorException
1470 private static function ostatus($webfinger, $short = false)
1474 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1475 foreach ($webfinger["aliases"] as $alias) {
1476 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1477 $data["addr"] = str_replace('acct:', '', $alias);
1482 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1483 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1485 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1488 if (!empty($webfinger["links"])) {
1489 // The array is reversed to take into account the order of preference for same-rel links
1490 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1491 foreach (array_reverse($webfinger["links"]) as $link) {
1492 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1493 && (($link["type"] ?? "") == "text/html")
1494 && ($link["href"] != "")
1496 $data["url"] = $link["href"];
1497 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1498 $data["notify"] = $link["href"];
1499 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1500 $data["poll"] = $link["href"];
1501 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1502 $pubkey = $link["href"];
1504 if (substr($pubkey, 0, 5) === 'data:') {
1505 if (strstr($pubkey, ',')) {
1506 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1508 $pubkey = substr($pubkey, 5);
1510 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1511 $curlResult = Network::curl($pubkey);
1512 if ($curlResult->isTimeout()) {
1513 self::$istimeout = true;
1514 return $short ? false : [];
1516 $pubkey = $curlResult->getBody();
1519 $key = explode(".", $pubkey);
1521 if (sizeof($key) >= 3) {
1522 $m = Strings::base64UrlDecode($key[1]);
1523 $e = Strings::base64UrlDecode($key[2]);
1524 $data["pubkey"] = Crypto::meToPem($m, $e);
1530 if (isset($data["notify"]) && isset($data["pubkey"])
1531 && isset($data["poll"])
1532 && isset($data["url"])
1534 $data["network"] = Protocol::OSTATUS;
1536 return $short ? false : [];
1543 // Fetch all additional data from the feed
1544 $curlResult = Network::curl($data["poll"]);
1545 if ($curlResult->isTimeout()) {
1546 self::$istimeout = true;
1549 $feed = $curlResult->getBody();
1550 $feed_data = Feed::import($feed);
1555 if (!empty($feed_data["header"]["author-name"])) {
1556 $data["name"] = $feed_data["header"]["author-name"];
1558 if (!empty($feed_data["header"]["author-nick"])) {
1559 $data["nick"] = $feed_data["header"]["author-nick"];
1561 if (!empty($feed_data["header"]["author-avatar"])) {
1562 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1564 if (!empty($feed_data["header"]["author-id"])) {
1565 $data["alias"] = $feed_data["header"]["author-id"];
1567 if (!empty($feed_data["header"]["author-location"])) {
1568 $data["location"] = $feed_data["header"]["author-location"];
1570 if (!empty($feed_data["header"]["author-about"])) {
1571 $data["about"] = $feed_data["header"]["author-about"];
1573 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1574 // So we take the value that we just fetched, although the other one worked as well
1575 if (!empty($feed_data["header"]["author-link"])) {
1576 $data["url"] = $feed_data["header"]["author-link"];
1579 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1580 $data['url'] = $data["alias"];
1581 $data["alias"] = '';
1584 /// @todo Fetch location and "about" from the feed as well
1589 * Fetch data from a pump.io profile page
1591 * @param string $profile_link Link to the profile page
1593 * @return array profile data
1595 private static function pumpioProfileData($profile_link)
1597 $curlResult = Network::curl($profile_link);
1598 if (!$curlResult->isSuccess()) {
1602 $doc = new DOMDocument();
1603 if (!@$doc->loadHTML($curlResult->getBody())) {
1607 $xpath = new DomXPath($doc);
1611 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1613 if ($data["name"] == '') {
1614 // This is ugly - but pump.io doesn't seem to know a better way for it
1615 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1616 $pos = strpos($data["name"], chr(10));
1618 $data["name"] = trim(substr($data["name"], 0, $pos));
1622 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1624 if ($data["location"] == '') {
1625 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1628 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1630 if ($data["about"] == '') {
1631 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1634 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1636 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1639 foreach ($avatar->attributes as $attribute) {
1640 if ($attribute->name == "src") {
1641 $data["photo"] = trim($attribute->value);
1650 * Check for pump.io contact
1652 * @param array $webfinger Webfinger data
1653 * @param string $addr
1654 * @return array pump.io data
1656 private static function pumpio($webfinger, $addr)
1659 // The array is reversed to take into account the order of preference for same-rel links
1660 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1661 foreach (array_reverse($webfinger["links"]) as $link) {
1662 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1663 && (($link["type"] ?? "") == "text/html")
1664 && ($link["href"] != "")
1666 $data["url"] = $link["href"];
1667 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1668 $data["notify"] = $link["href"];
1669 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1670 $data["poll"] = $link["href"];
1671 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1672 $data["dialback"] = $link["href"];
1675 if (isset($data["poll"]) && isset($data["notify"])
1676 && isset($data["dialback"])
1677 && isset($data["url"])
1679 // by now we use these fields only for the network type detection
1680 // So we unset all data that isn't used at the moment
1681 unset($data["dialback"]);
1683 $data["network"] = Protocol::PUMPIO;
1688 $profile_data = self::pumpioProfileData($data["url"]);
1690 if (!$profile_data) {
1694 $data = array_merge($data, $profile_data);
1696 if (($addr != '') && ($data['name'] != '')) {
1697 $name = trim(str_replace($addr, '', $data['name']));
1699 $data['name'] = $name;
1707 * Check for twitter contact
1709 * @param string $uri
1711 * @return array twitter data
1713 private static function twitter($uri)
1715 if (preg_match('=(.*)@twitter.com=i', $uri, $matches)) {
1716 $nick = $matches[1];
1717 } elseif (preg_match('=https?://twitter.com/(.*)=i', $uri, $matches)) {
1718 $nick = $matches[1];
1724 $data['url'] = 'https://twitter.com/' . $nick;
1725 $data['addr'] = $nick . '@twitter.com';
1726 $data['nick'] = $data['name'] = $nick;
1727 $data['network'] = Protocol::TWITTER;
1728 $data['baseurl'] = 'https://twitter.com';
1730 $curlResult = Network::curl($data['url'], false);
1731 if (!$curlResult->isSuccess()) {
1735 $body = $curlResult->getBody();
1736 $doc = new DOMDocument();
1737 @$doc->loadHTML($body);
1738 $xpath = new DOMXPath($doc);
1740 $list = $xpath->query('//img[@class]');
1741 foreach ($list as $node) {
1743 if ($node->attributes->length) {
1744 foreach ($node->attributes as $attribute) {
1745 $img_attr[$attribute->name] = $attribute->value;
1749 if (empty($img_attr['class'])) {
1753 if (strpos($img_attr['class'], 'ProfileAvatar-image') !== false) {
1754 if (!empty($img_attr['src'])) {
1755 $data['photo'] = $img_attr['src'];
1757 if (!empty($img_attr['alt'])) {
1758 $data['name'] = $img_attr['alt'];
1767 * Checks HTML page for RSS feed link
1769 * @param string $url Page link
1770 * @param string $body Page body string
1771 * @return string|false Feed link or false if body was invalid HTML document
1773 public static function getFeedLink(string $url, string $body)
1775 $doc = new DOMDocument();
1776 if (!@$doc->loadHTML($body)) {
1780 $xpath = new DOMXPath($doc);
1782 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1784 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1790 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1792 * Loosely based on RFC 1808
1794 * @see https://tools.ietf.org/html/rfc1808
1796 * @param string $href The potential relative href found in the HTML document
1797 * @param string $base The HTML document URL
1798 * @param DOMXPath $xpath The HTML document XPath
1801 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath)
1803 if (filter_var($href, FILTER_VALIDATE_URL)) {
1807 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1809 $baseParts = parse_url($base);
1811 // Naked domain case (scheme://basehost)
1812 $path = $baseParts['path'] ?? '/';
1814 // Remove the filename part of the path if it exists (/base/path/file)
1815 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1817 $hrefParts = parse_url($href);
1819 // Root path case (/path) including relative scheme case (//host/path)
1820 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1821 $path = $hrefParts['path'];
1823 $path = $path . '/' . $hrefParts['path'];
1825 // Resolve arbitrary relative path
1826 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1827 $parts = array_filter(explode('/', $path), 'strlen');
1828 $absolutes = array();
1829 foreach ($parts as $part) {
1830 if ('.' == $part) continue;
1831 if ('..' == $part) {
1832 array_pop($absolutes);
1834 $absolutes[] = $part;
1838 $path = '/' . implode('/', $absolutes);
1841 // Relative scheme case (//host/path)
1842 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1843 $baseParts['path'] = $path;
1844 unset($baseParts['query']);
1845 unset($baseParts['fragment']);
1847 return Network::unparseURL($baseParts);
1851 * Check for feed contact
1853 * @param string $url Profile link
1854 * @param boolean $probe Do a probe if the page contains a feed link
1856 * @return array feed data
1857 * @throws HTTPException\InternalServerErrorException
1859 private static function feed($url, $probe = true)
1861 $curlResult = Network::curl($url);
1862 if ($curlResult->isTimeout()) {
1863 self::$istimeout = true;
1866 $feed = $curlResult->getBody();
1867 $feed_data = Feed::import($feed);
1874 $feed_url = self::getFeedLink($url, $feed);
1880 return self::feed($feed_url, false);
1883 if (!empty($feed_data["header"]["author-name"])) {
1884 $data["name"] = $feed_data["header"]["author-name"];
1887 if (!empty($feed_data["header"]["author-nick"])) {
1888 $data["nick"] = $feed_data["header"]["author-nick"];
1891 if (!empty($feed_data["header"]["author-avatar"])) {
1892 $data["photo"] = $feed_data["header"]["author-avatar"];
1895 if (!empty($feed_data["header"]["author-id"])) {
1896 $data["alias"] = $feed_data["header"]["author-id"];
1899 $data["url"] = $url;
1900 $data["poll"] = $url;
1902 if (!empty($feed_data["header"]["author-link"])) {
1903 $data["baseurl"] = $feed_data["header"]["author-link"];
1905 $data["baseurl"] = $data["url"];
1908 $data["network"] = Protocol::FEED;
1914 * Check for mail contact
1916 * @param string $uri Profile link
1917 * @param integer $uid User ID
1919 * @return array mail data
1920 * @throws \Exception
1922 private static function mail($uri, $uid)
1924 if (!Network::isEmailDomainValid($uri)) {
1932 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1934 $condition = ["`uid` = ? AND `server` != ''", $uid];
1935 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1936 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1938 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1942 $mailbox = Email::constructMailboxName($mailacct);
1944 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1945 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1950 $msgs = Email::poll($mbox, $uri);
1951 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1953 if (!count($msgs)) {
1957 $phost = substr($uri, strpos($uri, '@') + 1);
1960 $data["addr"] = $uri;
1961 $data["network"] = Protocol::MAIL;
1962 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1963 $data["nick"] = $data["name"];
1964 $data["photo"] = Network::lookupAvatarByEmail($uri);
1965 $data["url"] = 'mailto:'.$uri;
1966 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1967 $data["poll"] = 'email ' . Strings::getRandomHex();
1969 $x = Email::messageMeta($mbox, $msgs[0]);
1970 if (stristr($x[0]->from, $uri)) {
1971 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1972 } elseif (stristr($x[0]->to, $uri)) {
1973 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1976 foreach ($adr as $feadr) {
1977 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1978 &&(strcasecmp($feadr->host, $phost) == 0)
1979 && (strlen($feadr->personal))
1981 $personal = imap_mime_header_decode($feadr->personal);
1983 foreach ($personal as $perspart) {
1984 if ($perspart->charset != "default") {
1985 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1987 $data["name"] .= $perspart->text;
1991 $data["name"] = Strings::escapeTags($data["name"]);
1995 if (!empty($mbox)) {
2002 * Mix two paths together to possibly fix missing parts
2004 * @param string $avatar Path to the avatar
2005 * @param string $base Another path that is hopefully complete
2007 * @return string fixed avatar path
2008 * @throws \Exception
2010 public static function fixAvatar($avatar, $base)
2012 $base_parts = parse_url($base);
2014 // Remove all parts that could create a problem
2015 unset($base_parts['path']);
2016 unset($base_parts['query']);
2017 unset($base_parts['fragment']);
2019 $avatar_parts = parse_url($avatar);
2022 $parts = array_merge($base_parts, $avatar_parts);
2024 // And put them together again
2025 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
2026 $host = isset($parts['host']) ? $parts['host'] : '';
2027 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
2028 $path = isset($parts['path']) ? $parts['path'] : '';
2029 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
2030 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
2032 $fixed = $scheme.$host.$port.$path.$query.$fragment;
2034 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);