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\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
33 use Friendica\Model\Contact;
34 use Friendica\Model\GServer;
35 use Friendica\Model\Profile;
36 use Friendica\Protocol\ActivityNamespace;
37 use Friendica\Protocol\ActivityPub;
38 use Friendica\Protocol\Email;
39 use Friendica\Protocol\Feed;
40 use Friendica\Util\Crypto;
41 use Friendica\Util\Network;
42 use Friendica\Util\Strings;
43 use Friendica\Util\XML;
46 * This class contain functions for probing URL
50 private static $baseurl;
51 private static $istimeout;
54 * Remove stuff from an URI that doesn't belong there
57 * @return string Cleaned URI
59 public static function cleanURI(string $URI)
61 // At first remove leading and trailing junk
62 $URI = trim($URI, "@#?:/ \t\n\r\0\x0B");
64 $parts = parse_url($URI);
66 if (empty($parts['scheme'])) {
70 // Remove the URL fragment, since these shouldn't be part of any profile URL
71 unset($parts['fragment']);
73 $URI = Network::unparseURL($parts);
79 * Rearrange the array so that it always has the same order
81 * @param array $data Unordered data
83 * @return array Ordered data
85 private static function rearrangeData($data)
87 $fields = ["name", "nick", "guid", "url", "addr", "alias", "photo", "account-type",
88 "community", "keywords", "location", "about", "hide",
89 "batch", "notify", "poll", "request", "confirm", "subscribe", "poco",
90 "following", "followers", "inbox", "outbox", "sharedinbox",
91 "priority", "network", "pubkey", "baseurl", "gsid"];
94 foreach ($fields as $field) {
95 if (isset($data[$field])) {
96 if (in_array($field, ["gsid", "hide", "account-type"])) {
97 $newdata[$field] = (int)$data[$field];
99 $newdata[$field] = $data[$field];
101 } elseif ($field != "gsid") {
102 $newdata[$field] = "";
104 $newdata[$field] = null;
108 // We don't use the "priority" field anymore and replace it with a dummy.
109 $newdata["priority"] = 0;
115 * Check if the hostname belongs to the own server
117 * @param string $host The hostname that is to be checked
119 * @return bool Does the testes hostname belongs to the own server?
121 private static function ownHost($host)
123 $own_host = DI::baseUrl()->getHostname();
125 $parts = parse_url($host);
127 if (!isset($parts['scheme'])) {
128 $parts = parse_url('http://'.$host);
131 if (!isset($parts['host'])) {
134 return $parts['host'] == $own_host;
138 * Probes for webfinger path via "host-meta"
140 * We have to check if the servers in the future still will offer this.
141 * It seems as if it was dropped from the standard.
143 * @param string $host The host part of an url
145 * @return array with template and type of the webfinger template for JSON or XML
146 * @throws HTTPException\InternalServerErrorException
148 private static function hostMeta($host)
150 // Reset the static variable
153 // Handles the case when the hostname contains the scheme
154 if (!parse_url($host, PHP_URL_SCHEME)) {
155 $ssl_url = "https://" . $host . "/.well-known/host-meta";
156 $url = "http://" . $host . "/.well-known/host-meta";
158 $ssl_url = $host . "/.well-known/host-meta";
162 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
164 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
167 $curlResult = Network::curl($ssl_url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
168 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
169 if ($curlResult->isSuccess()) {
170 $xml = $curlResult->getBody();
171 $xrd = XML::parseString($xml, true);
173 $host_url = 'https://' . $host;
177 } elseif ($curlResult->isTimeout()) {
178 Logger::info('Probing timeout', ['url' => $ssl_url], Logger::DEBUG);
179 self::$istimeout = true;
183 if (!is_object($xrd) && !empty($url)) {
184 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
185 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
186 if ($curlResult->isTimeout()) {
187 Logger::info('Probing timeout', ['url' => $url], Logger::DEBUG);
188 self::$istimeout = true;
190 } elseif ($connection_error && $ssl_connection_error) {
191 self::$istimeout = true;
195 $xml = $curlResult->getBody();
196 $xrd = XML::parseString($xml, true);
197 $host_url = 'http://'.$host;
199 if (!is_object($xrd)) {
200 Logger::log("No xrd object found for ".$host, Logger::DEBUG);
204 $links = XML::elementToArray($xrd);
205 if (!isset($links["xrd"]["link"])) {
206 Logger::log("No xrd data found for ".$host, Logger::DEBUG);
210 $lrdd = ['application/jrd+json' => $host_url . '/.well-known/webfinger?resource={uri}'];
212 foreach ($links["xrd"]["link"] as $value => $link) {
213 if (!empty($link["@attributes"])) {
214 $attributes = $link["@attributes"];
215 } elseif ($value == "@attributes") {
221 if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
222 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
224 $lrdd[$type] = $attributes["template"];
228 self::$baseurl = $host_url;
230 Logger::log("Probing successful for ".$host, Logger::DEBUG);
236 * Perform Webfinger lookup and return DFRN data
238 * Given an email style address, perform webfinger lookup and
239 * return the resulting DFRN profile URL, or if no DFRN profile URL
240 * is located, returns an OStatus subscription template (prefixed
241 * with the string 'stat:' to identify it as on OStatus template).
242 * If this isn't an email style address just return $webbie.
243 * Return an empty string if email-style addresses but webfinger fails,
244 * or if the resultant personal XRD doesn't contain a supported
245 * subscription/friend-request attribute.
247 * amended 7/9/2011 to return an hcard which could save potentially loading
248 * a lengthy content page to scrape dfrn attributes
250 * @param string $webbie Address that should be probed
251 * @param string $hcard_url Link to the hcard - is returned by reference
253 * @return string profile link
254 * @throws HTTPException\InternalServerErrorException
256 public static function webfingerDfrn($webbie, &$hcard_url)
260 $links = self::lrdd($webbie);
261 Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA);
262 if (!empty($links) && is_array($links)) {
263 foreach ($links as $link) {
264 if ($link['@attributes']['rel'] === ActivityNamespace::DFRN) {
265 $profile_link = $link['@attributes']['href'];
267 if (($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) && ($profile_link == "")) {
268 $profile_link = 'stat:'.$link['@attributes']['template'];
270 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
271 $hcard_url = $link['@attributes']['href'];
275 return $profile_link;
279 * Check an URI for LRDD data
281 * @param string $uri Address that should be probed
283 * @return array uri data
284 * @throws HTTPException\InternalServerErrorException
286 public static function lrdd(string $uri)
288 $lrdd = self::hostMeta($uri);
291 if (is_bool($lrdd)) {
296 $parts = @parse_url($uri);
297 if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
301 $host = $parts['scheme'] . '://' . $parts["host"];
302 if (!empty($parts["port"])) {
303 $host .= ':'.$parts["port"];
306 $path_parts = explode("/", trim($parts["path"], "/"));
308 $nick = array_pop($path_parts);
311 $lrdd = self::hostMeta($host);
312 $host .= "/".array_shift($path_parts);
313 } while (!$lrdd && (sizeof($path_parts) > 0));
317 Logger::log("No lrdd data found for ".$uri, Logger::DEBUG);
321 foreach ($lrdd as $type => $template) {
326 $path = str_replace('{uri}', urlencode($uri), $template);
327 $webfinger = self::webfinger($path, $type);
329 if (!$webfinger && (strstr($uri, "@"))) {
330 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
331 $webfinger = self::webfinger($path, $type);
334 // Special treatment for Mastodon
335 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
336 // But the webfinger for this format fails.
337 if (!$webfinger && !empty($nick)) {
338 // Mastodon uses a "@" as prefix for usernames in their url format
339 $nick = ltrim($nick, '@');
341 $addr = $nick."@".$host;
343 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
344 $webfinger = self::webfinger($path, $type);
348 if (empty($webfinger["links"])) {
349 Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
355 foreach ($webfinger["links"] as $link) {
356 $data[] = ["@attributes" => $link];
359 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
360 foreach ($webfinger["aliases"] as $alias) {
361 $data[] = ["@attributes" =>
371 * Fetch information (protocol endpoints and user information) about a given uri
373 * @param string $uri Address that should be probed
374 * @param string $network Test for this specific network
375 * @param integer $uid User ID for the probe (only used for mails)
376 * @param boolean $cache Use cached values?
378 * @return array uri data
379 * @throws HTTPException\InternalServerErrorException
380 * @throws \ImagickException
382 public static function uri($uri, $network = '', $uid = -1, $cache = true)
385 $result = DI::cache()->get('Probe::uri:' . $network . ':' . $uri);
386 if (!is_null($result)) {
395 self::$istimeout = false;
397 if ($network != Protocol::ACTIVITYPUB) {
398 $data = self::detect($uri, $network, $uid);
403 // When the previous detection process had got a time out
404 // we could falsely detect a Friendica profile as AP profile.
405 if (!self::$istimeout) {
406 $ap_profile = ActivityPub::probeProfile($uri, !$cache);
408 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
410 } elseif (!empty($ap_profile)) {
411 $ap_profile['batch'] = '';
412 $data = array_merge($ap_profile, $data);
415 Logger::notice('Time out detected. AP will not be probed.', ['uri' => $uri]);
418 if (!isset($data['url'])) {
422 if (empty($data['photo'])) {
423 $data['photo'] = DI::baseUrl() . '/images/person-300.jpg';
426 if (empty($data['name'])) {
427 if (!empty($data['nick'])) {
428 $data['name'] = $data['nick'];
431 if (empty($data['name'])) {
432 $data['name'] = $data['url'];
436 if (empty($data['nick'])) {
437 $data['nick'] = strtolower($data['name']);
439 if (strpos($data['nick'], ' ')) {
440 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
444 if (empty($data['baseurl']) && !empty(self::$baseurl)) {
445 $data['baseurl'] = self::$baseurl;
448 if (!empty($data['baseurl']) && empty($data['gsid'])) {
449 $data['gsid'] = GServer::getID($data['baseurl']);
452 if (empty($data['network'])) {
453 $data['network'] = Protocol::PHANTOM;
456 // Ensure that local connections always are DFRN
457 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
458 $data['network'] = Protocol::DFRN;
461 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
462 $data['hide'] = self::getHideStatus($data['url']);
465 $data = self::rearrangeData($data);
467 // Only store into the cache if the value seems to be valid
468 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
469 DI::cache()->set('Probe::uri:' . $network . ':' . $uri, $data, Duration::DAY);
477 * Fetches the "hide" status from the profile
479 * @param string $url URL of the profile
481 * @return boolean "hide" status
483 private static function getHideStatus($url)
485 $curlResult = Network::curl($url);
486 if (!$curlResult->isSuccess()) {
490 // If the file is too large then exit
491 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
495 // If it isn't a HTML file then exit
496 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
500 $body = $curlResult->getBody();
502 $doc = new DOMDocument();
503 @$doc->loadHTML($body);
505 $xpath = new DOMXPath($doc);
507 $list = $xpath->query('//meta[@name]');
508 foreach ($list as $node) {
510 if ($node->attributes->length) {
511 foreach ($node->attributes as $attribute) {
512 $meta_tag[$attribute->name] = $attribute->value;
516 if (empty($meta_tag['content'])) {
520 $content = strtolower(trim($meta_tag['content']));
522 switch (strtolower(trim($meta_tag['name']))) {
523 case 'dfrn-global-visibility':
524 if ($content == 'false') {
529 if (strpos($content, 'noindex') !== false) {
540 * Checks if a profile url should be OStatus but only provides partial information
542 * @param array $webfinger Webfinger data
543 * @param string $lrdd Path template for webfinger request
544 * @param string $type type
546 * @return array fixed webfinger data
547 * @throws HTTPException\InternalServerErrorException
549 private static function fixOStatus($webfinger, $lrdd, $type)
551 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
558 foreach ($webfinger['links'] as $link) {
559 if ($link['rel'] == ActivityNamespace::OSTATUSSUB) {
562 if ($link['rel'] == 'magic-public-key') {
567 if (!$is_ostatus || $has_key) {
571 $url = Network::switchScheme($webfinger['subject']);
572 $path = str_replace('{uri}', urlencode($url), $lrdd);
573 $webfinger2 = self::webfinger($path, $type);
575 // Is the new webfinger detectable as OStatus?
576 if (self::ostatus($webfinger2, true)) {
577 $webfinger = $webfinger2;
584 * Fetch the "subscribe" and add it to the result
586 * @param array $result
587 * @param array $webfinger
588 * @return array result
590 private static function getSubscribeLink(array $result, array $webfinger)
592 if (empty($webfinger['links'])) {
596 foreach ($webfinger['links'] as $link) {
597 if (!empty($link['template']) && ($link['rel'] === ActivityNamespace::OSTATUSSUB)) {
598 $result['subscribe'] = $link['template'];
606 * Fetch information (protocol endpoints and user information) about a given uri
608 * This function is only called by the "uri" function that adds caching and rearranging of data.
610 * @param string $uri Address that should be probed
611 * @param string $network Test for this specific network
612 * @param integer $uid User ID for the probe (only used for mails)
614 * @return array uri data
615 * @throws HTTPException\InternalServerErrorException
617 private static function detect($uri, $network, $uid)
619 $parts = parse_url($uri);
623 'network' => $network,
628 Hook::callAll('probe_detect', $hookData);
630 if ($hookData['result']) {
631 return $hookData['result'];
634 if (!empty($parts["scheme"]) && !empty($parts["host"])) {
635 $host = $parts["host"];
636 if (!empty($parts["port"])) {
637 $host .= ':'.$parts["port"];
640 if ($host == 'twitter.com') {
641 return self::twitter($uri);
643 $lrdd = self::hostMeta($host);
645 if (is_bool($lrdd)) {
649 $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
651 while (!$lrdd && (sizeof($path_parts) > 1)) {
652 $host .= "/".array_shift($path_parts);
653 $lrdd = self::hostMeta($host);
656 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
657 return self::feed($uri);
659 $nick = array_pop($path_parts);
661 // Mastodon uses a "@" as prefix for usernames in their url format
662 $nick = ltrim($nick, '@');
664 $addr = $nick."@".$host;
665 } elseif (strstr($uri, '@')) {
666 // If the URI starts with "mailto:" then jump directly to the mail detection
667 if (strpos($uri, 'mailto:') !== false) {
668 $uri = str_replace('mailto:', '', $uri);
669 return self::mail($uri, $uid);
672 if ($network == Protocol::MAIL) {
673 return self::mail($uri, $uid);
675 // Remove "acct:" from the URI
676 $uri = str_replace('acct:', '', $uri);
678 $host = substr($uri, strpos($uri, '@') + 1);
679 $nick = substr($uri, 0, strpos($uri, '@'));
681 if (strpos($uri, '@twitter.com')) {
682 return self::twitter($uri);
684 $lrdd = self::hostMeta($host);
686 if (is_bool($lrdd)) {
691 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
692 return self::mail($uri, $uid);
696 Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
702 /// @todo Do we need the prefix "acct:" or "acct://"?
704 foreach ($lrdd as $type => $template) {
709 // At first try it with the given uri
710 $path = str_replace('{uri}', urlencode($uri), $template);
711 $webfinger = self::webfinger($path, $type);
713 // Fix possible problems with GNU Social probing to wrong scheme
714 $webfinger = self::fixOStatus($webfinger, $template, $type);
716 // We cannot be sure that the detected address was correct, so we don't use the values
717 if ($webfinger && ($uri != $addr)) {
722 // Try webfinger with the address (user@domain.tld)
724 $path = str_replace('{uri}', urlencode($addr), $template);
725 $webfinger = self::webfinger($path, $type);
728 // Mastodon needs to have it with "acct:"
730 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
731 $webfinger = self::webfinger($path, $type);
736 return self::feed($uri);
741 Logger::info("Probing", ['uri' => $uri]);
743 if (in_array($network, ["", Protocol::DFRN])) {
744 $result = self::dfrn($webfinger);
746 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
747 $result = self::diaspora($webfinger);
749 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
750 $result = self::ostatus($webfinger);
752 if (in_array($network, ['', Protocol::ZOT])) {
753 $result = self::zot($webfinger, $result);
755 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
756 $result = self::pumpio($webfinger, $addr);
758 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
759 $result = self::feed($uri);
761 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
762 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
763 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
764 $result["nick"] = $nick;
767 if (empty($result["addr"]) && ($addr != "")) {
768 $result["addr"] = $addr;
772 $result = self::getSubscribeLink($result, $webfinger);
774 if (empty($result["network"])) {
775 $result["network"] = Protocol::PHANTOM;
778 if (empty($result["url"])) {
779 $result["url"] = $uri;
782 Logger::log($uri." is ".$result["network"], Logger::DEBUG);
788 * Check for Zot contact
790 * @param array $webfinger Webfinger data
791 * @param array $data previously probed data
793 * @return array Zot data
794 * @throws HTTPException\InternalServerErrorException
796 private static function zot($webfinger, $data)
798 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
799 foreach ($webfinger["aliases"] as $alias) {
800 if (substr($alias, 0, 5) == 'acct:') {
801 $data["addr"] = substr($alias, 5);
806 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
807 $data["addr"] = substr($webfinger["subject"], 5);
811 foreach ($webfinger['links'] as $link) {
812 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
813 $zot_url = $link['href'];
817 if (empty($zot_url) && !empty($data['addr']) && !empty(self::$baseurl)) {
818 $condition = ['nurl' => Strings::normaliseLink(self::$baseurl), 'platform' => ['hubzilla']];
819 if (!DBA::exists('gserver', $condition)) {
822 $zot_url = self::$baseurl . '/.well-known/zot-info?address=' . $data['addr'];
825 if (empty($zot_url)) {
829 $data = self::pollZot($zot_url, $data);
831 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
832 foreach ($webfinger['aliases'] as $alias) {
833 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
834 $data['alias'] = $alias;
842 public static function pollZot($url, $data)
844 $curlResult = Network::curl($url);
845 if ($curlResult->isTimeout()) {
848 $content = $curlResult->getBody();
853 $json = json_decode($content, true);
854 if (!is_array($json)) {
858 if (empty($data['network'])) {
859 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
860 $data['network'] = Protocol::ZOT;
861 } elseif (!isset($json['protocols'])) {
862 $data['network'] = Protocol::ZOT;
866 if (!empty($json['guid']) && empty($data['guid'])) {
867 $data['guid'] = $json['guid'];
869 if (!empty($json['key']) && empty($data['pubkey'])) {
870 $data['pubkey'] = $json['key'];
872 if (!empty($json['name'])) {
873 $data['name'] = $json['name'];
875 if (!empty($json['photo'])) {
876 $data['photo'] = $json['photo'];
877 if (!empty($json['photo_updated'])) {
878 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
881 if (!empty($json['address'])) {
882 $data['addr'] = $json['address'];
884 if (!empty($json['url'])) {
885 $data['url'] = $json['url'];
887 if (!empty($json['connections_url'])) {
888 $data['poco'] = $json['connections_url'];
890 if (isset($json['searchable'])) {
891 $data['hide'] = !$json['searchable'];
893 if (!empty($json['public_forum'])) {
894 $data['community'] = $json['public_forum'];
895 $data['account-type'] = Contact::PAGE_COMMUNITY;
898 if (!empty($json['profile'])) {
899 $profile = $json['profile'];
900 if (!empty($profile['description'])) {
901 $data['about'] = $profile['description'];
903 if (!empty($profile['keywords'])) {
904 $keywords = implode(', ', $profile['keywords']);
905 if (!empty($keywords)) {
906 $data['keywords'] = $keywords;
911 if (!empty($profile['region'])) {
912 $loc['region'] = $profile['region'];
914 if (!empty($profile['country'])) {
915 $loc['country-name'] = $profile['country'];
917 $location = Profile::formatLocation($loc);
918 if (!empty($location)) {
919 $data['location'] = $location;
927 * Perform a webfinger request.
929 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
931 * @param string $url Address that should be probed
932 * @param string $type type
934 * @return array webfinger data
935 * @throws HTTPException\InternalServerErrorException
937 public static function webfinger($url, $type)
939 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
941 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
942 if ($curlResult->isTimeout()) {
943 self::$istimeout = true;
946 $data = $curlResult->getBody();
948 $webfinger = json_decode($data, true);
949 if (!empty($webfinger)) {
950 if (!isset($webfinger["links"])) {
951 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
957 // If it is not JSON, maybe it is XML
958 $xrd = XML::parseString($data, true);
959 if (!is_object($xrd)) {
960 Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
964 $xrd_arr = XML::elementToArray($xrd);
965 if (!isset($xrd_arr["xrd"]["link"])) {
966 Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
972 if (!empty($xrd_arr["xrd"]["subject"])) {
973 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
976 if (!empty($xrd_arr["xrd"]["alias"])) {
977 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
980 $webfinger["links"] = [];
982 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
983 if (!empty($data["@attributes"])) {
984 $attributes = $data["@attributes"];
985 } elseif ($value == "@attributes") {
991 $webfinger["links"][] = $attributes;
997 * Poll the Friendica specific noscrape page.
999 * "noscrape" is a faster alternative to fetch the data from the hcard.
1000 * This functionality was originally created for the directory.
1002 * @param string $noscrape_url Link to the noscrape page
1003 * @param array $data The already fetched data
1005 * @return array noscrape data
1006 * @throws HTTPException\InternalServerErrorException
1008 private static function pollNoscrape($noscrape_url, $data)
1010 $curlResult = Network::curl($noscrape_url);
1011 if ($curlResult->isTimeout()) {
1012 self::$istimeout = true;
1015 $content = $curlResult->getBody();
1017 Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
1021 $json = json_decode($content, true);
1022 if (!is_array($json)) {
1023 Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
1027 if (!empty($json["fn"])) {
1028 $data["name"] = $json["fn"];
1031 if (!empty($json["addr"])) {
1032 $data["addr"] = $json["addr"];
1035 if (!empty($json["nick"])) {
1036 $data["nick"] = $json["nick"];
1039 if (!empty($json["guid"])) {
1040 $data["guid"] = $json["guid"];
1043 if (!empty($json["comm"])) {
1044 $data["community"] = $json["comm"];
1047 if (!empty($json["tags"])) {
1048 $keywords = implode(", ", $json["tags"]);
1049 if ($keywords != "") {
1050 $data["keywords"] = $keywords;
1054 $location = Profile::formatLocation($json);
1056 $data["location"] = $location;
1059 if (!empty($json["about"])) {
1060 $data["about"] = $json["about"];
1063 if (!empty($json["key"])) {
1064 $data["pubkey"] = $json["key"];
1067 if (!empty($json["photo"])) {
1068 $data["photo"] = $json["photo"];
1071 if (!empty($json["dfrn-request"])) {
1072 $data["request"] = $json["dfrn-request"];
1075 if (!empty($json["dfrn-confirm"])) {
1076 $data["confirm"] = $json["dfrn-confirm"];
1079 if (!empty($json["dfrn-notify"])) {
1080 $data["notify"] = $json["dfrn-notify"];
1083 if (!empty($json["dfrn-poll"])) {
1084 $data["poll"] = $json["dfrn-poll"];
1087 if (isset($json["hide"])) {
1088 $data["hide"] = (bool)$json["hide"];
1090 $data["hide"] = false;
1097 * Check for valid DFRN data
1099 * @param array $data DFRN data
1101 * @return int Number of errors
1103 public static function validDfrn($data)
1106 if (!isset($data['key'])) {
1109 if (!isset($data['dfrn-request'])) {
1112 if (!isset($data['dfrn-confirm'])) {
1115 if (!isset($data['dfrn-notify'])) {
1118 if (!isset($data['dfrn-poll'])) {
1125 * Fetch data from a DFRN profile page and via "noscrape"
1127 * @param string $profile_link Link to the profile page
1129 * @return array profile data
1130 * @throws HTTPException\InternalServerErrorException
1131 * @throws \ImagickException
1133 public static function profile($profile_link)
1137 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
1139 // Fetch data via noscrape - this is faster
1140 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1141 $data = self::pollNoscrape($noscrape_url, $data);
1143 if (!isset($data["notify"])
1144 || !isset($data["confirm"])
1145 || !isset($data["request"])
1146 || !isset($data["poll"])
1147 || !isset($data["name"])
1148 || !isset($data["photo"])
1150 $data = self::pollHcard($profile_link, $data, true);
1155 if (empty($data["addr"]) || empty($data["nick"])) {
1156 $probe_data = self::uri($profile_link);
1157 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1158 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1161 $prof_data["addr"] = $data["addr"];
1162 $prof_data["nick"] = $data["nick"];
1163 $prof_data["dfrn-request"] = $data['request'] ?? null;
1164 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1165 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1166 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1167 $prof_data["photo"] = $data['photo'] ?? null;
1168 $prof_data["fn"] = $data['name'] ?? null;
1169 $prof_data["key"] = $data['pubkey'] ?? null;
1171 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
1177 * Check for DFRN contact
1179 * @param array $webfinger Webfinger data
1181 * @return array DFRN data
1182 * @throws HTTPException\InternalServerErrorException
1184 private static function dfrn($webfinger)
1188 // The array is reversed to take into account the order of preference for same-rel links
1189 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1190 foreach (array_reverse($webfinger["links"]) as $link) {
1191 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1192 $data["network"] = Protocol::DFRN;
1193 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1194 $data["poll"] = $link["href"];
1195 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1196 $data["url"] = $link["href"];
1197 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1198 $hcard_url = $link["href"];
1199 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1200 $data["poco"] = $link["href"];
1201 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1202 $data["photo"] = $link["href"];
1203 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1204 $data["baseurl"] = trim($link["href"], '/');
1205 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1206 $data["guid"] = $link["href"];
1207 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1208 $data["pubkey"] = base64_decode($link["href"]);
1210 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1211 if (strstr($data["pubkey"], 'RSA ')) {
1212 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1217 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1218 foreach ($webfinger["aliases"] as $alias) {
1219 if (empty($data["url"]) && !strstr($alias, "@")) {
1220 $data["url"] = $alias;
1221 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1222 $data["alias"] = $alias;
1223 } elseif (substr($alias, 0, 5) == 'acct:') {
1224 $data["addr"] = substr($alias, 5);
1229 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1230 $data["addr"] = substr($webfinger["subject"], 5);
1233 if (!isset($data["network"]) || ($hcard_url == "")) {
1237 // Fetch data via noscrape - this is faster
1238 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1239 $data = self::pollNoscrape($noscrape_url, $data);
1241 if (isset($data["notify"])
1242 && isset($data["confirm"])
1243 && isset($data["request"])
1244 && isset($data["poll"])
1245 && isset($data["name"])
1246 && isset($data["photo"])
1251 $data = self::pollHcard($hcard_url, $data, true);
1257 * Poll the hcard page (Diaspora and Friendica specific)
1259 * @param string $hcard_url Link to the hcard page
1260 * @param array $data The already fetched data
1261 * @param boolean $dfrn Poll DFRN specific data
1263 * @return array hcard data
1264 * @throws HTTPException\InternalServerErrorException
1266 private static function pollHcard($hcard_url, $data, $dfrn = false)
1268 $curlResult = Network::curl($hcard_url);
1269 if ($curlResult->isTimeout()) {
1270 self::$istimeout = true;
1273 $content = $curlResult->getBody();
1278 $doc = new DOMDocument();
1279 if (!@$doc->loadHTML($content)) {
1283 $xpath = new DomXPath($doc);
1285 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1286 if (!is_object($vcards)) {
1290 if (!isset($data["baseurl"])) {
1291 $data["baseurl"] = "";
1294 if ($vcards->length > 0) {
1295 $vcard = $vcards->item(0);
1297 // We have to discard the guid from the hcard in favour of the guid from lrdd
1298 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1299 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1300 if (($search->length > 0) && empty($data["guid"])) {
1301 $data["guid"] = $search->item(0)->nodeValue;
1304 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1305 if ($search->length > 0) {
1306 $data["nick"] = $search->item(0)->nodeValue;
1309 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1310 if ($search->length > 0) {
1311 $data["name"] = $search->item(0)->nodeValue;
1314 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1315 if ($search->length > 0) {
1316 $data["searchable"] = $search->item(0)->nodeValue;
1319 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1320 if ($search->length > 0) {
1321 $data["pubkey"] = $search->item(0)->nodeValue;
1322 if (strstr($data["pubkey"], 'RSA ')) {
1323 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1327 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1328 if ($search->length > 0) {
1329 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1334 if (!empty($vcard)) {
1335 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1336 foreach ($photos as $photo) {
1338 foreach ($photo->attributes as $attribute) {
1339 $attr[$attribute->name] = trim($attribute->value);
1342 if (isset($attr["src"]) && isset($attr["width"])) {
1343 $avatar[$attr["width"]] = $attr["src"];
1346 // We don't have a width. So we just take everything that we got.
1347 // This is a Hubzilla workaround which doesn't send a width.
1348 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1349 $avatar[] = $attr["src"];
1354 if (sizeof($avatar)) {
1356 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1360 // Poll DFRN specific data
1361 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1362 if ($search->length > 0) {
1363 foreach ($search as $link) {
1364 //$data["request"] = $search->item(0)->nodeValue;
1366 foreach ($link->attributes as $attribute) {
1367 $attr[$attribute->name] = trim($attribute->value);
1370 $data[substr($attr["rel"], 5)] = $attr["href"];
1374 // Older Friendica versions had used the "uid" field differently than newer versions
1375 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1376 unset($data["guid"]);
1385 * Check for Diaspora contact
1387 * @param array $webfinger Webfinger data
1389 * @return array Diaspora data
1390 * @throws HTTPException\InternalServerErrorException
1392 private static function diaspora($webfinger)
1397 // The array is reversed to take into account the order of preference for same-rel links
1398 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1399 foreach (array_reverse($webfinger["links"]) as $link) {
1400 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1401 $hcard_url = $link["href"];
1402 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1403 $data["baseurl"] = trim($link["href"], '/');
1404 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1405 $data["guid"] = $link["href"];
1406 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1407 $data["url"] = $link["href"];
1408 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1409 $data["poll"] = $link["href"];
1410 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1411 $data["poco"] = $link["href"];
1412 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1413 $data["notify"] = $link["href"];
1414 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1415 $data["pubkey"] = base64_decode($link["href"]);
1417 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1418 if (strstr($data["pubkey"], 'RSA ')) {
1419 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1424 if (empty($data["url"]) || empty($hcard_url)) {
1428 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1429 foreach ($webfinger["aliases"] as $alias) {
1430 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1431 $data["alias"] = $alias;
1432 } elseif (substr($alias, 0, 5) == 'acct:') {
1433 $data["addr"] = substr($alias, 5);
1438 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1439 $data["addr"] = substr($webfinger["subject"], 5);
1442 // Fetch further information from the hcard
1443 $data = self::pollHcard($hcard_url, $data);
1449 if (!empty($data["url"])
1450 && !empty($data["guid"])
1451 && !empty($data["baseurl"])
1452 && !empty($data["pubkey"])
1453 && !empty($hcard_url)
1455 $data["network"] = Protocol::DIASPORA;
1457 // The Diaspora handle must always be lowercase
1458 if (!empty($data["addr"])) {
1459 $data["addr"] = strtolower($data["addr"]);
1462 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1463 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1464 $data["batch"] = $data["baseurl"] . "/receive/public";
1473 * Check for OStatus contact
1475 * @param array $webfinger Webfinger data
1476 * @param bool $short Short detection mode
1478 * @return array|bool OStatus data or "false" on error or "true" on short mode
1479 * @throws HTTPException\InternalServerErrorException
1481 private static function ostatus($webfinger, $short = false)
1485 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1486 foreach ($webfinger["aliases"] as $alias) {
1487 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1488 $data["addr"] = str_replace('acct:', '', $alias);
1493 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1494 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1496 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1499 if (!empty($webfinger["links"])) {
1500 // The array is reversed to take into account the order of preference for same-rel links
1501 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1502 foreach (array_reverse($webfinger["links"]) as $link) {
1503 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1504 && (($link["type"] ?? "") == "text/html")
1505 && ($link["href"] != "")
1507 $data["url"] = $link["href"];
1508 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1509 $data["notify"] = $link["href"];
1510 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1511 $data["poll"] = $link["href"];
1512 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1513 $pubkey = $link["href"];
1515 if (substr($pubkey, 0, 5) === 'data:') {
1516 if (strstr($pubkey, ',')) {
1517 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1519 $pubkey = substr($pubkey, 5);
1521 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1522 $curlResult = Network::curl($pubkey);
1523 if ($curlResult->isTimeout()) {
1524 self::$istimeout = true;
1525 return $short ? false : [];
1527 $pubkey = $curlResult->getBody();
1530 $key = explode(".", $pubkey);
1532 if (sizeof($key) >= 3) {
1533 $m = Strings::base64UrlDecode($key[1]);
1534 $e = Strings::base64UrlDecode($key[2]);
1535 $data["pubkey"] = Crypto::meToPem($m, $e);
1541 if (isset($data["notify"]) && isset($data["pubkey"])
1542 && isset($data["poll"])
1543 && isset($data["url"])
1545 $data["network"] = Protocol::OSTATUS;
1547 return $short ? false : [];
1554 // Fetch all additional data from the feed
1555 $curlResult = Network::curl($data["poll"]);
1556 if ($curlResult->isTimeout()) {
1557 self::$istimeout = true;
1560 $feed = $curlResult->getBody();
1561 $feed_data = Feed::import($feed);
1566 if (!empty($feed_data["header"]["author-name"])) {
1567 $data["name"] = $feed_data["header"]["author-name"];
1569 if (!empty($feed_data["header"]["author-nick"])) {
1570 $data["nick"] = $feed_data["header"]["author-nick"];
1572 if (!empty($feed_data["header"]["author-avatar"])) {
1573 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1575 if (!empty($feed_data["header"]["author-id"])) {
1576 $data["alias"] = $feed_data["header"]["author-id"];
1578 if (!empty($feed_data["header"]["author-location"])) {
1579 $data["location"] = $feed_data["header"]["author-location"];
1581 if (!empty($feed_data["header"]["author-about"])) {
1582 $data["about"] = $feed_data["header"]["author-about"];
1584 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1585 // So we take the value that we just fetched, although the other one worked as well
1586 if (!empty($feed_data["header"]["author-link"])) {
1587 $data["url"] = $feed_data["header"]["author-link"];
1590 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1591 $data['url'] = $data["alias"];
1592 $data["alias"] = '';
1595 /// @todo Fetch location and "about" from the feed as well
1600 * Fetch data from a pump.io profile page
1602 * @param string $profile_link Link to the profile page
1604 * @return array profile data
1606 private static function pumpioProfileData($profile_link)
1608 $curlResult = Network::curl($profile_link);
1609 if (!$curlResult->isSuccess()) {
1613 $doc = new DOMDocument();
1614 if (!@$doc->loadHTML($curlResult->getBody())) {
1618 $xpath = new DomXPath($doc);
1622 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1624 if ($data["name"] == '') {
1625 // This is ugly - but pump.io doesn't seem to know a better way for it
1626 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1627 $pos = strpos($data["name"], chr(10));
1629 $data["name"] = trim(substr($data["name"], 0, $pos));
1633 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1635 if ($data["location"] == '') {
1636 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1639 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1641 if ($data["about"] == '') {
1642 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1645 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1647 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1650 foreach ($avatar->attributes as $attribute) {
1651 if ($attribute->name == "src") {
1652 $data["photo"] = trim($attribute->value);
1661 * Check for pump.io contact
1663 * @param array $webfinger Webfinger data
1664 * @param string $addr
1665 * @return array pump.io data
1667 private static function pumpio($webfinger, $addr)
1670 // The array is reversed to take into account the order of preference for same-rel links
1671 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1672 foreach (array_reverse($webfinger["links"]) as $link) {
1673 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1674 && (($link["type"] ?? "") == "text/html")
1675 && ($link["href"] != "")
1677 $data["url"] = $link["href"];
1678 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1679 $data["notify"] = $link["href"];
1680 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1681 $data["poll"] = $link["href"];
1682 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1683 $data["dialback"] = $link["href"];
1686 if (isset($data["poll"]) && isset($data["notify"])
1687 && isset($data["dialback"])
1688 && isset($data["url"])
1690 // by now we use these fields only for the network type detection
1691 // So we unset all data that isn't used at the moment
1692 unset($data["dialback"]);
1694 $data["network"] = Protocol::PUMPIO;
1699 $profile_data = self::pumpioProfileData($data["url"]);
1701 if (!$profile_data) {
1705 $data = array_merge($data, $profile_data);
1707 if (($addr != '') && ($data['name'] != '')) {
1708 $name = trim(str_replace($addr, '', $data['name']));
1710 $data['name'] = $name;
1718 * Check for twitter contact
1720 * @param string $uri
1722 * @return array twitter data
1724 private static function twitter($uri)
1726 if (preg_match('=(.*)@twitter.com=i', $uri, $matches)) {
1727 $nick = $matches[1];
1728 } elseif (preg_match('=https?://twitter.com/(.*)=i', $uri, $matches)) {
1729 $nick = $matches[1];
1735 $data['url'] = 'https://twitter.com/' . $nick;
1736 $data['addr'] = $nick . '@twitter.com';
1737 $data['nick'] = $data['name'] = $nick;
1738 $data['network'] = Protocol::TWITTER;
1739 $data['baseurl'] = 'https://twitter.com';
1745 * Checks HTML page for RSS feed link
1747 * @param string $url Page link
1748 * @param string $body Page body string
1749 * @return string|false Feed link or false if body was invalid HTML document
1751 public static function getFeedLink(string $url, string $body)
1753 $doc = new DOMDocument();
1754 if (!@$doc->loadHTML($body)) {
1758 $xpath = new DOMXPath($doc);
1760 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1762 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1768 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1770 * Loosely based on RFC 1808
1772 * @see https://tools.ietf.org/html/rfc1808
1774 * @param string $href The potential relative href found in the HTML document
1775 * @param string $base The HTML document URL
1776 * @param DOMXPath $xpath The HTML document XPath
1779 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath)
1781 if (filter_var($href, FILTER_VALIDATE_URL)) {
1785 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1787 $baseParts = parse_url($base);
1789 // Naked domain case (scheme://basehost)
1790 $path = $baseParts['path'] ?? '/';
1792 // Remove the filename part of the path if it exists (/base/path/file)
1793 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1795 $hrefParts = parse_url($href);
1797 // Root path case (/path) including relative scheme case (//host/path)
1798 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1799 $path = $hrefParts['path'];
1801 $path = $path . '/' . $hrefParts['path'];
1803 // Resolve arbitrary relative path
1804 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1805 $parts = array_filter(explode('/', $path), 'strlen');
1806 $absolutes = array();
1807 foreach ($parts as $part) {
1808 if ('.' == $part) continue;
1809 if ('..' == $part) {
1810 array_pop($absolutes);
1812 $absolutes[] = $part;
1816 $path = '/' . implode('/', $absolutes);
1819 // Relative scheme case (//host/path)
1820 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1821 $baseParts['path'] = $path;
1822 unset($baseParts['query']);
1823 unset($baseParts['fragment']);
1825 return Network::unparseURL($baseParts);
1829 * Check for feed contact
1831 * @param string $url Profile link
1832 * @param boolean $probe Do a probe if the page contains a feed link
1834 * @return array feed data
1835 * @throws HTTPException\InternalServerErrorException
1837 private static function feed($url, $probe = true)
1839 $curlResult = Network::curl($url);
1840 if ($curlResult->isTimeout()) {
1841 self::$istimeout = true;
1844 $feed = $curlResult->getBody();
1845 $feed_data = Feed::import($feed);
1852 $feed_url = self::getFeedLink($url, $feed);
1858 return self::feed($feed_url, false);
1861 if (!empty($feed_data["header"]["author-name"])) {
1862 $data["name"] = $feed_data["header"]["author-name"];
1865 if (!empty($feed_data["header"]["author-nick"])) {
1866 $data["nick"] = $feed_data["header"]["author-nick"];
1869 if (!empty($feed_data["header"]["author-avatar"])) {
1870 $data["photo"] = $feed_data["header"]["author-avatar"];
1873 if (!empty($feed_data["header"]["author-id"])) {
1874 $data["alias"] = $feed_data["header"]["author-id"];
1877 $data["url"] = $url;
1878 $data["poll"] = $url;
1880 if (!empty($feed_data["header"]["author-link"])) {
1881 $data["baseurl"] = $feed_data["header"]["author-link"];
1883 $data["baseurl"] = $data["url"];
1886 $data["network"] = Protocol::FEED;
1892 * Check for mail contact
1894 * @param string $uri Profile link
1895 * @param integer $uid User ID
1897 * @return array mail data
1898 * @throws \Exception
1900 private static function mail($uri, $uid)
1902 if (!Network::isEmailDomainValid($uri)) {
1910 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1912 $condition = ["`uid` = ? AND `server` != ''", $uid];
1913 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1914 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1916 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1920 $mailbox = Email::constructMailboxName($mailacct);
1922 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1923 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1928 $msgs = Email::poll($mbox, $uri);
1929 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1931 if (!count($msgs)) {
1935 $phost = substr($uri, strpos($uri, '@') + 1);
1938 $data["addr"] = $uri;
1939 $data["network"] = Protocol::MAIL;
1940 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1941 $data["nick"] = $data["name"];
1942 $data["photo"] = Network::lookupAvatarByEmail($uri);
1943 $data["url"] = 'mailto:'.$uri;
1944 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1945 $data["poll"] = 'email ' . Strings::getRandomHex();
1947 $x = Email::messageMeta($mbox, $msgs[0]);
1948 if (stristr($x[0]->from, $uri)) {
1949 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1950 } elseif (stristr($x[0]->to, $uri)) {
1951 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1954 foreach ($adr as $feadr) {
1955 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1956 &&(strcasecmp($feadr->host, $phost) == 0)
1957 && (strlen($feadr->personal))
1959 $personal = imap_mime_header_decode($feadr->personal);
1961 foreach ($personal as $perspart) {
1962 if ($perspart->charset != "default") {
1963 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1965 $data["name"] .= $perspart->text;
1969 $data["name"] = Strings::escapeTags($data["name"]);
1973 if (!empty($mbox)) {
1980 * Mix two paths together to possibly fix missing parts
1982 * @param string $avatar Path to the avatar
1983 * @param string $base Another path that is hopefully complete
1985 * @return string fixed avatar path
1986 * @throws \Exception
1988 public static function fixAvatar($avatar, $base)
1990 $base_parts = parse_url($base);
1992 // Remove all parts that could create a problem
1993 unset($base_parts['path']);
1994 unset($base_parts['query']);
1995 unset($base_parts['fragment']);
1997 $avatar_parts = parse_url($avatar);
2000 $parts = array_merge($base_parts, $avatar_parts);
2002 // And put them together again
2003 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
2004 $host = isset($parts['host']) ? $parts['host'] : '';
2005 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
2006 $path = isset($parts['path']) ? $parts['path'] : '';
2007 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
2008 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
2010 $fixed = $scheme.$host.$port.$path.$query.$fragment;
2012 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);