3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Network;
26 use Friendica\Core\Cache\Duration;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\System;
30 use Friendica\Database\DBA;
32 use Friendica\Model\Contact;
33 use Friendica\Model\GServer;
34 use Friendica\Model\Profile;
35 use Friendica\Protocol\ActivityNamespace;
36 use Friendica\Protocol\ActivityPub;
37 use Friendica\Protocol\Email;
38 use Friendica\Protocol\Feed;
39 use Friendica\Util\Crypto;
40 use Friendica\Util\Network;
41 use Friendica\Util\Strings;
42 use Friendica\Util\XML;
45 * This class contain functions for probing URL
49 private static $baseurl;
50 private static $istimeout;
53 * Remove stuff from an URI that doesn't belong there
56 * @return string Cleaned URI
58 public static function cleanURI(string $URI)
60 // At first remove leading and trailing junk
61 $URI = trim($URI, "@#?:/ \t\n\r\0\x0B");
63 $parts = parse_url($URI);
65 if (empty($parts['scheme'])) {
69 // Remove the URL fragment, since these shouldn't be part of any profile URL
70 unset($parts['fragment']);
72 $URI = Network::unparseURL($parts);
78 * Rearrange the array so that it always has the same order
80 * @param array $data Unordered data
82 * @return array Ordered data
84 private static function rearrangeData($data)
86 $fields = ["name", "nick", "guid", "url", "addr", "alias", "photo", "account-type",
87 "community", "keywords", "location", "about", "hide",
88 "batch", "notify", "poll", "request", "confirm", "subscribe", "poco",
89 "following", "followers", "inbox", "outbox", "sharedinbox",
90 "priority", "network", "pubkey", "baseurl", "gsid"];
93 foreach ($fields as $field) {
94 if (isset($data[$field])) {
95 $newdata[$field] = $data[$field];
96 } elseif ($field != "gsid") {
97 $newdata[$field] = "";
99 $newdata[$field] = null;
103 // We don't use the "priority" field anymore and replace it with a dummy.
104 $newdata["priority"] = 0;
110 * Check if the hostname belongs to the own server
112 * @param string $host The hostname that is to be checked
114 * @return bool Does the testes hostname belongs to the own server?
116 private static function ownHost($host)
118 $own_host = DI::baseUrl()->getHostname();
120 $parts = parse_url($host);
122 if (!isset($parts['scheme'])) {
123 $parts = parse_url('http://'.$host);
126 if (!isset($parts['host'])) {
129 return $parts['host'] == $own_host;
133 * Probes for webfinger path via "host-meta"
135 * We have to check if the servers in the future still will offer this.
136 * It seems as if it was dropped from the standard.
138 * @param string $host The host part of an url
140 * @return array with template and type of the webfinger template for JSON or XML
141 * @throws HTTPException\InternalServerErrorException
143 private static function hostMeta($host)
145 // Reset the static variable
148 // Handles the case when the hostname contains the scheme
149 if (!parse_url($host, PHP_URL_SCHEME)) {
150 $ssl_url = "https://" . $host . "/.well-known/host-meta";
151 $url = "http://" . $host . "/.well-known/host-meta";
153 $ssl_url = $host . "/.well-known/host-meta";
157 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
159 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
162 $curlResult = Network::curl($ssl_url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
163 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
164 if ($curlResult->isSuccess()) {
165 $xml = $curlResult->getBody();
166 $xrd = XML::parseString($xml, true);
168 $host_url = 'https://' . $host;
172 } elseif ($curlResult->isTimeout()) {
173 Logger::info('Probing timeout', ['url' => $ssl_url], Logger::DEBUG);
174 self::$istimeout = true;
178 if (!is_object($xrd) && !empty($url)) {
179 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
180 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
181 if ($curlResult->isTimeout()) {
182 Logger::info('Probing timeout', ['url' => $url], Logger::DEBUG);
183 self::$istimeout = true;
185 } elseif ($connection_error && $ssl_connection_error) {
186 self::$istimeout = true;
190 $xml = $curlResult->getBody();
191 $xrd = XML::parseString($xml, true);
192 $host_url = 'http://'.$host;
194 if (!is_object($xrd)) {
195 Logger::log("No xrd object found for ".$host, Logger::DEBUG);
199 $links = XML::elementToArray($xrd);
200 if (!isset($links["xrd"]["link"])) {
201 Logger::log("No xrd data found for ".$host, Logger::DEBUG);
205 $lrdd = ['application/jrd+json' => $host_url . '/.well-known/webfinger?resource={uri}'];
207 foreach ($links["xrd"]["link"] as $value => $link) {
208 if (!empty($link["@attributes"])) {
209 $attributes = $link["@attributes"];
210 } elseif ($value == "@attributes") {
216 if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
217 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
219 $lrdd[$type] = $attributes["template"];
223 self::$baseurl = $host_url;
225 Logger::log("Probing successful for ".$host, Logger::DEBUG);
231 * Perform Webfinger lookup and return DFRN data
233 * Given an email style address, perform webfinger lookup and
234 * return the resulting DFRN profile URL, or if no DFRN profile URL
235 * is located, returns an OStatus subscription template (prefixed
236 * with the string 'stat:' to identify it as on OStatus template).
237 * If this isn't an email style address just return $webbie.
238 * Return an empty string if email-style addresses but webfinger fails,
239 * or if the resultant personal XRD doesn't contain a supported
240 * subscription/friend-request attribute.
242 * amended 7/9/2011 to return an hcard which could save potentially loading
243 * a lengthy content page to scrape dfrn attributes
245 * @param string $webbie Address that should be probed
246 * @param string $hcard_url Link to the hcard - is returned by reference
248 * @return string profile link
249 * @throws HTTPException\InternalServerErrorException
251 public static function webfingerDfrn($webbie, &$hcard_url)
255 $links = self::lrdd($webbie);
256 Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA);
257 if (!empty($links) && is_array($links)) {
258 foreach ($links as $link) {
259 if ($link['@attributes']['rel'] === ActivityNamespace::DFRN) {
260 $profile_link = $link['@attributes']['href'];
262 if (($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) && ($profile_link == "")) {
263 $profile_link = 'stat:'.$link['@attributes']['template'];
265 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
266 $hcard_url = $link['@attributes']['href'];
270 return $profile_link;
274 * Check an URI for LRDD data
276 * @param string $uri Address that should be probed
278 * @return array uri data
279 * @throws HTTPException\InternalServerErrorException
281 public static function lrdd(string $uri)
283 $lrdd = self::hostMeta($uri);
286 if (is_bool($lrdd)) {
291 $parts = @parse_url($uri);
292 if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
296 $host = $parts['scheme'] . '://' . $parts["host"];
297 if (!empty($parts["port"])) {
298 $host .= ':'.$parts["port"];
301 $path_parts = explode("/", trim($parts["path"], "/"));
303 $nick = array_pop($path_parts);
306 $lrdd = self::hostMeta($host);
307 $host .= "/".array_shift($path_parts);
308 } while (!$lrdd && (sizeof($path_parts) > 0));
312 Logger::log("No lrdd data found for ".$uri, Logger::DEBUG);
316 foreach ($lrdd as $type => $template) {
321 $path = str_replace('{uri}', urlencode($uri), $template);
322 $webfinger = self::webfinger($path, $type);
324 if (!$webfinger && (strstr($uri, "@"))) {
325 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
326 $webfinger = self::webfinger($path, $type);
329 // Special treatment for Mastodon
330 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
331 // But the webfinger for this format fails.
332 if (!$webfinger && !empty($nick)) {
333 // Mastodon uses a "@" as prefix for usernames in their url format
334 $nick = ltrim($nick, '@');
336 $addr = $nick."@".$host;
338 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
339 $webfinger = self::webfinger($path, $type);
343 if (!is_array($webfinger["links"])) {
344 Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
350 foreach ($webfinger["links"] as $link) {
351 $data[] = ["@attributes" => $link];
354 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
355 foreach ($webfinger["aliases"] as $alias) {
356 $data[] = ["@attributes" =>
366 * Fetch information (protocol endpoints and user information) about a given uri
368 * @param string $uri Address that should be probed
369 * @param string $network Test for this specific network
370 * @param integer $uid User ID for the probe (only used for mails)
371 * @param boolean $cache Use cached values?
373 * @return array uri data
374 * @throws HTTPException\InternalServerErrorException
375 * @throws \ImagickException
377 public static function uri($uri, $network = '', $uid = -1, $cache = true)
380 $result = DI::cache()->get('Probe::uri:' . $network . ':' . $uri);
381 if (!is_null($result)) {
390 self::$istimeout = false;
392 $data = self::detect($uri, $network, $uid);
394 // When the previous detection process had got a time out
395 // we could falsely detect a Friendica profile as AP profile.
396 if (!self::$istimeout) {
397 $ap_profile = ActivityPub::probeProfile($uri);
399 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
400 $subscribe = $data['subscribe'];
402 $data['subscribe'] = $subscribe;
403 } elseif (!empty($ap_profile)) {
404 $ap_profile['batch'] = '';
405 $data = array_merge($ap_profile, $data);
408 Logger::notice('Time out detected. AP will not be probed.', ['uri' => $uri]);
411 if (!isset($data['url'])) {
415 if (empty($data['photo'])) {
416 $data['photo'] = DI::baseUrl() . '/images/person-300.jpg';
419 if (empty($data['name'])) {
420 if (!empty($data['nick'])) {
421 $data['name'] = $data['nick'];
424 if (empty($data['name'])) {
425 $data['name'] = $data['url'];
429 if (empty($data['nick'])) {
430 $data['nick'] = strtolower($data['name']);
432 if (strpos($data['nick'], ' ')) {
433 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
437 if (!empty(self::$baseurl)) {
438 $data['baseurl'] = self::$baseurl;
441 if (!empty($data['baseurl']) && empty($data['gsid'])) {
442 $data['gsid'] = GServer::getID($data['baseurl']);
445 if (empty($data['network'])) {
446 $data['network'] = Protocol::PHANTOM;
449 // Ensure that local connections always are DFRN
450 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
451 $data['network'] = Protocol::DFRN;
454 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
455 $data['hide'] = self::getHideStatus($data['url']);
458 $data = self::rearrangeData($data);
460 // Only store into the cache if the value seems to be valid
461 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
462 DI::cache()->set('Probe::uri:' . $network . ':' . $uri, $data, Duration::DAY);
470 * Fetches the "hide" status from the profile
472 * @param string $url URL of the profile
474 * @return boolean "hide" status
476 private static function getHideStatus($url)
478 $curlResult = Network::curl($url);
479 if (!$curlResult->isSuccess()) {
483 // If the file is too large then exit
484 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
488 // If it isn't a HTML file then exit
489 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
493 $body = $curlResult->getBody();
495 $doc = new DOMDocument();
496 @$doc->loadHTML($body);
498 $xpath = new DOMXPath($doc);
500 $list = $xpath->query('//meta[@name]');
501 foreach ($list as $node) {
503 if ($node->attributes->length) {
504 foreach ($node->attributes as $attribute) {
505 $meta_tag[$attribute->name] = $attribute->value;
509 if (empty($meta_tag['content'])) {
513 $content = strtolower(trim($meta_tag['content']));
515 switch (strtolower(trim($meta_tag['name']))) {
516 case 'dfrn-global-visibility':
517 if ($content == 'false') {
522 if (strpos($content, 'noindex') !== false) {
533 * Checks if a profile url should be OStatus but only provides partial information
535 * @param array $webfinger Webfinger data
536 * @param string $lrdd Path template for webfinger request
537 * @param string $type type
539 * @return array fixed webfinger data
540 * @throws HTTPException\InternalServerErrorException
542 private static function fixOStatus($webfinger, $lrdd, $type)
544 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
551 foreach ($webfinger['links'] as $link) {
552 if ($link['rel'] == ActivityNamespace::OSTATUSSUB) {
555 if ($link['rel'] == 'magic-public-key') {
560 if (!$is_ostatus || $has_key) {
564 $url = Network::switchScheme($webfinger['subject']);
565 $path = str_replace('{uri}', urlencode($url), $lrdd);
566 $webfinger2 = self::webfinger($path, $type);
568 // Is the new webfinger detectable as OStatus?
569 if (self::ostatus($webfinger2, true)) {
570 $webfinger = $webfinger2;
577 * Fetch the "subscribe" and add it to the result
579 * @param array $result
580 * @param array $webfinger
581 * @return array result
583 private static function getSubscribeLink(array $result, array $webfinger)
585 if (empty($webfinger['links'])) {
589 foreach ($webfinger['links'] as $link) {
590 if ($link['rel'] === ActivityNamespace::OSTATUSSUB) {
591 $result['subscribe'] = $link['template'];
599 * Fetch information (protocol endpoints and user information) about a given uri
601 * This function is only called by the "uri" function that adds caching and rearranging of data.
603 * @param string $uri Address that should be probed
604 * @param string $network Test for this specific network
605 * @param integer $uid User ID for the probe (only used for mails)
607 * @return array uri data
608 * @throws HTTPException\InternalServerErrorException
610 private static function detect($uri, $network, $uid)
612 $parts = parse_url($uri);
614 if (!empty($parts["scheme"]) && !empty($parts["host"])) {
615 $host = $parts["host"];
616 if (!empty($parts["port"])) {
617 $host .= ':'.$parts["port"];
620 if ($host == 'twitter.com') {
621 return self::twitter($uri);
623 $lrdd = self::hostMeta($host);
625 if (is_bool($lrdd)) {
629 $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
631 while (!$lrdd && (sizeof($path_parts) > 1)) {
632 $host .= "/".array_shift($path_parts);
633 $lrdd = self::hostMeta($host);
636 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
637 return self::feed($uri);
639 $nick = array_pop($path_parts);
641 // Mastodon uses a "@" as prefix for usernames in their url format
642 $nick = ltrim($nick, '@');
644 $addr = $nick."@".$host;
645 } elseif (strstr($uri, '@')) {
646 // If the URI starts with "mailto:" then jump directly to the mail detection
647 if (strpos($uri, 'mailto:') !== false) {
648 $uri = str_replace('mailto:', '', $uri);
649 return self::mail($uri, $uid);
652 if ($network == Protocol::MAIL) {
653 return self::mail($uri, $uid);
655 // Remove "acct:" from the URI
656 $uri = str_replace('acct:', '', $uri);
658 $host = substr($uri, strpos($uri, '@') + 1);
659 $nick = substr($uri, 0, strpos($uri, '@'));
661 if (strpos($uri, '@twitter.com')) {
662 return self::twitter($uri);
664 $lrdd = self::hostMeta($host);
666 if (is_bool($lrdd)) {
671 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
672 return self::mail($uri, $uid);
676 Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
682 /// @todo Do we need the prefix "acct:" or "acct://"?
684 foreach ($lrdd as $type => $template) {
689 // At first try it with the given uri
690 $path = str_replace('{uri}', urlencode($uri), $template);
691 $webfinger = self::webfinger($path, $type);
693 // Fix possible problems with GNU Social probing to wrong scheme
694 $webfinger = self::fixOStatus($webfinger, $template, $type);
696 // We cannot be sure that the detected address was correct, so we don't use the values
697 if ($webfinger && ($uri != $addr)) {
702 // Try webfinger with the address (user@domain.tld)
704 $path = str_replace('{uri}', urlencode($addr), $template);
705 $webfinger = self::webfinger($path, $type);
708 // Mastodon needs to have it with "acct:"
710 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
711 $webfinger = self::webfinger($path, $type);
716 return self::feed($uri);
721 Logger::info("Probing", ['uri' => $uri]);
723 if (in_array($network, ["", Protocol::DFRN])) {
724 $result = self::dfrn($webfinger);
726 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
727 $result = self::diaspora($webfinger);
729 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
730 $result = self::ostatus($webfinger);
732 if (in_array($network, ['', Protocol::ZOT])) {
733 $result = self::zot($webfinger, $result);
735 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
736 $result = self::pumpio($webfinger, $addr);
738 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
739 $result = self::feed($uri);
741 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
742 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
743 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
744 $result["nick"] = $nick;
747 if (empty($result["addr"]) && ($addr != "")) {
748 $result["addr"] = $addr;
752 $result = self::getSubscribeLink($result, $webfinger);
754 if (empty($result["network"])) {
755 $result["network"] = Protocol::PHANTOM;
758 if (empty($result["url"])) {
759 $result["url"] = $uri;
762 Logger::log($uri." is ".$result["network"], Logger::DEBUG);
764 if (empty($result["baseurl"]) && ($result["network"] != Protocol::PHANTOM)) {
765 $pos = strpos($result["url"], $host);
767 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
775 * Check for Zot contact
777 * @param array $webfinger Webfinger data
778 * @param array $data previously probed data
780 * @return array Zot data
781 * @throws HTTPException\InternalServerErrorException
783 private static function zot($webfinger, $data)
785 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
786 foreach ($webfinger["aliases"] as $alias) {
787 if (substr($alias, 0, 5) == 'acct:') {
788 $data["addr"] = substr($alias, 5);
793 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
794 $data["addr"] = substr($webfinger["subject"], 5);
798 foreach ($webfinger['links'] as $link) {
799 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
800 $zot_url = $link['href'];
804 if (empty($zot_url) && !empty($data['addr']) && !empty(self::$baseurl)) {
805 $condition = ['nurl' => Strings::normaliseLink(self::$baseurl), 'platform' => ['hubzilla']];
806 if (!DBA::exists('gserver', $condition)) {
809 $zot_url = self::$baseurl . '/.well-known/zot-info?address=' . $data['addr'];
812 if (empty($zot_url)) {
816 $data = self::pollZot($zot_url, $data);
818 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
819 foreach ($webfinger['aliases'] as $alias) {
820 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
821 $data['alias'] = $alias;
829 public static function pollZot($url, $data)
831 $curlResult = Network::curl($url);
832 if ($curlResult->isTimeout()) {
835 $content = $curlResult->getBody();
840 $json = json_decode($content, true);
841 if (!is_array($json)) {
845 if (empty($data['network'])) {
846 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
847 $data['network'] = Protocol::ZOT;
848 } elseif (!isset($json['protocols'])) {
849 $data['network'] = Protocol::ZOT;
853 if (!empty($json['guid']) && empty($data['guid'])) {
854 $data['guid'] = $json['guid'];
856 if (!empty($json['key']) && empty($data['pubkey'])) {
857 $data['pubkey'] = $json['key'];
859 if (!empty($json['name'])) {
860 $data['name'] = $json['name'];
862 if (!empty($json['photo'])) {
863 $data['photo'] = $json['photo'];
864 if (!empty($json['photo_updated'])) {
865 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
868 if (!empty($json['address'])) {
869 $data['addr'] = $json['address'];
871 if (!empty($json['url'])) {
872 $data['url'] = $json['url'];
874 if (!empty($json['connections_url'])) {
875 $data['poco'] = $json['connections_url'];
877 if (isset($json['searchable'])) {
878 $data['hide'] = !$json['searchable'];
880 if (!empty($json['public_forum'])) {
881 $data['community'] = $json['public_forum'];
882 $data['account-type'] = Contact::PAGE_COMMUNITY;
885 if (!empty($json['profile'])) {
886 $profile = $json['profile'];
887 if (!empty($profile['description'])) {
888 $data['about'] = $profile['description'];
890 if (!empty($profile['keywords'])) {
891 $keywords = implode(', ', $profile['keywords']);
892 if (!empty($keywords)) {
893 $data['keywords'] = $keywords;
898 if (!empty($profile['region'])) {
899 $loc['region'] = $profile['region'];
901 if (!empty($profile['country'])) {
902 $loc['country-name'] = $profile['country'];
904 $location = Profile::formatLocation($loc);
905 if (!empty($location)) {
906 $data['location'] = $location;
914 * Perform a webfinger request.
916 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
918 * @param string $url Address that should be probed
919 * @param string $type type
921 * @return array webfinger data
922 * @throws HTTPException\InternalServerErrorException
924 private static function webfinger($url, $type)
926 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
928 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
929 if ($curlResult->isTimeout()) {
930 self::$istimeout = true;
933 $data = $curlResult->getBody();
935 $webfinger = json_decode($data, true);
936 if (is_array($webfinger)) {
937 if (!isset($webfinger["links"])) {
938 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
944 // If it is not JSON, maybe it is XML
945 $xrd = XML::parseString($data, true);
946 if (!is_object($xrd)) {
947 Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
951 $xrd_arr = XML::elementToArray($xrd);
952 if (!isset($xrd_arr["xrd"]["link"])) {
953 Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
959 if (!empty($xrd_arr["xrd"]["subject"])) {
960 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
963 if (!empty($xrd_arr["xrd"]["alias"])) {
964 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
967 $webfinger["links"] = [];
969 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
970 if (!empty($data["@attributes"])) {
971 $attributes = $data["@attributes"];
972 } elseif ($value == "@attributes") {
978 $webfinger["links"][] = $attributes;
984 * Poll the Friendica specific noscrape page.
986 * "noscrape" is a faster alternative to fetch the data from the hcard.
987 * This functionality was originally created for the directory.
989 * @param string $noscrape_url Link to the noscrape page
990 * @param array $data The already fetched data
992 * @return array noscrape data
993 * @throws HTTPException\InternalServerErrorException
995 private static function pollNoscrape($noscrape_url, $data)
997 $curlResult = Network::curl($noscrape_url);
998 if ($curlResult->isTimeout()) {
999 self::$istimeout = true;
1002 $content = $curlResult->getBody();
1004 Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
1008 $json = json_decode($content, true);
1009 if (!is_array($json)) {
1010 Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
1014 if (!empty($json["fn"])) {
1015 $data["name"] = $json["fn"];
1018 if (!empty($json["addr"])) {
1019 $data["addr"] = $json["addr"];
1022 if (!empty($json["nick"])) {
1023 $data["nick"] = $json["nick"];
1026 if (!empty($json["guid"])) {
1027 $data["guid"] = $json["guid"];
1030 if (!empty($json["comm"])) {
1031 $data["community"] = $json["comm"];
1034 if (!empty($json["tags"])) {
1035 $keywords = implode(", ", $json["tags"]);
1036 if ($keywords != "") {
1037 $data["keywords"] = $keywords;
1041 $location = Profile::formatLocation($json);
1043 $data["location"] = $location;
1046 if (!empty($json["about"])) {
1047 $data["about"] = $json["about"];
1050 if (!empty($json["key"])) {
1051 $data["pubkey"] = $json["key"];
1054 if (!empty($json["photo"])) {
1055 $data["photo"] = $json["photo"];
1058 if (!empty($json["dfrn-request"])) {
1059 $data["request"] = $json["dfrn-request"];
1062 if (!empty($json["dfrn-confirm"])) {
1063 $data["confirm"] = $json["dfrn-confirm"];
1066 if (!empty($json["dfrn-notify"])) {
1067 $data["notify"] = $json["dfrn-notify"];
1070 if (!empty($json["dfrn-poll"])) {
1071 $data["poll"] = $json["dfrn-poll"];
1074 if (isset($json["hide"])) {
1075 $data["hide"] = (bool)$json["hide"];
1077 $data["hide"] = false;
1084 * Check for valid DFRN data
1086 * @param array $data DFRN data
1088 * @return int Number of errors
1090 public static function validDfrn($data)
1093 if (!isset($data['key'])) {
1096 if (!isset($data['dfrn-request'])) {
1099 if (!isset($data['dfrn-confirm'])) {
1102 if (!isset($data['dfrn-notify'])) {
1105 if (!isset($data['dfrn-poll'])) {
1112 * Fetch data from a DFRN profile page and via "noscrape"
1114 * @param string $profile_link Link to the profile page
1116 * @return array profile data
1117 * @throws HTTPException\InternalServerErrorException
1118 * @throws \ImagickException
1120 public static function profile($profile_link)
1124 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
1126 // Fetch data via noscrape - this is faster
1127 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1128 $data = self::pollNoscrape($noscrape_url, $data);
1130 if (!isset($data["notify"])
1131 || !isset($data["confirm"])
1132 || !isset($data["request"])
1133 || !isset($data["poll"])
1134 || !isset($data["name"])
1135 || !isset($data["photo"])
1137 $data = self::pollHcard($profile_link, $data, true);
1142 if (empty($data["addr"]) || empty($data["nick"])) {
1143 $probe_data = self::uri($profile_link);
1144 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1145 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1148 $prof_data["addr"] = $data["addr"];
1149 $prof_data["nick"] = $data["nick"];
1150 $prof_data["dfrn-request"] = $data['request'] ?? null;
1151 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1152 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1153 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1154 $prof_data["photo"] = $data['photo'] ?? null;
1155 $prof_data["fn"] = $data['name'] ?? null;
1156 $prof_data["key"] = $data['pubkey'] ?? null;
1158 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
1164 * Check for DFRN contact
1166 * @param array $webfinger Webfinger data
1168 * @return array DFRN data
1169 * @throws HTTPException\InternalServerErrorException
1171 private static function dfrn($webfinger)
1175 // The array is reversed to take into account the order of preference for same-rel links
1176 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1177 foreach (array_reverse($webfinger["links"]) as $link) {
1178 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1179 $data["network"] = Protocol::DFRN;
1180 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1181 $data["poll"] = $link["href"];
1182 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1183 $data["url"] = $link["href"];
1184 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1185 $hcard_url = $link["href"];
1186 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1187 $data["poco"] = $link["href"];
1188 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1189 $data["photo"] = $link["href"];
1190 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1191 $data["baseurl"] = trim($link["href"], '/');
1192 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1193 $data["guid"] = $link["href"];
1194 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1195 $data["pubkey"] = base64_decode($link["href"]);
1197 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1198 if (strstr($data["pubkey"], 'RSA ')) {
1199 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1204 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1205 foreach ($webfinger["aliases"] as $alias) {
1206 if (empty($data["url"]) && !strstr($alias, "@")) {
1207 $data["url"] = $alias;
1208 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1209 $data["alias"] = $alias;
1210 } elseif (substr($alias, 0, 5) == 'acct:') {
1211 $data["addr"] = substr($alias, 5);
1216 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1217 $data["addr"] = substr($webfinger["subject"], 5);
1220 if (!isset($data["network"]) || ($hcard_url == "")) {
1224 // Fetch data via noscrape - this is faster
1225 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1226 $data = self::pollNoscrape($noscrape_url, $data);
1228 if (isset($data["notify"])
1229 && isset($data["confirm"])
1230 && isset($data["request"])
1231 && isset($data["poll"])
1232 && isset($data["name"])
1233 && isset($data["photo"])
1238 $data = self::pollHcard($hcard_url, $data, true);
1244 * Poll the hcard page (Diaspora and Friendica specific)
1246 * @param string $hcard_url Link to the hcard page
1247 * @param array $data The already fetched data
1248 * @param boolean $dfrn Poll DFRN specific data
1250 * @return array hcard data
1251 * @throws HTTPException\InternalServerErrorException
1253 private static function pollHcard($hcard_url, $data, $dfrn = false)
1255 $curlResult = Network::curl($hcard_url);
1256 if ($curlResult->isTimeout()) {
1257 self::$istimeout = true;
1260 $content = $curlResult->getBody();
1265 $doc = new DOMDocument();
1266 if (!@$doc->loadHTML($content)) {
1270 $xpath = new DomXPath($doc);
1272 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1273 if (!is_object($vcards)) {
1277 if (!isset($data["baseurl"])) {
1278 $data["baseurl"] = "";
1281 if ($vcards->length > 0) {
1282 $vcard = $vcards->item(0);
1284 // We have to discard the guid from the hcard in favour of the guid from lrdd
1285 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1286 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1287 if (($search->length > 0) && empty($data["guid"])) {
1288 $data["guid"] = $search->item(0)->nodeValue;
1291 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1292 if ($search->length > 0) {
1293 $data["nick"] = $search->item(0)->nodeValue;
1296 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1297 if ($search->length > 0) {
1298 $data["name"] = $search->item(0)->nodeValue;
1301 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1302 if ($search->length > 0) {
1303 $data["searchable"] = $search->item(0)->nodeValue;
1306 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1307 if ($search->length > 0) {
1308 $data["pubkey"] = $search->item(0)->nodeValue;
1309 if (strstr($data["pubkey"], 'RSA ')) {
1310 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1314 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1315 if ($search->length > 0) {
1316 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1321 if (!empty($vcard)) {
1322 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1323 foreach ($photos as $photo) {
1325 foreach ($photo->attributes as $attribute) {
1326 $attr[$attribute->name] = trim($attribute->value);
1329 if (isset($attr["src"]) && isset($attr["width"])) {
1330 $avatar[$attr["width"]] = $attr["src"];
1333 // We don't have a width. So we just take everything that we got.
1334 // This is a Hubzilla workaround which doesn't send a width.
1335 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1336 $avatar[] = $attr["src"];
1341 if (sizeof($avatar)) {
1343 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1347 // Poll DFRN specific data
1348 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1349 if ($search->length > 0) {
1350 foreach ($search as $link) {
1351 //$data["request"] = $search->item(0)->nodeValue;
1353 foreach ($link->attributes as $attribute) {
1354 $attr[$attribute->name] = trim($attribute->value);
1357 $data[substr($attr["rel"], 5)] = $attr["href"];
1361 // Older Friendica versions had used the "uid" field differently than newer versions
1362 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1363 unset($data["guid"]);
1372 * Check for Diaspora contact
1374 * @param array $webfinger Webfinger data
1376 * @return array Diaspora data
1377 * @throws HTTPException\InternalServerErrorException
1379 private static function diaspora($webfinger)
1384 // The array is reversed to take into account the order of preference for same-rel links
1385 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1386 foreach (array_reverse($webfinger["links"]) as $link) {
1387 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1388 $hcard_url = $link["href"];
1389 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1390 $data["baseurl"] = trim($link["href"], '/');
1391 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1392 $data["guid"] = $link["href"];
1393 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1394 $data["url"] = $link["href"];
1395 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1396 $data["poll"] = $link["href"];
1397 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1398 $data["poco"] = $link["href"];
1399 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1400 $data["notify"] = $link["href"];
1401 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1402 $data["pubkey"] = base64_decode($link["href"]);
1404 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1405 if (strstr($data["pubkey"], 'RSA ')) {
1406 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1411 if (empty($data["url"]) || empty($hcard_url)) {
1415 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1416 foreach ($webfinger["aliases"] as $alias) {
1417 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1418 $data["alias"] = $alias;
1419 } elseif (substr($alias, 0, 5) == 'acct:') {
1420 $data["addr"] = substr($alias, 5);
1425 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1426 $data["addr"] = substr($webfinger["subject"], 5);
1429 // Fetch further information from the hcard
1430 $data = self::pollHcard($hcard_url, $data);
1436 if (!empty($data["url"])
1437 && !empty($data["guid"])
1438 && !empty($data["baseurl"])
1439 && !empty($data["pubkey"])
1440 && !empty($hcard_url)
1442 $data["network"] = Protocol::DIASPORA;
1444 // The Diaspora handle must always be lowercase
1445 if (!empty($data["addr"])) {
1446 $data["addr"] = strtolower($data["addr"]);
1449 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1450 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1451 $data["batch"] = $data["baseurl"] . "/receive/public";
1460 * Check for OStatus contact
1462 * @param array $webfinger Webfinger data
1463 * @param bool $short Short detection mode
1465 * @return array|bool OStatus data or "false" on error or "true" on short mode
1466 * @throws HTTPException\InternalServerErrorException
1468 private static function ostatus($webfinger, $short = false)
1472 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1473 foreach ($webfinger["aliases"] as $alias) {
1474 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1475 $data["addr"] = str_replace('acct:', '', $alias);
1480 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1481 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1483 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1486 if (is_array($webfinger["links"])) {
1487 // The array is reversed to take into account the order of preference for same-rel links
1488 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1489 foreach (array_reverse($webfinger["links"]) as $link) {
1490 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1491 && (($link["type"] ?? "") == "text/html")
1492 && ($link["href"] != "")
1494 $data["url"] = $link["href"];
1495 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1496 $data["notify"] = $link["href"];
1497 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1498 $data["poll"] = $link["href"];
1499 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1500 $pubkey = $link["href"];
1502 if (substr($pubkey, 0, 5) === 'data:') {
1503 if (strstr($pubkey, ',')) {
1504 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1506 $pubkey = substr($pubkey, 5);
1508 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1509 $curlResult = Network::curl($pubkey);
1510 if ($curlResult->isTimeout()) {
1511 self::$istimeout = true;
1514 $pubkey = $curlResult->getBody();
1517 $key = explode(".", $pubkey);
1519 if (sizeof($key) >= 3) {
1520 $m = Strings::base64UrlDecode($key[1]);
1521 $e = Strings::base64UrlDecode($key[2]);
1522 $data["pubkey"] = Crypto::meToPem($m, $e);
1528 if (isset($data["notify"]) && isset($data["pubkey"])
1529 && isset($data["poll"])
1530 && isset($data["url"])
1532 $data["network"] = Protocol::OSTATUS;
1541 // Fetch all additional data from the feed
1542 $curlResult = Network::curl($data["poll"]);
1543 if ($curlResult->isTimeout()) {
1544 self::$istimeout = true;
1547 $feed = $curlResult->getBody();
1548 $feed_data = Feed::import($feed);
1553 if (!empty($feed_data["header"]["author-name"])) {
1554 $data["name"] = $feed_data["header"]["author-name"];
1556 if (!empty($feed_data["header"]["author-nick"])) {
1557 $data["nick"] = $feed_data["header"]["author-nick"];
1559 if (!empty($feed_data["header"]["author-avatar"])) {
1560 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1562 if (!empty($feed_data["header"]["author-id"])) {
1563 $data["alias"] = $feed_data["header"]["author-id"];
1565 if (!empty($feed_data["header"]["author-location"])) {
1566 $data["location"] = $feed_data["header"]["author-location"];
1568 if (!empty($feed_data["header"]["author-about"])) {
1569 $data["about"] = $feed_data["header"]["author-about"];
1571 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1572 // So we take the value that we just fetched, although the other one worked as well
1573 if (!empty($feed_data["header"]["author-link"])) {
1574 $data["url"] = $feed_data["header"]["author-link"];
1577 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1578 $data['url'] = $data["alias"];
1579 $data["alias"] = '';
1582 /// @todo Fetch location and "about" from the feed as well
1587 * Fetch data from a pump.io profile page
1589 * @param string $profile_link Link to the profile page
1591 * @return array profile data
1593 private static function pumpioProfileData($profile_link)
1595 $curlResult = Network::curl($profile_link);
1596 if (!$curlResult->isSuccess()) {
1600 $doc = new DOMDocument();
1601 if (!@$doc->loadHTML($curlResult->getBody())) {
1605 $xpath = new DomXPath($doc);
1609 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1611 if ($data["name"] == '') {
1612 // This is ugly - but pump.io doesn't seem to know a better way for it
1613 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1614 $pos = strpos($data["name"], chr(10));
1616 $data["name"] = trim(substr($data["name"], 0, $pos));
1620 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1622 if ($data["location"] == '') {
1623 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1626 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1628 if ($data["about"] == '') {
1629 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1632 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1634 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1637 foreach ($avatar->attributes as $attribute) {
1638 if ($attribute->name == "src") {
1639 $data["photo"] = trim($attribute->value);
1648 * Check for pump.io contact
1650 * @param array $webfinger Webfinger data
1651 * @param string $addr
1652 * @return array pump.io data
1654 private static function pumpio($webfinger, $addr)
1657 // The array is reversed to take into account the order of preference for same-rel links
1658 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1659 foreach (array_reverse($webfinger["links"]) as $link) {
1660 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1661 && (($link["type"] ?? "") == "text/html")
1662 && ($link["href"] != "")
1664 $data["url"] = $link["href"];
1665 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1666 $data["notify"] = $link["href"];
1667 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1668 $data["poll"] = $link["href"];
1669 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1670 $data["dialback"] = $link["href"];
1673 if (isset($data["poll"]) && isset($data["notify"])
1674 && isset($data["dialback"])
1675 && isset($data["url"])
1677 // by now we use these fields only for the network type detection
1678 // So we unset all data that isn't used at the moment
1679 unset($data["dialback"]);
1681 $data["network"] = Protocol::PUMPIO;
1686 $profile_data = self::pumpioProfileData($data["url"]);
1688 if (!$profile_data) {
1692 $data = array_merge($data, $profile_data);
1694 if (($addr != '') && ($data['name'] != '')) {
1695 $name = trim(str_replace($addr, '', $data['name']));
1697 $data['name'] = $name;
1705 * Check for twitter contact
1707 * @param string $uri
1709 * @return array twitter data
1711 private static function twitter($uri)
1713 if (preg_match('=(.*)@twitter.com=i', $uri, $matches)) {
1714 $nick = $matches[1];
1715 } elseif (preg_match('=https?://twitter.com/(.*)=i', $uri, $matches)) {
1716 $nick = $matches[1];
1722 $data['url'] = 'https://twitter.com/' . $nick;
1723 $data['addr'] = $nick . '@twitter.com';
1724 $data['nick'] = $data['name'] = $nick;
1725 $data['network'] = Protocol::TWITTER;
1726 $data['baseurl'] = 'https://twitter.com';
1728 $curlResult = Network::curl($data['url'], false);
1729 if (!$curlResult->isSuccess()) {
1733 $body = $curlResult->getBody();
1734 $doc = new DOMDocument();
1735 @$doc->loadHTML($body);
1736 $xpath = new DOMXPath($doc);
1738 $list = $xpath->query('//img[@class]');
1739 foreach ($list as $node) {
1741 if ($node->attributes->length) {
1742 foreach ($node->attributes as $attribute) {
1743 $img_attr[$attribute->name] = $attribute->value;
1747 if (empty($img_attr['class'])) {
1751 if (strpos($img_attr['class'], 'ProfileAvatar-image') !== false) {
1752 if (!empty($img_attr['src'])) {
1753 $data['photo'] = $img_attr['src'];
1755 if (!empty($img_attr['alt'])) {
1756 $data['name'] = $img_attr['alt'];
1765 * Checks HTML page for RSS feed link
1767 * @param string $url Page link
1768 * @param string $body Page body string
1769 * @return string|false Feed link or false if body was invalid HTML document
1771 public static function getFeedLink(string $url, string $body)
1773 $doc = new DOMDocument();
1774 if (!@$doc->loadHTML($body)) {
1778 $xpath = new DOMXPath($doc);
1780 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1782 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1788 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1790 * Loosely based on RFC 1808
1792 * @see https://tools.ietf.org/html/rfc1808
1794 * @param string $href The potential relative href found in the HTML document
1795 * @param string $base The HTML document URL
1796 * @param DOMXPath $xpath The HTML document XPath
1799 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath)
1801 if (filter_var($href, FILTER_VALIDATE_URL)) {
1805 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1807 $baseParts = parse_url($base);
1809 // Naked domain case (scheme://basehost)
1810 $path = $baseParts['path'] ?? '/';
1812 // Remove the filename part of the path if it exists (/base/path/file)
1813 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1815 $hrefParts = parse_url($href);
1817 // Root path case (/path) including relative scheme case (//host/path)
1818 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1819 $path = $hrefParts['path'];
1821 $path = $path . '/' . $hrefParts['path'];
1823 // Resolve arbitrary relative path
1824 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1825 $parts = array_filter(explode('/', $path), 'strlen');
1826 $absolutes = array();
1827 foreach ($parts as $part) {
1828 if ('.' == $part) continue;
1829 if ('..' == $part) {
1830 array_pop($absolutes);
1832 $absolutes[] = $part;
1836 $path = '/' . implode('/', $absolutes);
1839 // Relative scheme case (//host/path)
1840 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1841 $baseParts['path'] = $path;
1842 unset($baseParts['query']);
1843 unset($baseParts['fragment']);
1845 return Network::unparseURL($baseParts);
1849 * Check for feed contact
1851 * @param string $url Profile link
1852 * @param boolean $probe Do a probe if the page contains a feed link
1854 * @return array feed data
1855 * @throws HTTPException\InternalServerErrorException
1857 private static function feed($url, $probe = true)
1859 $curlResult = Network::curl($url);
1860 if ($curlResult->isTimeout()) {
1861 self::$istimeout = true;
1864 $feed = $curlResult->getBody();
1865 $feed_data = Feed::import($feed);
1872 $feed_url = self::getFeedLink($url, $feed);
1878 return self::feed($feed_url, false);
1881 if (!empty($feed_data["header"]["author-name"])) {
1882 $data["name"] = $feed_data["header"]["author-name"];
1885 if (!empty($feed_data["header"]["author-nick"])) {
1886 $data["nick"] = $feed_data["header"]["author-nick"];
1889 if (!empty($feed_data["header"]["author-avatar"])) {
1890 $data["photo"] = $feed_data["header"]["author-avatar"];
1893 if (!empty($feed_data["header"]["author-id"])) {
1894 $data["alias"] = $feed_data["header"]["author-id"];
1897 $data["url"] = $url;
1898 $data["poll"] = $url;
1900 if (!empty($feed_data["header"]["author-link"])) {
1901 $data["baseurl"] = $feed_data["header"]["author-link"];
1903 $data["baseurl"] = $data["url"];
1906 $data["network"] = Protocol::FEED;
1912 * Check for mail contact
1914 * @param string $uri Profile link
1915 * @param integer $uid User ID
1917 * @return array mail data
1918 * @throws \Exception
1920 private static function mail($uri, $uid)
1922 if (!Network::isEmailDomainValid($uri)) {
1930 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1932 $condition = ["`uid` = ? AND `server` != ''", $uid];
1933 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1934 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1936 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1940 $mailbox = Email::constructMailboxName($mailacct);
1942 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1943 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1948 $msgs = Email::poll($mbox, $uri);
1949 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1951 if (!count($msgs)) {
1955 $phost = substr($uri, strpos($uri, '@') + 1);
1958 $data["addr"] = $uri;
1959 $data["network"] = Protocol::MAIL;
1960 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1961 $data["nick"] = $data["name"];
1962 $data["photo"] = Network::lookupAvatarByEmail($uri);
1963 $data["url"] = 'mailto:'.$uri;
1964 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1965 $data["poll"] = 'email ' . Strings::getRandomHex();
1967 $x = Email::messageMeta($mbox, $msgs[0]);
1968 if (stristr($x[0]->from, $uri)) {
1969 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1970 } elseif (stristr($x[0]->to, $uri)) {
1971 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1974 foreach ($adr as $feadr) {
1975 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1976 &&(strcasecmp($feadr->host, $phost) == 0)
1977 && (strlen($feadr->personal))
1979 $personal = imap_mime_header_decode($feadr->personal);
1981 foreach ($personal as $perspart) {
1982 if ($perspart->charset != "default") {
1983 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1985 $data["name"] .= $perspart->text;
1989 $data["name"] = Strings::escapeTags($data["name"]);
1993 if (!empty($mbox)) {
2000 * Mix two paths together to possibly fix missing parts
2002 * @param string $avatar Path to the avatar
2003 * @param string $base Another path that is hopefully complete
2005 * @return string fixed avatar path
2006 * @throws \Exception
2008 public static function fixAvatar($avatar, $base)
2010 $base_parts = parse_url($base);
2012 // Remove all parts that could create a problem
2013 unset($base_parts['path']);
2014 unset($base_parts['query']);
2015 unset($base_parts['fragment']);
2017 $avatar_parts = parse_url($avatar);
2020 $parts = array_merge($base_parts, $avatar_parts);
2022 // And put them together again
2023 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
2024 $host = isset($parts['host']) ? $parts['host'] : '';
2025 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
2026 $path = isset($parts['path']) ? $parts['path'] : '';
2027 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
2028 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
2030 $fixed = $scheme.$host.$port.$path.$query.$fragment;
2032 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);