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 if ($network != Protocol::ACTIVITYPUB) {
393 $data = self::detect($uri, $network, $uid);
398 // When the previous detection process had got a time out
399 // we could falsely detect a Friendica profile as AP profile.
400 if (!self::$istimeout) {
401 $ap_profile = ActivityPub::probeProfile($uri);
403 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
404 $subscribe = $data['subscribe'];
406 $data['subscribe'] = $subscribe;
407 } elseif (!empty($ap_profile)) {
408 $ap_profile['batch'] = '';
409 $data = array_merge($ap_profile, $data);
412 Logger::notice('Time out detected. AP will not be probed.', ['uri' => $uri]);
415 if (!isset($data['url'])) {
419 if (empty($data['photo'])) {
420 $data['photo'] = DI::baseUrl() . '/images/person-300.jpg';
423 if (empty($data['name'])) {
424 if (!empty($data['nick'])) {
425 $data['name'] = $data['nick'];
428 if (empty($data['name'])) {
429 $data['name'] = $data['url'];
433 if (empty($data['nick'])) {
434 $data['nick'] = strtolower($data['name']);
436 if (strpos($data['nick'], ' ')) {
437 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
441 if (!empty(self::$baseurl)) {
442 $data['baseurl'] = self::$baseurl;
445 if (!empty($data['baseurl']) && empty($data['gsid'])) {
446 $data['gsid'] = GServer::getID($data['baseurl']);
449 if (empty($data['network'])) {
450 $data['network'] = Protocol::PHANTOM;
453 // Ensure that local connections always are DFRN
454 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
455 $data['network'] = Protocol::DFRN;
458 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
459 $data['hide'] = self::getHideStatus($data['url']);
462 $data = self::rearrangeData($data);
464 // Only store into the cache if the value seems to be valid
465 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
466 DI::cache()->set('Probe::uri:' . $network . ':' . $uri, $data, Duration::DAY);
474 * Fetches the "hide" status from the profile
476 * @param string $url URL of the profile
478 * @return boolean "hide" status
480 private static function getHideStatus($url)
482 $curlResult = Network::curl($url);
483 if (!$curlResult->isSuccess()) {
487 // If the file is too large then exit
488 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
492 // If it isn't a HTML file then exit
493 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
497 $body = $curlResult->getBody();
499 $doc = new DOMDocument();
500 @$doc->loadHTML($body);
502 $xpath = new DOMXPath($doc);
504 $list = $xpath->query('//meta[@name]');
505 foreach ($list as $node) {
507 if ($node->attributes->length) {
508 foreach ($node->attributes as $attribute) {
509 $meta_tag[$attribute->name] = $attribute->value;
513 if (empty($meta_tag['content'])) {
517 $content = strtolower(trim($meta_tag['content']));
519 switch (strtolower(trim($meta_tag['name']))) {
520 case 'dfrn-global-visibility':
521 if ($content == 'false') {
526 if (strpos($content, 'noindex') !== false) {
537 * Checks if a profile url should be OStatus but only provides partial information
539 * @param array $webfinger Webfinger data
540 * @param string $lrdd Path template for webfinger request
541 * @param string $type type
543 * @return array fixed webfinger data
544 * @throws HTTPException\InternalServerErrorException
546 private static function fixOStatus($webfinger, $lrdd, $type)
548 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
555 foreach ($webfinger['links'] as $link) {
556 if ($link['rel'] == ActivityNamespace::OSTATUSSUB) {
559 if ($link['rel'] == 'magic-public-key') {
564 if (!$is_ostatus || $has_key) {
568 $url = Network::switchScheme($webfinger['subject']);
569 $path = str_replace('{uri}', urlencode($url), $lrdd);
570 $webfinger2 = self::webfinger($path, $type);
572 // Is the new webfinger detectable as OStatus?
573 if (self::ostatus($webfinger2, true)) {
574 $webfinger = $webfinger2;
581 * Fetch the "subscribe" and add it to the result
583 * @param array $result
584 * @param array $webfinger
585 * @return array result
587 private static function getSubscribeLink(array $result, array $webfinger)
589 if (empty($webfinger['links'])) {
593 foreach ($webfinger['links'] as $link) {
594 if ($link['rel'] === ActivityNamespace::OSTATUSSUB) {
595 $result['subscribe'] = $link['template'];
603 * Fetch information (protocol endpoints and user information) about a given uri
605 * This function is only called by the "uri" function that adds caching and rearranging of data.
607 * @param string $uri Address that should be probed
608 * @param string $network Test for this specific network
609 * @param integer $uid User ID for the probe (only used for mails)
611 * @return array uri data
612 * @throws HTTPException\InternalServerErrorException
614 private static function detect($uri, $network, $uid)
616 $parts = parse_url($uri);
618 if (!empty($parts["scheme"]) && !empty($parts["host"])) {
619 $host = $parts["host"];
620 if (!empty($parts["port"])) {
621 $host .= ':'.$parts["port"];
624 if ($host == 'twitter.com') {
625 return self::twitter($uri);
627 $lrdd = self::hostMeta($host);
629 if (is_bool($lrdd)) {
633 $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
635 while (!$lrdd && (sizeof($path_parts) > 1)) {
636 $host .= "/".array_shift($path_parts);
637 $lrdd = self::hostMeta($host);
640 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
641 return self::feed($uri);
643 $nick = array_pop($path_parts);
645 // Mastodon uses a "@" as prefix for usernames in their url format
646 $nick = ltrim($nick, '@');
648 $addr = $nick."@".$host;
649 } elseif (strstr($uri, '@')) {
650 // If the URI starts with "mailto:" then jump directly to the mail detection
651 if (strpos($uri, 'mailto:') !== false) {
652 $uri = str_replace('mailto:', '', $uri);
653 return self::mail($uri, $uid);
656 if ($network == Protocol::MAIL) {
657 return self::mail($uri, $uid);
659 // Remove "acct:" from the URI
660 $uri = str_replace('acct:', '', $uri);
662 $host = substr($uri, strpos($uri, '@') + 1);
663 $nick = substr($uri, 0, strpos($uri, '@'));
665 if (strpos($uri, '@twitter.com')) {
666 return self::twitter($uri);
668 $lrdd = self::hostMeta($host);
670 if (is_bool($lrdd)) {
675 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
676 return self::mail($uri, $uid);
680 Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
686 /// @todo Do we need the prefix "acct:" or "acct://"?
688 foreach ($lrdd as $type => $template) {
693 // At first try it with the given uri
694 $path = str_replace('{uri}', urlencode($uri), $template);
695 $webfinger = self::webfinger($path, $type);
697 // Fix possible problems with GNU Social probing to wrong scheme
698 $webfinger = self::fixOStatus($webfinger, $template, $type);
700 // We cannot be sure that the detected address was correct, so we don't use the values
701 if ($webfinger && ($uri != $addr)) {
706 // Try webfinger with the address (user@domain.tld)
708 $path = str_replace('{uri}', urlencode($addr), $template);
709 $webfinger = self::webfinger($path, $type);
712 // Mastodon needs to have it with "acct:"
714 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
715 $webfinger = self::webfinger($path, $type);
720 return self::feed($uri);
725 Logger::info("Probing", ['uri' => $uri]);
727 if (in_array($network, ["", Protocol::DFRN])) {
728 $result = self::dfrn($webfinger);
730 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
731 $result = self::diaspora($webfinger);
733 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
734 $result = self::ostatus($webfinger);
736 if (in_array($network, ['', Protocol::ZOT])) {
737 $result = self::zot($webfinger, $result);
739 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
740 $result = self::pumpio($webfinger, $addr);
742 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
743 $result = self::feed($uri);
745 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
746 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
747 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
748 $result["nick"] = $nick;
751 if (empty($result["addr"]) && ($addr != "")) {
752 $result["addr"] = $addr;
756 $result = self::getSubscribeLink($result, $webfinger);
758 if (empty($result["network"])) {
759 $result["network"] = Protocol::PHANTOM;
762 if (empty($result["url"])) {
763 $result["url"] = $uri;
766 Logger::log($uri." is ".$result["network"], Logger::DEBUG);
768 if (empty($result["baseurl"]) && ($result["network"] != Protocol::PHANTOM)) {
769 $pos = strpos($result["url"], $host);
771 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
778 * Check for Zot contact
780 * @param array $webfinger Webfinger data
781 * @param array $data previously probed data
783 * @return array Zot data
784 * @throws HTTPException\InternalServerErrorException
786 private static function zot($webfinger, $data)
788 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
789 foreach ($webfinger["aliases"] as $alias) {
790 if (substr($alias, 0, 5) == 'acct:') {
791 $data["addr"] = substr($alias, 5);
796 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
797 $data["addr"] = substr($webfinger["subject"], 5);
801 foreach ($webfinger['links'] as $link) {
802 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
803 $zot_url = $link['href'];
807 if (empty($zot_url) && !empty($data['addr']) && !empty(self::$baseurl)) {
808 $condition = ['nurl' => Strings::normaliseLink(self::$baseurl), 'platform' => ['hubzilla']];
809 if (!DBA::exists('gserver', $condition)) {
812 $zot_url = self::$baseurl . '/.well-known/zot-info?address=' . $data['addr'];
815 if (empty($zot_url)) {
819 $data = self::pollZot($zot_url, $data);
821 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
822 foreach ($webfinger['aliases'] as $alias) {
823 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
824 $data['alias'] = $alias;
832 public static function pollZot($url, $data)
834 $curlResult = Network::curl($url);
835 if ($curlResult->isTimeout()) {
838 $content = $curlResult->getBody();
843 $json = json_decode($content, true);
844 if (!is_array($json)) {
848 if (empty($data['network'])) {
849 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
850 $data['network'] = Protocol::ZOT;
851 } elseif (!isset($json['protocols'])) {
852 $data['network'] = Protocol::ZOT;
856 if (!empty($json['guid']) && empty($data['guid'])) {
857 $data['guid'] = $json['guid'];
859 if (!empty($json['key']) && empty($data['pubkey'])) {
860 $data['pubkey'] = $json['key'];
862 if (!empty($json['name'])) {
863 $data['name'] = $json['name'];
865 if (!empty($json['photo'])) {
866 $data['photo'] = $json['photo'];
867 if (!empty($json['photo_updated'])) {
868 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
871 if (!empty($json['address'])) {
872 $data['addr'] = $json['address'];
874 if (!empty($json['url'])) {
875 $data['url'] = $json['url'];
877 if (!empty($json['connections_url'])) {
878 $data['poco'] = $json['connections_url'];
880 if (isset($json['searchable'])) {
881 $data['hide'] = !$json['searchable'];
883 if (!empty($json['public_forum'])) {
884 $data['community'] = $json['public_forum'];
885 $data['account-type'] = Contact::PAGE_COMMUNITY;
888 if (!empty($json['profile'])) {
889 $profile = $json['profile'];
890 if (!empty($profile['description'])) {
891 $data['about'] = $profile['description'];
893 if (!empty($profile['keywords'])) {
894 $keywords = implode(', ', $profile['keywords']);
895 if (!empty($keywords)) {
896 $data['keywords'] = $keywords;
901 if (!empty($profile['region'])) {
902 $loc['region'] = $profile['region'];
904 if (!empty($profile['country'])) {
905 $loc['country-name'] = $profile['country'];
907 $location = Profile::formatLocation($loc);
908 if (!empty($location)) {
909 $data['location'] = $location;
917 * Perform a webfinger request.
919 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
921 * @param string $url Address that should be probed
922 * @param string $type type
924 * @return array webfinger data
925 * @throws HTTPException\InternalServerErrorException
927 private static function webfinger($url, $type)
929 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
931 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
932 if ($curlResult->isTimeout()) {
933 self::$istimeout = true;
936 $data = $curlResult->getBody();
938 $webfinger = json_decode($data, true);
939 if (is_array($webfinger)) {
940 if (!isset($webfinger["links"])) {
941 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
947 // If it is not JSON, maybe it is XML
948 $xrd = XML::parseString($data, true);
949 if (!is_object($xrd)) {
950 Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
954 $xrd_arr = XML::elementToArray($xrd);
955 if (!isset($xrd_arr["xrd"]["link"])) {
956 Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
962 if (!empty($xrd_arr["xrd"]["subject"])) {
963 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
966 if (!empty($xrd_arr["xrd"]["alias"])) {
967 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
970 $webfinger["links"] = [];
972 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
973 if (!empty($data["@attributes"])) {
974 $attributes = $data["@attributes"];
975 } elseif ($value == "@attributes") {
981 $webfinger["links"][] = $attributes;
987 * Poll the Friendica specific noscrape page.
989 * "noscrape" is a faster alternative to fetch the data from the hcard.
990 * This functionality was originally created for the directory.
992 * @param string $noscrape_url Link to the noscrape page
993 * @param array $data The already fetched data
995 * @return array noscrape data
996 * @throws HTTPException\InternalServerErrorException
998 private static function pollNoscrape($noscrape_url, $data)
1000 $curlResult = Network::curl($noscrape_url);
1001 if ($curlResult->isTimeout()) {
1002 self::$istimeout = true;
1005 $content = $curlResult->getBody();
1007 Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
1011 $json = json_decode($content, true);
1012 if (!is_array($json)) {
1013 Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
1017 if (!empty($json["fn"])) {
1018 $data["name"] = $json["fn"];
1021 if (!empty($json["addr"])) {
1022 $data["addr"] = $json["addr"];
1025 if (!empty($json["nick"])) {
1026 $data["nick"] = $json["nick"];
1029 if (!empty($json["guid"])) {
1030 $data["guid"] = $json["guid"];
1033 if (!empty($json["comm"])) {
1034 $data["community"] = $json["comm"];
1037 if (!empty($json["tags"])) {
1038 $keywords = implode(", ", $json["tags"]);
1039 if ($keywords != "") {
1040 $data["keywords"] = $keywords;
1044 $location = Profile::formatLocation($json);
1046 $data["location"] = $location;
1049 if (!empty($json["about"])) {
1050 $data["about"] = $json["about"];
1053 if (!empty($json["key"])) {
1054 $data["pubkey"] = $json["key"];
1057 if (!empty($json["photo"])) {
1058 $data["photo"] = $json["photo"];
1061 if (!empty($json["dfrn-request"])) {
1062 $data["request"] = $json["dfrn-request"];
1065 if (!empty($json["dfrn-confirm"])) {
1066 $data["confirm"] = $json["dfrn-confirm"];
1069 if (!empty($json["dfrn-notify"])) {
1070 $data["notify"] = $json["dfrn-notify"];
1073 if (!empty($json["dfrn-poll"])) {
1074 $data["poll"] = $json["dfrn-poll"];
1077 if (isset($json["hide"])) {
1078 $data["hide"] = (bool)$json["hide"];
1080 $data["hide"] = false;
1087 * Check for valid DFRN data
1089 * @param array $data DFRN data
1091 * @return int Number of errors
1093 public static function validDfrn($data)
1096 if (!isset($data['key'])) {
1099 if (!isset($data['dfrn-request'])) {
1102 if (!isset($data['dfrn-confirm'])) {
1105 if (!isset($data['dfrn-notify'])) {
1108 if (!isset($data['dfrn-poll'])) {
1115 * Fetch data from a DFRN profile page and via "noscrape"
1117 * @param string $profile_link Link to the profile page
1119 * @return array profile data
1120 * @throws HTTPException\InternalServerErrorException
1121 * @throws \ImagickException
1123 public static function profile($profile_link)
1127 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
1129 // Fetch data via noscrape - this is faster
1130 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1131 $data = self::pollNoscrape($noscrape_url, $data);
1133 if (!isset($data["notify"])
1134 || !isset($data["confirm"])
1135 || !isset($data["request"])
1136 || !isset($data["poll"])
1137 || !isset($data["name"])
1138 || !isset($data["photo"])
1140 $data = self::pollHcard($profile_link, $data, true);
1145 if (empty($data["addr"]) || empty($data["nick"])) {
1146 $probe_data = self::uri($profile_link);
1147 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1148 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1151 $prof_data["addr"] = $data["addr"];
1152 $prof_data["nick"] = $data["nick"];
1153 $prof_data["dfrn-request"] = $data['request'] ?? null;
1154 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1155 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1156 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1157 $prof_data["photo"] = $data['photo'] ?? null;
1158 $prof_data["fn"] = $data['name'] ?? null;
1159 $prof_data["key"] = $data['pubkey'] ?? null;
1161 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
1167 * Check for DFRN contact
1169 * @param array $webfinger Webfinger data
1171 * @return array DFRN data
1172 * @throws HTTPException\InternalServerErrorException
1174 private static function dfrn($webfinger)
1178 // The array is reversed to take into account the order of preference for same-rel links
1179 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1180 foreach (array_reverse($webfinger["links"]) as $link) {
1181 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1182 $data["network"] = Protocol::DFRN;
1183 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1184 $data["poll"] = $link["href"];
1185 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1186 $data["url"] = $link["href"];
1187 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1188 $hcard_url = $link["href"];
1189 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1190 $data["poco"] = $link["href"];
1191 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1192 $data["photo"] = $link["href"];
1193 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1194 $data["baseurl"] = trim($link["href"], '/');
1195 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1196 $data["guid"] = $link["href"];
1197 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1198 $data["pubkey"] = base64_decode($link["href"]);
1200 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1201 if (strstr($data["pubkey"], 'RSA ')) {
1202 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1207 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1208 foreach ($webfinger["aliases"] as $alias) {
1209 if (empty($data["url"]) && !strstr($alias, "@")) {
1210 $data["url"] = $alias;
1211 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1212 $data["alias"] = $alias;
1213 } elseif (substr($alias, 0, 5) == 'acct:') {
1214 $data["addr"] = substr($alias, 5);
1219 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1220 $data["addr"] = substr($webfinger["subject"], 5);
1223 if (!isset($data["network"]) || ($hcard_url == "")) {
1227 // Fetch data via noscrape - this is faster
1228 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1229 $data = self::pollNoscrape($noscrape_url, $data);
1231 if (isset($data["notify"])
1232 && isset($data["confirm"])
1233 && isset($data["request"])
1234 && isset($data["poll"])
1235 && isset($data["name"])
1236 && isset($data["photo"])
1241 $data = self::pollHcard($hcard_url, $data, true);
1247 * Poll the hcard page (Diaspora and Friendica specific)
1249 * @param string $hcard_url Link to the hcard page
1250 * @param array $data The already fetched data
1251 * @param boolean $dfrn Poll DFRN specific data
1253 * @return array hcard data
1254 * @throws HTTPException\InternalServerErrorException
1256 private static function pollHcard($hcard_url, $data, $dfrn = false)
1258 $curlResult = Network::curl($hcard_url);
1259 if ($curlResult->isTimeout()) {
1260 self::$istimeout = true;
1263 $content = $curlResult->getBody();
1268 $doc = new DOMDocument();
1269 if (!@$doc->loadHTML($content)) {
1273 $xpath = new DomXPath($doc);
1275 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1276 if (!is_object($vcards)) {
1280 if (!isset($data["baseurl"])) {
1281 $data["baseurl"] = "";
1284 if ($vcards->length > 0) {
1285 $vcard = $vcards->item(0);
1287 // We have to discard the guid from the hcard in favour of the guid from lrdd
1288 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1289 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1290 if (($search->length > 0) && empty($data["guid"])) {
1291 $data["guid"] = $search->item(0)->nodeValue;
1294 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1295 if ($search->length > 0) {
1296 $data["nick"] = $search->item(0)->nodeValue;
1299 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1300 if ($search->length > 0) {
1301 $data["name"] = $search->item(0)->nodeValue;
1304 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1305 if ($search->length > 0) {
1306 $data["searchable"] = $search->item(0)->nodeValue;
1309 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1310 if ($search->length > 0) {
1311 $data["pubkey"] = $search->item(0)->nodeValue;
1312 if (strstr($data["pubkey"], 'RSA ')) {
1313 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1317 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1318 if ($search->length > 0) {
1319 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1324 if (!empty($vcard)) {
1325 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1326 foreach ($photos as $photo) {
1328 foreach ($photo->attributes as $attribute) {
1329 $attr[$attribute->name] = trim($attribute->value);
1332 if (isset($attr["src"]) && isset($attr["width"])) {
1333 $avatar[$attr["width"]] = $attr["src"];
1336 // We don't have a width. So we just take everything that we got.
1337 // This is a Hubzilla workaround which doesn't send a width.
1338 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1339 $avatar[] = $attr["src"];
1344 if (sizeof($avatar)) {
1346 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1350 // Poll DFRN specific data
1351 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1352 if ($search->length > 0) {
1353 foreach ($search as $link) {
1354 //$data["request"] = $search->item(0)->nodeValue;
1356 foreach ($link->attributes as $attribute) {
1357 $attr[$attribute->name] = trim($attribute->value);
1360 $data[substr($attr["rel"], 5)] = $attr["href"];
1364 // Older Friendica versions had used the "uid" field differently than newer versions
1365 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1366 unset($data["guid"]);
1375 * Check for Diaspora contact
1377 * @param array $webfinger Webfinger data
1379 * @return array Diaspora data
1380 * @throws HTTPException\InternalServerErrorException
1382 private static function diaspora($webfinger)
1387 // The array is reversed to take into account the order of preference for same-rel links
1388 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1389 foreach (array_reverse($webfinger["links"]) as $link) {
1390 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1391 $hcard_url = $link["href"];
1392 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1393 $data["baseurl"] = trim($link["href"], '/');
1394 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1395 $data["guid"] = $link["href"];
1396 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1397 $data["url"] = $link["href"];
1398 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1399 $data["poll"] = $link["href"];
1400 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1401 $data["poco"] = $link["href"];
1402 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1403 $data["notify"] = $link["href"];
1404 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1405 $data["pubkey"] = base64_decode($link["href"]);
1407 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1408 if (strstr($data["pubkey"], 'RSA ')) {
1409 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1414 if (empty($data["url"]) || empty($hcard_url)) {
1418 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1419 foreach ($webfinger["aliases"] as $alias) {
1420 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1421 $data["alias"] = $alias;
1422 } elseif (substr($alias, 0, 5) == 'acct:') {
1423 $data["addr"] = substr($alias, 5);
1428 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1429 $data["addr"] = substr($webfinger["subject"], 5);
1432 // Fetch further information from the hcard
1433 $data = self::pollHcard($hcard_url, $data);
1439 if (!empty($data["url"])
1440 && !empty($data["guid"])
1441 && !empty($data["baseurl"])
1442 && !empty($data["pubkey"])
1443 && !empty($hcard_url)
1445 $data["network"] = Protocol::DIASPORA;
1447 // The Diaspora handle must always be lowercase
1448 if (!empty($data["addr"])) {
1449 $data["addr"] = strtolower($data["addr"]);
1452 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1453 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1454 $data["batch"] = $data["baseurl"] . "/receive/public";
1463 * Check for OStatus contact
1465 * @param array $webfinger Webfinger data
1466 * @param bool $short Short detection mode
1468 * @return array|bool OStatus data or "false" on error or "true" on short mode
1469 * @throws HTTPException\InternalServerErrorException
1471 private static function ostatus($webfinger, $short = false)
1475 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1476 foreach ($webfinger["aliases"] as $alias) {
1477 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1478 $data["addr"] = str_replace('acct:', '', $alias);
1483 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1484 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1486 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1489 if (is_array($webfinger["links"])) {
1490 // The array is reversed to take into account the order of preference for same-rel links
1491 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1492 foreach (array_reverse($webfinger["links"]) as $link) {
1493 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1494 && (($link["type"] ?? "") == "text/html")
1495 && ($link["href"] != "")
1497 $data["url"] = $link["href"];
1498 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1499 $data["notify"] = $link["href"];
1500 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1501 $data["poll"] = $link["href"];
1502 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1503 $pubkey = $link["href"];
1505 if (substr($pubkey, 0, 5) === 'data:') {
1506 if (strstr($pubkey, ',')) {
1507 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1509 $pubkey = substr($pubkey, 5);
1511 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1512 $curlResult = Network::curl($pubkey);
1513 if ($curlResult->isTimeout()) {
1514 self::$istimeout = true;
1517 $pubkey = $curlResult->getBody();
1520 $key = explode(".", $pubkey);
1522 if (sizeof($key) >= 3) {
1523 $m = Strings::base64UrlDecode($key[1]);
1524 $e = Strings::base64UrlDecode($key[2]);
1525 $data["pubkey"] = Crypto::meToPem($m, $e);
1531 if (isset($data["notify"]) && isset($data["pubkey"])
1532 && isset($data["poll"])
1533 && isset($data["url"])
1535 $data["network"] = Protocol::OSTATUS;
1544 // Fetch all additional data from the feed
1545 $curlResult = Network::curl($data["poll"]);
1546 if ($curlResult->isTimeout()) {
1547 self::$istimeout = true;
1550 $feed = $curlResult->getBody();
1551 $feed_data = Feed::import($feed);
1556 if (!empty($feed_data["header"]["author-name"])) {
1557 $data["name"] = $feed_data["header"]["author-name"];
1559 if (!empty($feed_data["header"]["author-nick"])) {
1560 $data["nick"] = $feed_data["header"]["author-nick"];
1562 if (!empty($feed_data["header"]["author-avatar"])) {
1563 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1565 if (!empty($feed_data["header"]["author-id"])) {
1566 $data["alias"] = $feed_data["header"]["author-id"];
1568 if (!empty($feed_data["header"]["author-location"])) {
1569 $data["location"] = $feed_data["header"]["author-location"];
1571 if (!empty($feed_data["header"]["author-about"])) {
1572 $data["about"] = $feed_data["header"]["author-about"];
1574 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1575 // So we take the value that we just fetched, although the other one worked as well
1576 if (!empty($feed_data["header"]["author-link"])) {
1577 $data["url"] = $feed_data["header"]["author-link"];
1580 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1581 $data['url'] = $data["alias"];
1582 $data["alias"] = '';
1585 /// @todo Fetch location and "about" from the feed as well
1590 * Fetch data from a pump.io profile page
1592 * @param string $profile_link Link to the profile page
1594 * @return array profile data
1596 private static function pumpioProfileData($profile_link)
1598 $curlResult = Network::curl($profile_link);
1599 if (!$curlResult->isSuccess()) {
1603 $doc = new DOMDocument();
1604 if (!@$doc->loadHTML($curlResult->getBody())) {
1608 $xpath = new DomXPath($doc);
1612 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1614 if ($data["name"] == '') {
1615 // This is ugly - but pump.io doesn't seem to know a better way for it
1616 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1617 $pos = strpos($data["name"], chr(10));
1619 $data["name"] = trim(substr($data["name"], 0, $pos));
1623 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1625 if ($data["location"] == '') {
1626 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1629 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1631 if ($data["about"] == '') {
1632 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1635 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1637 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1640 foreach ($avatar->attributes as $attribute) {
1641 if ($attribute->name == "src") {
1642 $data["photo"] = trim($attribute->value);
1651 * Check for pump.io contact
1653 * @param array $webfinger Webfinger data
1654 * @param string $addr
1655 * @return array pump.io data
1657 private static function pumpio($webfinger, $addr)
1660 // The array is reversed to take into account the order of preference for same-rel links
1661 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1662 foreach (array_reverse($webfinger["links"]) as $link) {
1663 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1664 && (($link["type"] ?? "") == "text/html")
1665 && ($link["href"] != "")
1667 $data["url"] = $link["href"];
1668 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1669 $data["notify"] = $link["href"];
1670 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1671 $data["poll"] = $link["href"];
1672 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1673 $data["dialback"] = $link["href"];
1676 if (isset($data["poll"]) && isset($data["notify"])
1677 && isset($data["dialback"])
1678 && isset($data["url"])
1680 // by now we use these fields only for the network type detection
1681 // So we unset all data that isn't used at the moment
1682 unset($data["dialback"]);
1684 $data["network"] = Protocol::PUMPIO;
1689 $profile_data = self::pumpioProfileData($data["url"]);
1691 if (!$profile_data) {
1695 $data = array_merge($data, $profile_data);
1697 if (($addr != '') && ($data['name'] != '')) {
1698 $name = trim(str_replace($addr, '', $data['name']));
1700 $data['name'] = $name;
1708 * Check for twitter contact
1710 * @param string $uri
1712 * @return array twitter data
1714 private static function twitter($uri)
1716 if (preg_match('=(.*)@twitter.com=i', $uri, $matches)) {
1717 $nick = $matches[1];
1718 } elseif (preg_match('=https?://twitter.com/(.*)=i', $uri, $matches)) {
1719 $nick = $matches[1];
1725 $data['url'] = 'https://twitter.com/' . $nick;
1726 $data['addr'] = $nick . '@twitter.com';
1727 $data['nick'] = $data['name'] = $nick;
1728 $data['network'] = Protocol::TWITTER;
1729 $data['baseurl'] = 'https://twitter.com';
1731 $curlResult = Network::curl($data['url'], false);
1732 if (!$curlResult->isSuccess()) {
1736 $body = $curlResult->getBody();
1737 $doc = new DOMDocument();
1738 @$doc->loadHTML($body);
1739 $xpath = new DOMXPath($doc);
1741 $list = $xpath->query('//img[@class]');
1742 foreach ($list as $node) {
1744 if ($node->attributes->length) {
1745 foreach ($node->attributes as $attribute) {
1746 $img_attr[$attribute->name] = $attribute->value;
1750 if (empty($img_attr['class'])) {
1754 if (strpos($img_attr['class'], 'ProfileAvatar-image') !== false) {
1755 if (!empty($img_attr['src'])) {
1756 $data['photo'] = $img_attr['src'];
1758 if (!empty($img_attr['alt'])) {
1759 $data['name'] = $img_attr['alt'];
1768 * Checks HTML page for RSS feed link
1770 * @param string $url Page link
1771 * @param string $body Page body string
1772 * @return string|false Feed link or false if body was invalid HTML document
1774 public static function getFeedLink(string $url, string $body)
1776 $doc = new DOMDocument();
1777 if (!@$doc->loadHTML($body)) {
1781 $xpath = new DOMXPath($doc);
1783 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1785 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1791 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1793 * Loosely based on RFC 1808
1795 * @see https://tools.ietf.org/html/rfc1808
1797 * @param string $href The potential relative href found in the HTML document
1798 * @param string $base The HTML document URL
1799 * @param DOMXPath $xpath The HTML document XPath
1802 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath)
1804 if (filter_var($href, FILTER_VALIDATE_URL)) {
1808 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1810 $baseParts = parse_url($base);
1812 // Naked domain case (scheme://basehost)
1813 $path = $baseParts['path'] ?? '/';
1815 // Remove the filename part of the path if it exists (/base/path/file)
1816 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1818 $hrefParts = parse_url($href);
1820 // Root path case (/path) including relative scheme case (//host/path)
1821 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1822 $path = $hrefParts['path'];
1824 $path = $path . '/' . $hrefParts['path'];
1826 // Resolve arbitrary relative path
1827 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1828 $parts = array_filter(explode('/', $path), 'strlen');
1829 $absolutes = array();
1830 foreach ($parts as $part) {
1831 if ('.' == $part) continue;
1832 if ('..' == $part) {
1833 array_pop($absolutes);
1835 $absolutes[] = $part;
1839 $path = '/' . implode('/', $absolutes);
1842 // Relative scheme case (//host/path)
1843 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1844 $baseParts['path'] = $path;
1845 unset($baseParts['query']);
1846 unset($baseParts['fragment']);
1848 return Network::unparseURL($baseParts);
1852 * Check for feed contact
1854 * @param string $url Profile link
1855 * @param boolean $probe Do a probe if the page contains a feed link
1857 * @return array feed data
1858 * @throws HTTPException\InternalServerErrorException
1860 private static function feed($url, $probe = true)
1862 $curlResult = Network::curl($url);
1863 if ($curlResult->isTimeout()) {
1864 self::$istimeout = true;
1867 $feed = $curlResult->getBody();
1868 $feed_data = Feed::import($feed);
1875 $feed_url = self::getFeedLink($url, $feed);
1881 return self::feed($feed_url, false);
1884 if (!empty($feed_data["header"]["author-name"])) {
1885 $data["name"] = $feed_data["header"]["author-name"];
1888 if (!empty($feed_data["header"]["author-nick"])) {
1889 $data["nick"] = $feed_data["header"]["author-nick"];
1892 if (!empty($feed_data["header"]["author-avatar"])) {
1893 $data["photo"] = $feed_data["header"]["author-avatar"];
1896 if (!empty($feed_data["header"]["author-id"])) {
1897 $data["alias"] = $feed_data["header"]["author-id"];
1900 $data["url"] = $url;
1901 $data["poll"] = $url;
1903 if (!empty($feed_data["header"]["author-link"])) {
1904 $data["baseurl"] = $feed_data["header"]["author-link"];
1906 $data["baseurl"] = $data["url"];
1909 $data["network"] = Protocol::FEED;
1915 * Check for mail contact
1917 * @param string $uri Profile link
1918 * @param integer $uid User ID
1920 * @return array mail data
1921 * @throws \Exception
1923 private static function mail($uri, $uid)
1925 if (!Network::isEmailDomainValid($uri)) {
1933 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1935 $condition = ["`uid` = ? AND `server` != ''", $uid];
1936 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1937 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1939 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1943 $mailbox = Email::constructMailboxName($mailacct);
1945 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1946 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1951 $msgs = Email::poll($mbox, $uri);
1952 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1954 if (!count($msgs)) {
1958 $phost = substr($uri, strpos($uri, '@') + 1);
1961 $data["addr"] = $uri;
1962 $data["network"] = Protocol::MAIL;
1963 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1964 $data["nick"] = $data["name"];
1965 $data["photo"] = Network::lookupAvatarByEmail($uri);
1966 $data["url"] = 'mailto:'.$uri;
1967 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1968 $data["poll"] = 'email ' . Strings::getRandomHex();
1970 $x = Email::messageMeta($mbox, $msgs[0]);
1971 if (stristr($x[0]->from, $uri)) {
1972 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1973 } elseif (stristr($x[0]->to, $uri)) {
1974 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1977 foreach ($adr as $feadr) {
1978 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1979 &&(strcasecmp($feadr->host, $phost) == 0)
1980 && (strlen($feadr->personal))
1982 $personal = imap_mime_header_decode($feadr->personal);
1984 foreach ($personal as $perspart) {
1985 if ($perspart->charset != "default") {
1986 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1988 $data["name"] .= $perspart->text;
1992 $data["name"] = Strings::escapeTags($data["name"]);
1996 if (!empty($mbox)) {
2003 * Mix two paths together to possibly fix missing parts
2005 * @param string $avatar Path to the avatar
2006 * @param string $base Another path that is hopefully complete
2008 * @return string fixed avatar path
2009 * @throws \Exception
2011 public static function fixAvatar($avatar, $base)
2013 $base_parts = parse_url($base);
2015 // Remove all parts that could create a problem
2016 unset($base_parts['path']);
2017 unset($base_parts['query']);
2018 unset($base_parts['fragment']);
2020 $avatar_parts = parse_url($avatar);
2023 $parts = array_merge($base_parts, $avatar_parts);
2025 // And put them together again
2026 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
2027 $host = isset($parts['host']) ? $parts['host'] : '';
2028 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
2029 $path = isset($parts['path']) ? $parts['path'] : '';
2030 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
2031 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
2033 $fixed = $scheme.$host.$port.$path.$query.$fragment;
2035 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);