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 if (in_array($field, ["gsid", "hide", "account-type"])) {
96 $newdata[$field] = (int)$data[$field];
98 $newdata[$field] = $data[$field];
100 } elseif ($field != "gsid") {
101 $newdata[$field] = "";
103 $newdata[$field] = null;
107 // We don't use the "priority" field anymore and replace it with a dummy.
108 $newdata["priority"] = 0;
114 * Check if the hostname belongs to the own server
116 * @param string $host The hostname that is to be checked
118 * @return bool Does the testes hostname belongs to the own server?
120 private static function ownHost($host)
122 $own_host = DI::baseUrl()->getHostname();
124 $parts = parse_url($host);
126 if (!isset($parts['scheme'])) {
127 $parts = parse_url('http://'.$host);
130 if (!isset($parts['host'])) {
133 return $parts['host'] == $own_host;
137 * Probes for webfinger path via "host-meta"
139 * We have to check if the servers in the future still will offer this.
140 * It seems as if it was dropped from the standard.
142 * @param string $host The host part of an url
144 * @return array with template and type of the webfinger template for JSON or XML
145 * @throws HTTPException\InternalServerErrorException
147 private static function hostMeta($host)
149 // Reset the static variable
152 // Handles the case when the hostname contains the scheme
153 if (!parse_url($host, PHP_URL_SCHEME)) {
154 $ssl_url = "https://" . $host . "/.well-known/host-meta";
155 $url = "http://" . $host . "/.well-known/host-meta";
157 $ssl_url = $host . "/.well-known/host-meta";
161 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
163 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
166 $curlResult = Network::curl($ssl_url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
167 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
168 if ($curlResult->isSuccess()) {
169 $xml = $curlResult->getBody();
170 $xrd = XML::parseString($xml, true);
172 $host_url = 'https://' . $host;
176 } elseif ($curlResult->isTimeout()) {
177 Logger::info('Probing timeout', ['url' => $ssl_url], Logger::DEBUG);
178 self::$istimeout = true;
182 if (!is_object($xrd) && !empty($url)) {
183 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
184 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
185 if ($curlResult->isTimeout()) {
186 Logger::info('Probing timeout', ['url' => $url], Logger::DEBUG);
187 self::$istimeout = true;
189 } elseif ($connection_error && $ssl_connection_error) {
190 self::$istimeout = true;
194 $xml = $curlResult->getBody();
195 $xrd = XML::parseString($xml, true);
196 $host_url = 'http://'.$host;
198 if (!is_object($xrd)) {
199 Logger::log("No xrd object found for ".$host, Logger::DEBUG);
203 $links = XML::elementToArray($xrd);
204 if (!isset($links["xrd"]["link"])) {
205 Logger::log("No xrd data found for ".$host, Logger::DEBUG);
209 $lrdd = ['application/jrd+json' => $host_url . '/.well-known/webfinger?resource={uri}'];
211 foreach ($links["xrd"]["link"] as $value => $link) {
212 if (!empty($link["@attributes"])) {
213 $attributes = $link["@attributes"];
214 } elseif ($value == "@attributes") {
220 if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
221 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
223 $lrdd[$type] = $attributes["template"];
227 self::$baseurl = $host_url;
229 Logger::log("Probing successful for ".$host, Logger::DEBUG);
235 * Perform Webfinger lookup and return DFRN data
237 * Given an email style address, perform webfinger lookup and
238 * return the resulting DFRN profile URL, or if no DFRN profile URL
239 * is located, returns an OStatus subscription template (prefixed
240 * with the string 'stat:' to identify it as on OStatus template).
241 * If this isn't an email style address just return $webbie.
242 * Return an empty string if email-style addresses but webfinger fails,
243 * or if the resultant personal XRD doesn't contain a supported
244 * subscription/friend-request attribute.
246 * amended 7/9/2011 to return an hcard which could save potentially loading
247 * a lengthy content page to scrape dfrn attributes
249 * @param string $webbie Address that should be probed
250 * @param string $hcard_url Link to the hcard - is returned by reference
252 * @return string profile link
253 * @throws HTTPException\InternalServerErrorException
255 public static function webfingerDfrn($webbie, &$hcard_url)
259 $links = self::lrdd($webbie);
260 Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA);
261 if (!empty($links) && is_array($links)) {
262 foreach ($links as $link) {
263 if ($link['@attributes']['rel'] === ActivityNamespace::DFRN) {
264 $profile_link = $link['@attributes']['href'];
266 if (($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) && ($profile_link == "")) {
267 $profile_link = 'stat:'.$link['@attributes']['template'];
269 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
270 $hcard_url = $link['@attributes']['href'];
274 return $profile_link;
278 * Check an URI for LRDD data
280 * @param string $uri Address that should be probed
282 * @return array uri data
283 * @throws HTTPException\InternalServerErrorException
285 public static function lrdd(string $uri)
287 $lrdd = self::hostMeta($uri);
290 if (is_bool($lrdd)) {
295 $parts = @parse_url($uri);
296 if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
300 $host = $parts['scheme'] . '://' . $parts["host"];
301 if (!empty($parts["port"])) {
302 $host .= ':'.$parts["port"];
305 $path_parts = explode("/", trim($parts["path"], "/"));
307 $nick = array_pop($path_parts);
310 $lrdd = self::hostMeta($host);
311 $host .= "/".array_shift($path_parts);
312 } while (!$lrdd && (sizeof($path_parts) > 0));
316 Logger::log("No lrdd data found for ".$uri, Logger::DEBUG);
320 foreach ($lrdd as $type => $template) {
325 $path = str_replace('{uri}', urlencode($uri), $template);
326 $webfinger = self::webfinger($path, $type);
328 if (!$webfinger && (strstr($uri, "@"))) {
329 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
330 $webfinger = self::webfinger($path, $type);
333 // Special treatment for Mastodon
334 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
335 // But the webfinger for this format fails.
336 if (!$webfinger && !empty($nick)) {
337 // Mastodon uses a "@" as prefix for usernames in their url format
338 $nick = ltrim($nick, '@');
340 $addr = $nick."@".$host;
342 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
343 $webfinger = self::webfinger($path, $type);
347 if (empty($webfinger["links"])) {
348 Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
354 foreach ($webfinger["links"] as $link) {
355 $data[] = ["@attributes" => $link];
358 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
359 foreach ($webfinger["aliases"] as $alias) {
360 $data[] = ["@attributes" =>
370 * Fetch information (protocol endpoints and user information) about a given uri
372 * @param string $uri Address that should be probed
373 * @param string $network Test for this specific network
374 * @param integer $uid User ID for the probe (only used for mails)
375 * @param boolean $cache Use cached values?
377 * @return array uri data
378 * @throws HTTPException\InternalServerErrorException
379 * @throws \ImagickException
381 public static function uri($uri, $network = '', $uid = -1, $cache = true)
384 $result = DI::cache()->get('Probe::uri:' . $network . ':' . $uri);
385 if (!is_null($result)) {
394 self::$istimeout = false;
396 if ($network != Protocol::ACTIVITYPUB) {
397 $data = self::detect($uri, $network, $uid);
402 // When the previous detection process had got a time out
403 // we could falsely detect a Friendica profile as AP profile.
404 if (!self::$istimeout) {
405 $ap_profile = ActivityPub::probeProfile($uri, !$cache);
407 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
409 } elseif (!empty($ap_profile)) {
410 $ap_profile['batch'] = '';
411 $data = array_merge($ap_profile, $data);
414 Logger::notice('Time out detected. AP will not be probed.', ['uri' => $uri]);
417 if (!isset($data['url'])) {
421 if (empty($data['photo'])) {
422 $data['photo'] = DI::baseUrl() . '/images/person-300.jpg';
425 if (empty($data['name'])) {
426 if (!empty($data['nick'])) {
427 $data['name'] = $data['nick'];
430 if (empty($data['name'])) {
431 $data['name'] = $data['url'];
435 if (empty($data['nick'])) {
436 $data['nick'] = strtolower($data['name']);
438 if (strpos($data['nick'], ' ')) {
439 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
443 if (!empty(self::$baseurl)) {
444 $data['baseurl'] = self::$baseurl;
447 if (!empty($data['baseurl']) && empty($data['gsid'])) {
448 $data['gsid'] = GServer::getID($data['baseurl']);
451 if (empty($data['network'])) {
452 $data['network'] = Protocol::PHANTOM;
455 // Ensure that local connections always are DFRN
456 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
457 $data['network'] = Protocol::DFRN;
460 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
461 $data['hide'] = self::getHideStatus($data['url']);
464 $data = self::rearrangeData($data);
466 // Only store into the cache if the value seems to be valid
467 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
468 DI::cache()->set('Probe::uri:' . $network . ':' . $uri, $data, Duration::DAY);
476 * Fetches the "hide" status from the profile
478 * @param string $url URL of the profile
480 * @return boolean "hide" status
482 private static function getHideStatus($url)
484 $curlResult = Network::curl($url);
485 if (!$curlResult->isSuccess()) {
489 // If the file is too large then exit
490 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
494 // If it isn't a HTML file then exit
495 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
499 $body = $curlResult->getBody();
501 $doc = new DOMDocument();
502 @$doc->loadHTML($body);
504 $xpath = new DOMXPath($doc);
506 $list = $xpath->query('//meta[@name]');
507 foreach ($list as $node) {
509 if ($node->attributes->length) {
510 foreach ($node->attributes as $attribute) {
511 $meta_tag[$attribute->name] = $attribute->value;
515 if (empty($meta_tag['content'])) {
519 $content = strtolower(trim($meta_tag['content']));
521 switch (strtolower(trim($meta_tag['name']))) {
522 case 'dfrn-global-visibility':
523 if ($content == 'false') {
528 if (strpos($content, 'noindex') !== false) {
539 * Checks if a profile url should be OStatus but only provides partial information
541 * @param array $webfinger Webfinger data
542 * @param string $lrdd Path template for webfinger request
543 * @param string $type type
545 * @return array fixed webfinger data
546 * @throws HTTPException\InternalServerErrorException
548 private static function fixOStatus($webfinger, $lrdd, $type)
550 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
557 foreach ($webfinger['links'] as $link) {
558 if ($link['rel'] == ActivityNamespace::OSTATUSSUB) {
561 if ($link['rel'] == 'magic-public-key') {
566 if (!$is_ostatus || $has_key) {
570 $url = Network::switchScheme($webfinger['subject']);
571 $path = str_replace('{uri}', urlencode($url), $lrdd);
572 $webfinger2 = self::webfinger($path, $type);
574 // Is the new webfinger detectable as OStatus?
575 if (self::ostatus($webfinger2, true)) {
576 $webfinger = $webfinger2;
583 * Fetch the "subscribe" and add it to the result
585 * @param array $result
586 * @param array $webfinger
587 * @return array result
589 private static function getSubscribeLink(array $result, array $webfinger)
591 if (empty($webfinger['links'])) {
595 foreach ($webfinger['links'] as $link) {
596 if ($link['rel'] === ActivityNamespace::OSTATUSSUB) {
597 $result['subscribe'] = $link['template'];
605 * Fetch information (protocol endpoints and user information) about a given uri
607 * This function is only called by the "uri" function that adds caching and rearranging of data.
609 * @param string $uri Address that should be probed
610 * @param string $network Test for this specific network
611 * @param integer $uid User ID for the probe (only used for mails)
613 * @return array uri data
614 * @throws HTTPException\InternalServerErrorException
616 private static function detect($uri, $network, $uid)
618 $parts = parse_url($uri);
620 if (!empty($parts["scheme"]) && !empty($parts["host"])) {
621 $host = $parts["host"];
622 if (!empty($parts["port"])) {
623 $host .= ':'.$parts["port"];
626 if ($host == 'twitter.com') {
627 return self::twitter($uri);
629 $lrdd = self::hostMeta($host);
631 if (is_bool($lrdd)) {
635 $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
637 while (!$lrdd && (sizeof($path_parts) > 1)) {
638 $host .= "/".array_shift($path_parts);
639 $lrdd = self::hostMeta($host);
642 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
643 return self::feed($uri);
645 $nick = array_pop($path_parts);
647 // Mastodon uses a "@" as prefix for usernames in their url format
648 $nick = ltrim($nick, '@');
650 $addr = $nick."@".$host;
651 } elseif (strstr($uri, '@')) {
652 // If the URI starts with "mailto:" then jump directly to the mail detection
653 if (strpos($uri, 'mailto:') !== false) {
654 $uri = str_replace('mailto:', '', $uri);
655 return self::mail($uri, $uid);
658 if ($network == Protocol::MAIL) {
659 return self::mail($uri, $uid);
661 // Remove "acct:" from the URI
662 $uri = str_replace('acct:', '', $uri);
664 $host = substr($uri, strpos($uri, '@') + 1);
665 $nick = substr($uri, 0, strpos($uri, '@'));
667 if (strpos($uri, '@twitter.com')) {
668 return self::twitter($uri);
670 $lrdd = self::hostMeta($host);
672 if (is_bool($lrdd)) {
677 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
678 return self::mail($uri, $uid);
682 Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
688 /// @todo Do we need the prefix "acct:" or "acct://"?
690 foreach ($lrdd as $type => $template) {
695 // At first try it with the given uri
696 $path = str_replace('{uri}', urlencode($uri), $template);
697 $webfinger = self::webfinger($path, $type);
699 // Fix possible problems with GNU Social probing to wrong scheme
700 $webfinger = self::fixOStatus($webfinger, $template, $type);
702 // We cannot be sure that the detected address was correct, so we don't use the values
703 if ($webfinger && ($uri != $addr)) {
708 // Try webfinger with the address (user@domain.tld)
710 $path = str_replace('{uri}', urlencode($addr), $template);
711 $webfinger = self::webfinger($path, $type);
714 // Mastodon needs to have it with "acct:"
716 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
717 $webfinger = self::webfinger($path, $type);
722 return self::feed($uri);
727 Logger::info("Probing", ['uri' => $uri]);
729 if (in_array($network, ["", Protocol::DFRN])) {
730 $result = self::dfrn($webfinger);
732 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
733 $result = self::diaspora($webfinger);
735 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
736 $result = self::ostatus($webfinger);
738 if (in_array($network, ['', Protocol::ZOT])) {
739 $result = self::zot($webfinger, $result);
741 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
742 $result = self::pumpio($webfinger, $addr);
744 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
745 $result = self::feed($uri);
747 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
748 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
749 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
750 $result["nick"] = $nick;
753 if (empty($result["addr"]) && ($addr != "")) {
754 $result["addr"] = $addr;
758 $result = self::getSubscribeLink($result, $webfinger);
760 if (empty($result["network"])) {
761 $result["network"] = Protocol::PHANTOM;
764 if (empty($result["url"])) {
765 $result["url"] = $uri;
768 Logger::log($uri." is ".$result["network"], Logger::DEBUG);
770 if (empty($result["baseurl"]) && ($result["network"] != Protocol::PHANTOM)) {
771 $pos = strpos($result["url"], $host);
773 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
781 * Check for Zot contact
783 * @param array $webfinger Webfinger data
784 * @param array $data previously probed data
786 * @return array Zot data
787 * @throws HTTPException\InternalServerErrorException
789 private static function zot($webfinger, $data)
791 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
792 foreach ($webfinger["aliases"] as $alias) {
793 if (substr($alias, 0, 5) == 'acct:') {
794 $data["addr"] = substr($alias, 5);
799 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
800 $data["addr"] = substr($webfinger["subject"], 5);
804 foreach ($webfinger['links'] as $link) {
805 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
806 $zot_url = $link['href'];
810 if (empty($zot_url) && !empty($data['addr']) && !empty(self::$baseurl)) {
811 $condition = ['nurl' => Strings::normaliseLink(self::$baseurl), 'platform' => ['hubzilla']];
812 if (!DBA::exists('gserver', $condition)) {
815 $zot_url = self::$baseurl . '/.well-known/zot-info?address=' . $data['addr'];
818 if (empty($zot_url)) {
822 $data = self::pollZot($zot_url, $data);
824 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
825 foreach ($webfinger['aliases'] as $alias) {
826 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
827 $data['alias'] = $alias;
835 public static function pollZot($url, $data)
837 $curlResult = Network::curl($url);
838 if ($curlResult->isTimeout()) {
841 $content = $curlResult->getBody();
846 $json = json_decode($content, true);
847 if (!is_array($json)) {
851 if (empty($data['network'])) {
852 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
853 $data['network'] = Protocol::ZOT;
854 } elseif (!isset($json['protocols'])) {
855 $data['network'] = Protocol::ZOT;
859 if (!empty($json['guid']) && empty($data['guid'])) {
860 $data['guid'] = $json['guid'];
862 if (!empty($json['key']) && empty($data['pubkey'])) {
863 $data['pubkey'] = $json['key'];
865 if (!empty($json['name'])) {
866 $data['name'] = $json['name'];
868 if (!empty($json['photo'])) {
869 $data['photo'] = $json['photo'];
870 if (!empty($json['photo_updated'])) {
871 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
874 if (!empty($json['address'])) {
875 $data['addr'] = $json['address'];
877 if (!empty($json['url'])) {
878 $data['url'] = $json['url'];
880 if (!empty($json['connections_url'])) {
881 $data['poco'] = $json['connections_url'];
883 if (isset($json['searchable'])) {
884 $data['hide'] = !$json['searchable'];
886 if (!empty($json['public_forum'])) {
887 $data['community'] = $json['public_forum'];
888 $data['account-type'] = Contact::PAGE_COMMUNITY;
891 if (!empty($json['profile'])) {
892 $profile = $json['profile'];
893 if (!empty($profile['description'])) {
894 $data['about'] = $profile['description'];
896 if (!empty($profile['keywords'])) {
897 $keywords = implode(', ', $profile['keywords']);
898 if (!empty($keywords)) {
899 $data['keywords'] = $keywords;
904 if (!empty($profile['region'])) {
905 $loc['region'] = $profile['region'];
907 if (!empty($profile['country'])) {
908 $loc['country-name'] = $profile['country'];
910 $location = Profile::formatLocation($loc);
911 if (!empty($location)) {
912 $data['location'] = $location;
920 * Perform a webfinger request.
922 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
924 * @param string $url Address that should be probed
925 * @param string $type type
927 * @return array webfinger data
928 * @throws HTTPException\InternalServerErrorException
930 public static function webfinger($url, $type)
932 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
934 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
935 if ($curlResult->isTimeout()) {
936 self::$istimeout = true;
939 $data = $curlResult->getBody();
941 $webfinger = json_decode($data, true);
942 if (!empty($webfinger)) {
943 if (!isset($webfinger["links"])) {
944 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
950 // If it is not JSON, maybe it is XML
951 $xrd = XML::parseString($data, true);
952 if (!is_object($xrd)) {
953 Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
957 $xrd_arr = XML::elementToArray($xrd);
958 if (!isset($xrd_arr["xrd"]["link"])) {
959 Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
965 if (!empty($xrd_arr["xrd"]["subject"])) {
966 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
969 if (!empty($xrd_arr["xrd"]["alias"])) {
970 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
973 $webfinger["links"] = [];
975 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
976 if (!empty($data["@attributes"])) {
977 $attributes = $data["@attributes"];
978 } elseif ($value == "@attributes") {
984 $webfinger["links"][] = $attributes;
990 * Poll the Friendica specific noscrape page.
992 * "noscrape" is a faster alternative to fetch the data from the hcard.
993 * This functionality was originally created for the directory.
995 * @param string $noscrape_url Link to the noscrape page
996 * @param array $data The already fetched data
998 * @return array noscrape data
999 * @throws HTTPException\InternalServerErrorException
1001 private static function pollNoscrape($noscrape_url, $data)
1003 $curlResult = Network::curl($noscrape_url);
1004 if ($curlResult->isTimeout()) {
1005 self::$istimeout = true;
1008 $content = $curlResult->getBody();
1010 Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
1014 $json = json_decode($content, true);
1015 if (!is_array($json)) {
1016 Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
1020 if (!empty($json["fn"])) {
1021 $data["name"] = $json["fn"];
1024 if (!empty($json["addr"])) {
1025 $data["addr"] = $json["addr"];
1028 if (!empty($json["nick"])) {
1029 $data["nick"] = $json["nick"];
1032 if (!empty($json["guid"])) {
1033 $data["guid"] = $json["guid"];
1036 if (!empty($json["comm"])) {
1037 $data["community"] = $json["comm"];
1040 if (!empty($json["tags"])) {
1041 $keywords = implode(", ", $json["tags"]);
1042 if ($keywords != "") {
1043 $data["keywords"] = $keywords;
1047 $location = Profile::formatLocation($json);
1049 $data["location"] = $location;
1052 if (!empty($json["about"])) {
1053 $data["about"] = $json["about"];
1056 if (!empty($json["key"])) {
1057 $data["pubkey"] = $json["key"];
1060 if (!empty($json["photo"])) {
1061 $data["photo"] = $json["photo"];
1064 if (!empty($json["dfrn-request"])) {
1065 $data["request"] = $json["dfrn-request"];
1068 if (!empty($json["dfrn-confirm"])) {
1069 $data["confirm"] = $json["dfrn-confirm"];
1072 if (!empty($json["dfrn-notify"])) {
1073 $data["notify"] = $json["dfrn-notify"];
1076 if (!empty($json["dfrn-poll"])) {
1077 $data["poll"] = $json["dfrn-poll"];
1080 if (isset($json["hide"])) {
1081 $data["hide"] = (bool)$json["hide"];
1083 $data["hide"] = false;
1090 * Check for valid DFRN data
1092 * @param array $data DFRN data
1094 * @return int Number of errors
1096 public static function validDfrn($data)
1099 if (!isset($data['key'])) {
1102 if (!isset($data['dfrn-request'])) {
1105 if (!isset($data['dfrn-confirm'])) {
1108 if (!isset($data['dfrn-notify'])) {
1111 if (!isset($data['dfrn-poll'])) {
1118 * Fetch data from a DFRN profile page and via "noscrape"
1120 * @param string $profile_link Link to the profile page
1122 * @return array profile data
1123 * @throws HTTPException\InternalServerErrorException
1124 * @throws \ImagickException
1126 public static function profile($profile_link)
1130 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
1132 // Fetch data via noscrape - this is faster
1133 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1134 $data = self::pollNoscrape($noscrape_url, $data);
1136 if (!isset($data["notify"])
1137 || !isset($data["confirm"])
1138 || !isset($data["request"])
1139 || !isset($data["poll"])
1140 || !isset($data["name"])
1141 || !isset($data["photo"])
1143 $data = self::pollHcard($profile_link, $data, true);
1148 if (empty($data["addr"]) || empty($data["nick"])) {
1149 $probe_data = self::uri($profile_link);
1150 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1151 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1154 $prof_data["addr"] = $data["addr"];
1155 $prof_data["nick"] = $data["nick"];
1156 $prof_data["dfrn-request"] = $data['request'] ?? null;
1157 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1158 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1159 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1160 $prof_data["photo"] = $data['photo'] ?? null;
1161 $prof_data["fn"] = $data['name'] ?? null;
1162 $prof_data["key"] = $data['pubkey'] ?? null;
1164 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
1170 * Check for DFRN contact
1172 * @param array $webfinger Webfinger data
1174 * @return array DFRN data
1175 * @throws HTTPException\InternalServerErrorException
1177 private static function dfrn($webfinger)
1181 // The array is reversed to take into account the order of preference for same-rel links
1182 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1183 foreach (array_reverse($webfinger["links"]) as $link) {
1184 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1185 $data["network"] = Protocol::DFRN;
1186 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1187 $data["poll"] = $link["href"];
1188 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1189 $data["url"] = $link["href"];
1190 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1191 $hcard_url = $link["href"];
1192 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1193 $data["poco"] = $link["href"];
1194 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1195 $data["photo"] = $link["href"];
1196 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1197 $data["baseurl"] = trim($link["href"], '/');
1198 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1199 $data["guid"] = $link["href"];
1200 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1201 $data["pubkey"] = base64_decode($link["href"]);
1203 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1204 if (strstr($data["pubkey"], 'RSA ')) {
1205 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1210 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1211 foreach ($webfinger["aliases"] as $alias) {
1212 if (empty($data["url"]) && !strstr($alias, "@")) {
1213 $data["url"] = $alias;
1214 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1215 $data["alias"] = $alias;
1216 } elseif (substr($alias, 0, 5) == 'acct:') {
1217 $data["addr"] = substr($alias, 5);
1222 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1223 $data["addr"] = substr($webfinger["subject"], 5);
1226 if (!isset($data["network"]) || ($hcard_url == "")) {
1230 // Fetch data via noscrape - this is faster
1231 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1232 $data = self::pollNoscrape($noscrape_url, $data);
1234 if (isset($data["notify"])
1235 && isset($data["confirm"])
1236 && isset($data["request"])
1237 && isset($data["poll"])
1238 && isset($data["name"])
1239 && isset($data["photo"])
1244 $data = self::pollHcard($hcard_url, $data, true);
1250 * Poll the hcard page (Diaspora and Friendica specific)
1252 * @param string $hcard_url Link to the hcard page
1253 * @param array $data The already fetched data
1254 * @param boolean $dfrn Poll DFRN specific data
1256 * @return array hcard data
1257 * @throws HTTPException\InternalServerErrorException
1259 private static function pollHcard($hcard_url, $data, $dfrn = false)
1261 $curlResult = Network::curl($hcard_url);
1262 if ($curlResult->isTimeout()) {
1263 self::$istimeout = true;
1266 $content = $curlResult->getBody();
1271 $doc = new DOMDocument();
1272 if (!@$doc->loadHTML($content)) {
1276 $xpath = new DomXPath($doc);
1278 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1279 if (!is_object($vcards)) {
1283 if (!isset($data["baseurl"])) {
1284 $data["baseurl"] = "";
1287 if ($vcards->length > 0) {
1288 $vcard = $vcards->item(0);
1290 // We have to discard the guid from the hcard in favour of the guid from lrdd
1291 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1292 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1293 if (($search->length > 0) && empty($data["guid"])) {
1294 $data["guid"] = $search->item(0)->nodeValue;
1297 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1298 if ($search->length > 0) {
1299 $data["nick"] = $search->item(0)->nodeValue;
1302 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1303 if ($search->length > 0) {
1304 $data["name"] = $search->item(0)->nodeValue;
1307 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1308 if ($search->length > 0) {
1309 $data["searchable"] = $search->item(0)->nodeValue;
1312 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1313 if ($search->length > 0) {
1314 $data["pubkey"] = $search->item(0)->nodeValue;
1315 if (strstr($data["pubkey"], 'RSA ')) {
1316 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1320 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1321 if ($search->length > 0) {
1322 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1327 if (!empty($vcard)) {
1328 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1329 foreach ($photos as $photo) {
1331 foreach ($photo->attributes as $attribute) {
1332 $attr[$attribute->name] = trim($attribute->value);
1335 if (isset($attr["src"]) && isset($attr["width"])) {
1336 $avatar[$attr["width"]] = $attr["src"];
1339 // We don't have a width. So we just take everything that we got.
1340 // This is a Hubzilla workaround which doesn't send a width.
1341 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1342 $avatar[] = $attr["src"];
1347 if (sizeof($avatar)) {
1349 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1353 // Poll DFRN specific data
1354 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1355 if ($search->length > 0) {
1356 foreach ($search as $link) {
1357 //$data["request"] = $search->item(0)->nodeValue;
1359 foreach ($link->attributes as $attribute) {
1360 $attr[$attribute->name] = trim($attribute->value);
1363 $data[substr($attr["rel"], 5)] = $attr["href"];
1367 // Older Friendica versions had used the "uid" field differently than newer versions
1368 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1369 unset($data["guid"]);
1378 * Check for Diaspora contact
1380 * @param array $webfinger Webfinger data
1382 * @return array Diaspora data
1383 * @throws HTTPException\InternalServerErrorException
1385 private static function diaspora($webfinger)
1390 // The array is reversed to take into account the order of preference for same-rel links
1391 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1392 foreach (array_reverse($webfinger["links"]) as $link) {
1393 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1394 $hcard_url = $link["href"];
1395 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1396 $data["baseurl"] = trim($link["href"], '/');
1397 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1398 $data["guid"] = $link["href"];
1399 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1400 $data["url"] = $link["href"];
1401 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1402 $data["poll"] = $link["href"];
1403 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1404 $data["poco"] = $link["href"];
1405 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1406 $data["notify"] = $link["href"];
1407 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1408 $data["pubkey"] = base64_decode($link["href"]);
1410 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1411 if (strstr($data["pubkey"], 'RSA ')) {
1412 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1417 if (empty($data["url"]) || empty($hcard_url)) {
1421 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1422 foreach ($webfinger["aliases"] as $alias) {
1423 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1424 $data["alias"] = $alias;
1425 } elseif (substr($alias, 0, 5) == 'acct:') {
1426 $data["addr"] = substr($alias, 5);
1431 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1432 $data["addr"] = substr($webfinger["subject"], 5);
1435 // Fetch further information from the hcard
1436 $data = self::pollHcard($hcard_url, $data);
1442 if (!empty($data["url"])
1443 && !empty($data["guid"])
1444 && !empty($data["baseurl"])
1445 && !empty($data["pubkey"])
1446 && !empty($hcard_url)
1448 $data["network"] = Protocol::DIASPORA;
1450 // The Diaspora handle must always be lowercase
1451 if (!empty($data["addr"])) {
1452 $data["addr"] = strtolower($data["addr"]);
1455 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1456 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1457 $data["batch"] = $data["baseurl"] . "/receive/public";
1466 * Check for OStatus contact
1468 * @param array $webfinger Webfinger data
1469 * @param bool $short Short detection mode
1471 * @return array|bool OStatus data or "false" on error or "true" on short mode
1472 * @throws HTTPException\InternalServerErrorException
1474 private static function ostatus($webfinger, $short = false)
1478 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1479 foreach ($webfinger["aliases"] as $alias) {
1480 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1481 $data["addr"] = str_replace('acct:', '', $alias);
1486 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1487 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1489 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1492 if (!empty($webfinger["links"])) {
1493 // The array is reversed to take into account the order of preference for same-rel links
1494 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1495 foreach (array_reverse($webfinger["links"]) as $link) {
1496 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1497 && (($link["type"] ?? "") == "text/html")
1498 && ($link["href"] != "")
1500 $data["url"] = $link["href"];
1501 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1502 $data["notify"] = $link["href"];
1503 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1504 $data["poll"] = $link["href"];
1505 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1506 $pubkey = $link["href"];
1508 if (substr($pubkey, 0, 5) === 'data:') {
1509 if (strstr($pubkey, ',')) {
1510 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1512 $pubkey = substr($pubkey, 5);
1514 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1515 $curlResult = Network::curl($pubkey);
1516 if ($curlResult->isTimeout()) {
1517 self::$istimeout = true;
1518 return $short ? false : [];
1520 $pubkey = $curlResult->getBody();
1523 $key = explode(".", $pubkey);
1525 if (sizeof($key) >= 3) {
1526 $m = Strings::base64UrlDecode($key[1]);
1527 $e = Strings::base64UrlDecode($key[2]);
1528 $data["pubkey"] = Crypto::meToPem($m, $e);
1534 if (isset($data["notify"]) && isset($data["pubkey"])
1535 && isset($data["poll"])
1536 && isset($data["url"])
1538 $data["network"] = Protocol::OSTATUS;
1540 return $short ? false : [];
1547 // Fetch all additional data from the feed
1548 $curlResult = Network::curl($data["poll"]);
1549 if ($curlResult->isTimeout()) {
1550 self::$istimeout = true;
1553 $feed = $curlResult->getBody();
1554 $feed_data = Feed::import($feed);
1559 if (!empty($feed_data["header"]["author-name"])) {
1560 $data["name"] = $feed_data["header"]["author-name"];
1562 if (!empty($feed_data["header"]["author-nick"])) {
1563 $data["nick"] = $feed_data["header"]["author-nick"];
1565 if (!empty($feed_data["header"]["author-avatar"])) {
1566 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1568 if (!empty($feed_data["header"]["author-id"])) {
1569 $data["alias"] = $feed_data["header"]["author-id"];
1571 if (!empty($feed_data["header"]["author-location"])) {
1572 $data["location"] = $feed_data["header"]["author-location"];
1574 if (!empty($feed_data["header"]["author-about"])) {
1575 $data["about"] = $feed_data["header"]["author-about"];
1577 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1578 // So we take the value that we just fetched, although the other one worked as well
1579 if (!empty($feed_data["header"]["author-link"])) {
1580 $data["url"] = $feed_data["header"]["author-link"];
1583 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1584 $data['url'] = $data["alias"];
1585 $data["alias"] = '';
1588 /// @todo Fetch location and "about" from the feed as well
1593 * Fetch data from a pump.io profile page
1595 * @param string $profile_link Link to the profile page
1597 * @return array profile data
1599 private static function pumpioProfileData($profile_link)
1601 $curlResult = Network::curl($profile_link);
1602 if (!$curlResult->isSuccess()) {
1606 $doc = new DOMDocument();
1607 if (!@$doc->loadHTML($curlResult->getBody())) {
1611 $xpath = new DomXPath($doc);
1615 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1617 if ($data["name"] == '') {
1618 // This is ugly - but pump.io doesn't seem to know a better way for it
1619 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1620 $pos = strpos($data["name"], chr(10));
1622 $data["name"] = trim(substr($data["name"], 0, $pos));
1626 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1628 if ($data["location"] == '') {
1629 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1632 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1634 if ($data["about"] == '') {
1635 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1638 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1640 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1643 foreach ($avatar->attributes as $attribute) {
1644 if ($attribute->name == "src") {
1645 $data["photo"] = trim($attribute->value);
1654 * Check for pump.io contact
1656 * @param array $webfinger Webfinger data
1657 * @param string $addr
1658 * @return array pump.io data
1660 private static function pumpio($webfinger, $addr)
1663 // The array is reversed to take into account the order of preference for same-rel links
1664 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1665 foreach (array_reverse($webfinger["links"]) as $link) {
1666 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1667 && (($link["type"] ?? "") == "text/html")
1668 && ($link["href"] != "")
1670 $data["url"] = $link["href"];
1671 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1672 $data["notify"] = $link["href"];
1673 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1674 $data["poll"] = $link["href"];
1675 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1676 $data["dialback"] = $link["href"];
1679 if (isset($data["poll"]) && isset($data["notify"])
1680 && isset($data["dialback"])
1681 && isset($data["url"])
1683 // by now we use these fields only for the network type detection
1684 // So we unset all data that isn't used at the moment
1685 unset($data["dialback"]);
1687 $data["network"] = Protocol::PUMPIO;
1692 $profile_data = self::pumpioProfileData($data["url"]);
1694 if (!$profile_data) {
1698 $data = array_merge($data, $profile_data);
1700 if (($addr != '') && ($data['name'] != '')) {
1701 $name = trim(str_replace($addr, '', $data['name']));
1703 $data['name'] = $name;
1711 * Check for twitter contact
1713 * @param string $uri
1715 * @return array twitter data
1717 private static function twitter($uri)
1719 if (preg_match('=(.*)@twitter.com=i', $uri, $matches)) {
1720 $nick = $matches[1];
1721 } elseif (preg_match('=https?://twitter.com/(.*)=i', $uri, $matches)) {
1722 $nick = $matches[1];
1728 $data['url'] = 'https://twitter.com/' . $nick;
1729 $data['addr'] = $nick . '@twitter.com';
1730 $data['nick'] = $data['name'] = $nick;
1731 $data['network'] = Protocol::TWITTER;
1732 $data['baseurl'] = 'https://twitter.com';
1734 $curlResult = Network::curl($data['url'], false);
1735 if (!$curlResult->isSuccess()) {
1739 $body = $curlResult->getBody();
1740 $doc = new DOMDocument();
1741 @$doc->loadHTML($body);
1742 $xpath = new DOMXPath($doc);
1744 $list = $xpath->query('//img[@class]');
1745 foreach ($list as $node) {
1747 if ($node->attributes->length) {
1748 foreach ($node->attributes as $attribute) {
1749 $img_attr[$attribute->name] = $attribute->value;
1753 if (empty($img_attr['class'])) {
1757 if (strpos($img_attr['class'], 'ProfileAvatar-image') !== false) {
1758 if (!empty($img_attr['src'])) {
1759 $data['photo'] = $img_attr['src'];
1761 if (!empty($img_attr['alt'])) {
1762 $data['name'] = $img_attr['alt'];
1771 * Checks HTML page for RSS feed link
1773 * @param string $url Page link
1774 * @param string $body Page body string
1775 * @return string|false Feed link or false if body was invalid HTML document
1777 public static function getFeedLink(string $url, string $body)
1779 $doc = new DOMDocument();
1780 if (!@$doc->loadHTML($body)) {
1784 $xpath = new DOMXPath($doc);
1786 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1788 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1794 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1796 * Loosely based on RFC 1808
1798 * @see https://tools.ietf.org/html/rfc1808
1800 * @param string $href The potential relative href found in the HTML document
1801 * @param string $base The HTML document URL
1802 * @param DOMXPath $xpath The HTML document XPath
1805 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath)
1807 if (filter_var($href, FILTER_VALIDATE_URL)) {
1811 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1813 $baseParts = parse_url($base);
1815 // Naked domain case (scheme://basehost)
1816 $path = $baseParts['path'] ?? '/';
1818 // Remove the filename part of the path if it exists (/base/path/file)
1819 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1821 $hrefParts = parse_url($href);
1823 // Root path case (/path) including relative scheme case (//host/path)
1824 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1825 $path = $hrefParts['path'];
1827 $path = $path . '/' . $hrefParts['path'];
1829 // Resolve arbitrary relative path
1830 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1831 $parts = array_filter(explode('/', $path), 'strlen');
1832 $absolutes = array();
1833 foreach ($parts as $part) {
1834 if ('.' == $part) continue;
1835 if ('..' == $part) {
1836 array_pop($absolutes);
1838 $absolutes[] = $part;
1842 $path = '/' . implode('/', $absolutes);
1845 // Relative scheme case (//host/path)
1846 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1847 $baseParts['path'] = $path;
1848 unset($baseParts['query']);
1849 unset($baseParts['fragment']);
1851 return Network::unparseURL($baseParts);
1855 * Check for feed contact
1857 * @param string $url Profile link
1858 * @param boolean $probe Do a probe if the page contains a feed link
1860 * @return array feed data
1861 * @throws HTTPException\InternalServerErrorException
1863 private static function feed($url, $probe = true)
1865 $curlResult = Network::curl($url);
1866 if ($curlResult->isTimeout()) {
1867 self::$istimeout = true;
1870 $feed = $curlResult->getBody();
1871 $feed_data = Feed::import($feed);
1878 $feed_url = self::getFeedLink($url, $feed);
1884 return self::feed($feed_url, false);
1887 if (!empty($feed_data["header"]["author-name"])) {
1888 $data["name"] = $feed_data["header"]["author-name"];
1891 if (!empty($feed_data["header"]["author-nick"])) {
1892 $data["nick"] = $feed_data["header"]["author-nick"];
1895 if (!empty($feed_data["header"]["author-avatar"])) {
1896 $data["photo"] = $feed_data["header"]["author-avatar"];
1899 if (!empty($feed_data["header"]["author-id"])) {
1900 $data["alias"] = $feed_data["header"]["author-id"];
1903 $data["url"] = $url;
1904 $data["poll"] = $url;
1906 if (!empty($feed_data["header"]["author-link"])) {
1907 $data["baseurl"] = $feed_data["header"]["author-link"];
1909 $data["baseurl"] = $data["url"];
1912 $data["network"] = Protocol::FEED;
1918 * Check for mail contact
1920 * @param string $uri Profile link
1921 * @param integer $uid User ID
1923 * @return array mail data
1924 * @throws \Exception
1926 private static function mail($uri, $uid)
1928 if (!Network::isEmailDomainValid($uri)) {
1936 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1938 $condition = ["`uid` = ? AND `server` != ''", $uid];
1939 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1940 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1942 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1946 $mailbox = Email::constructMailboxName($mailacct);
1948 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1949 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1954 $msgs = Email::poll($mbox, $uri);
1955 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1957 if (!count($msgs)) {
1961 $phost = substr($uri, strpos($uri, '@') + 1);
1964 $data["addr"] = $uri;
1965 $data["network"] = Protocol::MAIL;
1966 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1967 $data["nick"] = $data["name"];
1968 $data["photo"] = Network::lookupAvatarByEmail($uri);
1969 $data["url"] = 'mailto:'.$uri;
1970 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1971 $data["poll"] = 'email ' . Strings::getRandomHex();
1973 $x = Email::messageMeta($mbox, $msgs[0]);
1974 if (stristr($x[0]->from, $uri)) {
1975 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1976 } elseif (stristr($x[0]->to, $uri)) {
1977 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1980 foreach ($adr as $feadr) {
1981 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1982 &&(strcasecmp($feadr->host, $phost) == 0)
1983 && (strlen($feadr->personal))
1985 $personal = imap_mime_header_decode($feadr->personal);
1987 foreach ($personal as $perspart) {
1988 if ($perspart->charset != "default") {
1989 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1991 $data["name"] .= $perspart->text;
1995 $data["name"] = Strings::escapeTags($data["name"]);
1999 if (!empty($mbox)) {
2006 * Mix two paths together to possibly fix missing parts
2008 * @param string $avatar Path to the avatar
2009 * @param string $base Another path that is hopefully complete
2011 * @return string fixed avatar path
2012 * @throws \Exception
2014 public static function fixAvatar($avatar, $base)
2016 $base_parts = parse_url($base);
2018 // Remove all parts that could create a problem
2019 unset($base_parts['path']);
2020 unset($base_parts['query']);
2021 unset($base_parts['fragment']);
2023 $avatar_parts = parse_url($avatar);
2026 $parts = array_merge($base_parts, $avatar_parts);
2028 // And put them together again
2029 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
2030 $host = isset($parts['host']) ? $parts['host'] : '';
2031 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
2032 $path = isset($parts['path']) ? $parts['path'] : '';
2033 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
2034 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
2036 $fixed = $scheme.$host.$port.$path.$query.$fragment;
2038 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);