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", "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 * Get the link for the remote follow page for a given profile link
276 * @param sting $profile
277 * @return string Remote follow page link
279 public static function getRemoteFollowLink(string $profile)
283 $links = self::lrdd($profile);
285 if (!empty($links) && is_array($links)) {
286 foreach ($links as $link) {
287 if ($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) {
288 $follow_link = $link['@attributes']['template'];
296 * Check an URI for LRDD data
298 * @param string $uri Address that should be probed
300 * @return array uri data
301 * @throws HTTPException\InternalServerErrorException
303 public static function lrdd($uri)
305 $lrdd = self::hostMeta($uri);
308 if (is_bool($lrdd)) {
313 $parts = @parse_url($uri);
314 if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
318 $host = $parts['scheme'] . '://' . $parts["host"];
319 if (!empty($parts["port"])) {
320 $host .= ':'.$parts["port"];
323 $path_parts = explode("/", trim($parts["path"], "/"));
325 $nick = array_pop($path_parts);
328 $lrdd = self::hostMeta($host);
329 $host .= "/".array_shift($path_parts);
330 } while (!$lrdd && (sizeof($path_parts) > 0));
334 Logger::log("No lrdd data found for ".$uri, Logger::DEBUG);
338 foreach ($lrdd as $type => $template) {
343 $path = str_replace('{uri}', urlencode($uri), $template);
344 $webfinger = self::webfinger($path, $type);
346 if (!$webfinger && (strstr($uri, "@"))) {
347 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
348 $webfinger = self::webfinger($path, $type);
351 // Special treatment for Mastodon
352 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
353 // But the webfinger for this format fails.
354 if (!$webfinger && !empty($nick)) {
355 // Mastodon uses a "@" as prefix for usernames in their url format
356 $nick = ltrim($nick, '@');
358 $addr = $nick."@".$host;
360 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
361 $webfinger = self::webfinger($path, $type);
365 if (!is_array($webfinger["links"])) {
366 Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
372 foreach ($webfinger["links"] as $link) {
373 $data[] = ["@attributes" => $link];
376 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
377 foreach ($webfinger["aliases"] as $alias) {
378 $data[] = ["@attributes" =>
388 * Fetch information (protocol endpoints and user information) about a given uri
390 * @param string $uri Address that should be probed
391 * @param string $network Test for this specific network
392 * @param integer $uid User ID for the probe (only used for mails)
393 * @param boolean $cache Use cached values?
395 * @return array uri data
396 * @throws HTTPException\InternalServerErrorException
397 * @throws \ImagickException
399 public static function uri($uri, $network = '', $uid = -1, $cache = true)
402 $result = DI::cache()->get('Probe::uri:' . $network . ':' . $uri);
403 if (!is_null($result)) {
412 self::$istimeout = false;
414 if ($network != Protocol::ACTIVITYPUB) {
415 $data = self::detect($uri, $network, $uid);
420 // When the previous detection process had got a time out
421 // we could falsely detect a Friendica profile as AP profile.
422 if (!self::$istimeout) {
423 $ap_profile = ActivityPub::probeProfile($uri);
425 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
427 } elseif (!empty($ap_profile)) {
428 $ap_profile['batch'] = '';
429 $data = array_merge($ap_profile, $data);
432 Logger::notice('Time out detected. AP will not be probed.', ['uri' => $uri]);
435 if (!isset($data['url'])) {
439 if (empty($data['photo'])) {
440 $data['photo'] = DI::baseUrl() . '/images/person-300.jpg';
443 if (empty($data['name'])) {
444 if (!empty($data['nick'])) {
445 $data['name'] = $data['nick'];
448 if (empty($data['name'])) {
449 $data['name'] = $data['url'];
453 if (empty($data['nick'])) {
454 $data['nick'] = strtolower($data['name']);
456 if (strpos($data['nick'], ' ')) {
457 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
461 if (!empty(self::$baseurl)) {
462 $data['baseurl'] = self::$baseurl;
465 if (!empty($data['baseurl']) && empty($data['gsid'])) {
466 $data['gsid'] = GServer::getID($data['baseurl']);
469 if (empty($data['network'])) {
470 $data['network'] = Protocol::PHANTOM;
473 // Ensure that local connections always are DFRN
474 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
475 $data['network'] = Protocol::DFRN;
478 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
479 $data['hide'] = self::getHideStatus($data['url']);
482 $data = self::rearrangeData($data);
484 // Only store into the cache if the value seems to be valid
485 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
486 DI::cache()->set('Probe::uri:' . $network . ':' . $uri, $data, Duration::DAY);
494 * Fetches the "hide" status from the profile
496 * @param string $url URL of the profile
498 * @return boolean "hide" status
500 private static function getHideStatus($url)
502 $curlResult = Network::curl($url);
503 if (!$curlResult->isSuccess()) {
507 // If the file is too large then exit
508 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
512 // If it isn't a HTML file then exit
513 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
517 $body = $curlResult->getBody();
519 $doc = new DOMDocument();
520 @$doc->loadHTML($body);
522 $xpath = new DOMXPath($doc);
524 $list = $xpath->query('//meta[@name]');
525 foreach ($list as $node) {
527 if ($node->attributes->length) {
528 foreach ($node->attributes as $attribute) {
529 $meta_tag[$attribute->name] = $attribute->value;
533 if (empty($meta_tag['content'])) {
537 $content = strtolower(trim($meta_tag['content']));
539 switch (strtolower(trim($meta_tag['name']))) {
540 case 'dfrn-global-visibility':
541 if ($content == 'false') {
546 if (strpos($content, 'noindex') !== false) {
557 * Checks if a profile url should be OStatus but only provides partial information
559 * @param array $webfinger Webfinger data
560 * @param string $lrdd Path template for webfinger request
561 * @param string $type type
563 * @return array fixed webfinger data
564 * @throws HTTPException\InternalServerErrorException
566 private static function fixOStatus($webfinger, $lrdd, $type)
568 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
575 foreach ($webfinger['links'] as $link) {
576 if ($link['rel'] == ActivityNamespace::OSTATUSSUB) {
579 if ($link['rel'] == 'magic-public-key') {
584 if (!$is_ostatus || $has_key) {
588 $url = Network::switchScheme($webfinger['subject']);
589 $path = str_replace('{uri}', urlencode($url), $lrdd);
590 $webfinger2 = self::webfinger($path, $type);
592 // Is the new webfinger detectable as OStatus?
593 if (self::ostatus($webfinger2, true)) {
594 $webfinger = $webfinger2;
601 * Fetch information (protocol endpoints and user information) about a given uri
603 * This function is only called by the "uri" function that adds caching and rearranging of data.
605 * @param string $uri Address that should be probed
606 * @param string $network Test for this specific network
607 * @param integer $uid User ID for the probe (only used for mails)
609 * @return array uri data
610 * @throws HTTPException\InternalServerErrorException
612 private static function detect($uri, $network, $uid)
614 $parts = parse_url($uri);
616 if (!empty($parts["scheme"]) && !empty($parts["host"])) {
617 $host = $parts["host"];
618 if (!empty($parts["port"])) {
619 $host .= ':'.$parts["port"];
622 if ($host == 'twitter.com') {
623 return self::twitter($uri);
625 $lrdd = self::hostMeta($host);
627 if (is_bool($lrdd)) {
631 $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
633 while (!$lrdd && (sizeof($path_parts) > 1)) {
634 $host .= "/".array_shift($path_parts);
635 $lrdd = self::hostMeta($host);
638 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
639 return self::feed($uri);
641 $nick = array_pop($path_parts);
643 // Mastodon uses a "@" as prefix for usernames in their url format
644 $nick = ltrim($nick, '@');
646 $addr = $nick."@".$host;
647 } elseif (strstr($uri, '@')) {
648 // If the URI starts with "mailto:" then jump directly to the mail detection
649 if (strpos($uri, 'mailto:') !== false) {
650 $uri = str_replace('mailto:', '', $uri);
651 return self::mail($uri, $uid);
654 if ($network == Protocol::MAIL) {
655 return self::mail($uri, $uid);
657 // Remove "acct:" from the URI
658 $uri = str_replace('acct:', '', $uri);
660 $host = substr($uri, strpos($uri, '@') + 1);
661 $nick = substr($uri, 0, strpos($uri, '@'));
663 if (strpos($uri, '@twitter.com')) {
664 return self::twitter($uri);
666 $lrdd = self::hostMeta($host);
668 if (is_bool($lrdd)) {
673 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
674 return self::mail($uri, $uid);
678 Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
684 /// @todo Do we need the prefix "acct:" or "acct://"?
686 foreach ($lrdd as $type => $template) {
691 // At first try it with the given uri
692 $path = str_replace('{uri}', urlencode($uri), $template);
693 $webfinger = self::webfinger($path, $type);
695 // Fix possible problems with GNU Social probing to wrong scheme
696 $webfinger = self::fixOStatus($webfinger, $template, $type);
698 // We cannot be sure that the detected address was correct, so we don't use the values
699 if ($webfinger && ($uri != $addr)) {
704 // Try webfinger with the address (user@domain.tld)
706 $path = str_replace('{uri}', urlencode($addr), $template);
707 $webfinger = self::webfinger($path, $type);
710 // Mastodon needs to have it with "acct:"
712 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
713 $webfinger = self::webfinger($path, $type);
718 return self::feed($uri);
723 Logger::log("Probing ".$uri, Logger::DEBUG);
725 if (in_array($network, ["", Protocol::DFRN])) {
726 $result = self::dfrn($webfinger);
728 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
729 $result = self::diaspora($webfinger);
731 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
732 $result = self::ostatus($webfinger);
734 if (in_array($network, ['', Protocol::ZOT])) {
735 $result = self::zot($webfinger, $result);
737 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
738 $result = self::pumpio($webfinger, $addr);
740 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
741 $result = self::feed($uri);
743 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
744 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
745 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
746 $result["nick"] = $nick;
749 if (empty($result["addr"]) && ($addr != "")) {
750 $result["addr"] = $addr;
754 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;
774 * Check for Zot contact
776 * @param array $webfinger Webfinger data
777 * @param array $data previously probed data
779 * @return array Zot data
780 * @throws HTTPException\InternalServerErrorException
782 private static function zot($webfinger, $data)
784 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
785 foreach ($webfinger["aliases"] as $alias) {
786 if (substr($alias, 0, 5) == 'acct:') {
787 $data["addr"] = substr($alias, 5);
792 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
793 $data["addr"] = substr($webfinger["subject"], 5);
797 foreach ($webfinger['links'] as $link) {
798 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
799 $zot_url = $link['href'];
803 if (empty($zot_url) && !empty($data['addr']) && !empty(self::$baseurl)) {
804 $condition = ['nurl' => Strings::normaliseLink(self::$baseurl), 'platform' => ['hubzilla']];
805 if (!DBA::exists('gserver', $condition)) {
808 $zot_url = self::$baseurl . '/.well-known/zot-info?address=' . $data['addr'];
811 if (empty($zot_url)) {
815 $data = self::pollZot($zot_url, $data);
817 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
818 foreach ($webfinger['aliases'] as $alias) {
819 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
820 $data['alias'] = $alias;
828 public static function pollZot($url, $data)
830 $curlResult = Network::curl($url);
831 if ($curlResult->isTimeout()) {
834 $content = $curlResult->getBody();
839 $json = json_decode($content, true);
840 if (!is_array($json)) {
844 if (empty($data['network'])) {
845 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
846 $data['network'] = Protocol::ZOT;
847 } elseif (!isset($json['protocols'])) {
848 $data['network'] = Protocol::ZOT;
852 if (!empty($json['guid']) && empty($data['guid'])) {
853 $data['guid'] = $json['guid'];
855 if (!empty($json['key']) && empty($data['pubkey'])) {
856 $data['pubkey'] = $json['key'];
858 if (!empty($json['name'])) {
859 $data['name'] = $json['name'];
861 if (!empty($json['photo'])) {
862 $data['photo'] = $json['photo'];
863 if (!empty($json['photo_updated'])) {
864 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
867 if (!empty($json['address'])) {
868 $data['addr'] = $json['address'];
870 if (!empty($json['url'])) {
871 $data['url'] = $json['url'];
873 if (!empty($json['connections_url'])) {
874 $data['poco'] = $json['connections_url'];
876 if (isset($json['searchable'])) {
877 $data['hide'] = !$json['searchable'];
879 if (!empty($json['public_forum'])) {
880 $data['community'] = $json['public_forum'];
881 $data['account-type'] = Contact::PAGE_COMMUNITY;
884 if (!empty($json['profile'])) {
885 $profile = $json['profile'];
886 if (!empty($profile['description'])) {
887 $data['about'] = $profile['description'];
889 if (!empty($profile['keywords'])) {
890 $keywords = implode(', ', $profile['keywords']);
891 if (!empty($keywords)) {
892 $data['keywords'] = $keywords;
897 if (!empty($profile['region'])) {
898 $loc['region'] = $profile['region'];
900 if (!empty($profile['country'])) {
901 $loc['country-name'] = $profile['country'];
903 $location = Profile::formatLocation($loc);
904 if (!empty($location)) {
905 $data['location'] = $location;
913 * Perform a webfinger request.
915 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
917 * @param string $url Address that should be probed
918 * @param string $type type
920 * @return array webfinger data
921 * @throws HTTPException\InternalServerErrorException
923 private static function webfinger($url, $type)
925 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
927 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
928 if ($curlResult->isTimeout()) {
929 self::$istimeout = true;
932 $data = $curlResult->getBody();
934 $webfinger = json_decode($data, true);
935 if (is_array($webfinger)) {
936 if (!isset($webfinger["links"])) {
937 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
943 // If it is not JSON, maybe it is XML
944 $xrd = XML::parseString($data, true);
945 if (!is_object($xrd)) {
946 Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
950 $xrd_arr = XML::elementToArray($xrd);
951 if (!isset($xrd_arr["xrd"]["link"])) {
952 Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
958 if (!empty($xrd_arr["xrd"]["subject"])) {
959 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
962 if (!empty($xrd_arr["xrd"]["alias"])) {
963 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
966 $webfinger["links"] = [];
968 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
969 if (!empty($data["@attributes"])) {
970 $attributes = $data["@attributes"];
971 } elseif ($value == "@attributes") {
977 $webfinger["links"][] = $attributes;
983 * Poll the Friendica specific noscrape page.
985 * "noscrape" is a faster alternative to fetch the data from the hcard.
986 * This functionality was originally created for the directory.
988 * @param string $noscrape_url Link to the noscrape page
989 * @param array $data The already fetched data
991 * @return array noscrape data
992 * @throws HTTPException\InternalServerErrorException
994 private static function pollNoscrape($noscrape_url, $data)
996 $curlResult = Network::curl($noscrape_url);
997 if ($curlResult->isTimeout()) {
998 self::$istimeout = true;
1001 $content = $curlResult->getBody();
1003 Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
1007 $json = json_decode($content, true);
1008 if (!is_array($json)) {
1009 Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
1013 if (!empty($json["fn"])) {
1014 $data["name"] = $json["fn"];
1017 if (!empty($json["addr"])) {
1018 $data["addr"] = $json["addr"];
1021 if (!empty($json["nick"])) {
1022 $data["nick"] = $json["nick"];
1025 if (!empty($json["guid"])) {
1026 $data["guid"] = $json["guid"];
1029 if (!empty($json["comm"])) {
1030 $data["community"] = $json["comm"];
1033 if (!empty($json["tags"])) {
1034 $keywords = implode(", ", $json["tags"]);
1035 if ($keywords != "") {
1036 $data["keywords"] = $keywords;
1040 $location = Profile::formatLocation($json);
1042 $data["location"] = $location;
1045 if (!empty($json["about"])) {
1046 $data["about"] = $json["about"];
1049 if (!empty($json["key"])) {
1050 $data["pubkey"] = $json["key"];
1053 if (!empty($json["photo"])) {
1054 $data["photo"] = $json["photo"];
1057 if (!empty($json["dfrn-request"])) {
1058 $data["request"] = $json["dfrn-request"];
1061 if (!empty($json["dfrn-confirm"])) {
1062 $data["confirm"] = $json["dfrn-confirm"];
1065 if (!empty($json["dfrn-notify"])) {
1066 $data["notify"] = $json["dfrn-notify"];
1069 if (!empty($json["dfrn-poll"])) {
1070 $data["poll"] = $json["dfrn-poll"];
1073 if (isset($json["hide"])) {
1074 $data["hide"] = (bool)$json["hide"];
1076 $data["hide"] = false;
1083 * Check for valid DFRN data
1085 * @param array $data DFRN data
1087 * @return int Number of errors
1089 public static function validDfrn($data)
1092 if (!isset($data['key'])) {
1095 if (!isset($data['dfrn-request'])) {
1098 if (!isset($data['dfrn-confirm'])) {
1101 if (!isset($data['dfrn-notify'])) {
1104 if (!isset($data['dfrn-poll'])) {
1111 * Fetch data from a DFRN profile page and via "noscrape"
1113 * @param string $profile_link Link to the profile page
1115 * @return array profile data
1116 * @throws HTTPException\InternalServerErrorException
1117 * @throws \ImagickException
1119 public static function profile($profile_link)
1123 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
1125 // Fetch data via noscrape - this is faster
1126 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1127 $data = self::pollNoscrape($noscrape_url, $data);
1129 if (!isset($data["notify"])
1130 || !isset($data["confirm"])
1131 || !isset($data["request"])
1132 || !isset($data["poll"])
1133 || !isset($data["name"])
1134 || !isset($data["photo"])
1136 $data = self::pollHcard($profile_link, $data, true);
1141 if (empty($data["addr"]) || empty($data["nick"])) {
1142 $probe_data = self::uri($profile_link);
1143 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1144 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1147 $prof_data["addr"] = $data["addr"];
1148 $prof_data["nick"] = $data["nick"];
1149 $prof_data["dfrn-request"] = $data['request'] ?? null;
1150 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1151 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1152 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1153 $prof_data["photo"] = $data['photo'] ?? null;
1154 $prof_data["fn"] = $data['name'] ?? null;
1155 $prof_data["key"] = $data['pubkey'] ?? null;
1157 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
1163 * Check for DFRN contact
1165 * @param array $webfinger Webfinger data
1167 * @return array DFRN data
1168 * @throws HTTPException\InternalServerErrorException
1170 private static function dfrn($webfinger)
1174 // The array is reversed to take into account the order of preference for same-rel links
1175 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1176 foreach (array_reverse($webfinger["links"]) as $link) {
1177 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1178 $data["network"] = Protocol::DFRN;
1179 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1180 $data["poll"] = $link["href"];
1181 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1182 $data["url"] = $link["href"];
1183 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1184 $hcard_url = $link["href"];
1185 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1186 $data["poco"] = $link["href"];
1187 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1188 $data["photo"] = $link["href"];
1189 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1190 $data["baseurl"] = trim($link["href"], '/');
1191 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1192 $data["guid"] = $link["href"];
1193 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1194 $data["pubkey"] = base64_decode($link["href"]);
1196 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1197 if (strstr($data["pubkey"], 'RSA ')) {
1198 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1203 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1204 foreach ($webfinger["aliases"] as $alias) {
1205 if (empty($data["url"]) && !strstr($alias, "@")) {
1206 $data["url"] = $alias;
1207 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1208 $data["alias"] = $alias;
1209 } elseif (substr($alias, 0, 5) == 'acct:') {
1210 $data["addr"] = substr($alias, 5);
1215 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1216 $data["addr"] = substr($webfinger["subject"], 5);
1219 if (!isset($data["network"]) || ($hcard_url == "")) {
1223 // Fetch data via noscrape - this is faster
1224 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1225 $data = self::pollNoscrape($noscrape_url, $data);
1227 if (isset($data["notify"])
1228 && isset($data["confirm"])
1229 && isset($data["request"])
1230 && isset($data["poll"])
1231 && isset($data["name"])
1232 && isset($data["photo"])
1237 $data = self::pollHcard($hcard_url, $data, true);
1243 * Poll the hcard page (Diaspora and Friendica specific)
1245 * @param string $hcard_url Link to the hcard page
1246 * @param array $data The already fetched data
1247 * @param boolean $dfrn Poll DFRN specific data
1249 * @return array hcard data
1250 * @throws HTTPException\InternalServerErrorException
1252 private static function pollHcard($hcard_url, $data, $dfrn = false)
1254 $curlResult = Network::curl($hcard_url);
1255 if ($curlResult->isTimeout()) {
1256 self::$istimeout = true;
1259 $content = $curlResult->getBody();
1264 $doc = new DOMDocument();
1265 if (!@$doc->loadHTML($content)) {
1269 $xpath = new DomXPath($doc);
1271 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1272 if (!is_object($vcards)) {
1276 if (!isset($data["baseurl"])) {
1277 $data["baseurl"] = "";
1280 if ($vcards->length > 0) {
1281 $vcard = $vcards->item(0);
1283 // We have to discard the guid from the hcard in favour of the guid from lrdd
1284 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1285 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1286 if (($search->length > 0) && empty($data["guid"])) {
1287 $data["guid"] = $search->item(0)->nodeValue;
1290 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1291 if ($search->length > 0) {
1292 $data["nick"] = $search->item(0)->nodeValue;
1295 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1296 if ($search->length > 0) {
1297 $data["name"] = $search->item(0)->nodeValue;
1300 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1301 if ($search->length > 0) {
1302 $data["searchable"] = $search->item(0)->nodeValue;
1305 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1306 if ($search->length > 0) {
1307 $data["pubkey"] = $search->item(0)->nodeValue;
1308 if (strstr($data["pubkey"], 'RSA ')) {
1309 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1313 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1314 if ($search->length > 0) {
1315 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1320 if (!empty($vcard)) {
1321 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1322 foreach ($photos as $photo) {
1324 foreach ($photo->attributes as $attribute) {
1325 $attr[$attribute->name] = trim($attribute->value);
1328 if (isset($attr["src"]) && isset($attr["width"])) {
1329 $avatar[$attr["width"]] = $attr["src"];
1332 // We don't have a width. So we just take everything that we got.
1333 // This is a Hubzilla workaround which doesn't send a width.
1334 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1335 $avatar[] = $attr["src"];
1340 if (sizeof($avatar)) {
1342 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1346 // Poll DFRN specific data
1347 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1348 if ($search->length > 0) {
1349 foreach ($search as $link) {
1350 //$data["request"] = $search->item(0)->nodeValue;
1352 foreach ($link->attributes as $attribute) {
1353 $attr[$attribute->name] = trim($attribute->value);
1356 $data[substr($attr["rel"], 5)] = $attr["href"];
1360 // Older Friendica versions had used the "uid" field differently than newer versions
1361 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1362 unset($data["guid"]);
1371 * Check for Diaspora contact
1373 * @param array $webfinger Webfinger data
1375 * @return array Diaspora data
1376 * @throws HTTPException\InternalServerErrorException
1378 private static function diaspora($webfinger)
1383 // The array is reversed to take into account the order of preference for same-rel links
1384 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1385 foreach (array_reverse($webfinger["links"]) as $link) {
1386 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1387 $hcard_url = $link["href"];
1388 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1389 $data["baseurl"] = trim($link["href"], '/');
1390 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1391 $data["guid"] = $link["href"];
1392 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1393 $data["url"] = $link["href"];
1394 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1395 $data["poll"] = $link["href"];
1396 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1397 $data["poco"] = $link["href"];
1398 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1399 $data["notify"] = $link["href"];
1400 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1401 $data["pubkey"] = base64_decode($link["href"]);
1403 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1404 if (strstr($data["pubkey"], 'RSA ')) {
1405 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1410 if (empty($data["url"]) || empty($hcard_url)) {
1414 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1415 foreach ($webfinger["aliases"] as $alias) {
1416 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1417 $data["alias"] = $alias;
1418 } elseif (substr($alias, 0, 5) == 'acct:') {
1419 $data["addr"] = substr($alias, 5);
1424 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1425 $data["addr"] = substr($webfinger["subject"], 5);
1428 // Fetch further information from the hcard
1429 $data = self::pollHcard($hcard_url, $data);
1435 if (!empty($data["url"])
1436 && !empty($data["guid"])
1437 && !empty($data["baseurl"])
1438 && !empty($data["pubkey"])
1439 && !empty($hcard_url)
1441 $data["network"] = Protocol::DIASPORA;
1443 // The Diaspora handle must always be lowercase
1444 if (!empty($data["addr"])) {
1445 $data["addr"] = strtolower($data["addr"]);
1448 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1449 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1450 $data["batch"] = $data["baseurl"] . "/receive/public";
1459 * Check for OStatus contact
1461 * @param array $webfinger Webfinger data
1462 * @param bool $short Short detection mode
1464 * @return array|bool OStatus data or "false" on error or "true" on short mode
1465 * @throws HTTPException\InternalServerErrorException
1467 private static function ostatus($webfinger, $short = false)
1471 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1472 foreach ($webfinger["aliases"] as $alias) {
1473 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1474 $data["addr"] = str_replace('acct:', '', $alias);
1479 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1480 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1482 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1485 if (is_array($webfinger["links"])) {
1486 // The array is reversed to take into account the order of preference for same-rel links
1487 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1488 foreach (array_reverse($webfinger["links"]) as $link) {
1489 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1490 && (($link["type"] ?? "") == "text/html")
1491 && ($link["href"] != "")
1493 $data["url"] = $link["href"];
1494 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1495 $data["notify"] = $link["href"];
1496 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1497 $data["poll"] = $link["href"];
1498 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1499 $pubkey = $link["href"];
1501 if (substr($pubkey, 0, 5) === 'data:') {
1502 if (strstr($pubkey, ',')) {
1503 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1505 $pubkey = substr($pubkey, 5);
1507 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1508 $curlResult = Network::curl($pubkey);
1509 if ($curlResult->isTimeout()) {
1510 self::$istimeout = true;
1513 $pubkey = $curlResult->getBody();
1516 $key = explode(".", $pubkey);
1518 if (sizeof($key) >= 3) {
1519 $m = Strings::base64UrlDecode($key[1]);
1520 $e = Strings::base64UrlDecode($key[2]);
1521 $data["pubkey"] = Crypto::meToPem($m, $e);
1527 if (isset($data["notify"]) && isset($data["pubkey"])
1528 && isset($data["poll"])
1529 && isset($data["url"])
1531 $data["network"] = Protocol::OSTATUS;
1540 // Fetch all additional data from the feed
1541 $curlResult = Network::curl($data["poll"]);
1542 if ($curlResult->isTimeout()) {
1543 self::$istimeout = true;
1546 $feed = $curlResult->getBody();
1547 $feed_data = Feed::import($feed);
1552 if (!empty($feed_data["header"]["author-name"])) {
1553 $data["name"] = $feed_data["header"]["author-name"];
1555 if (!empty($feed_data["header"]["author-nick"])) {
1556 $data["nick"] = $feed_data["header"]["author-nick"];
1558 if (!empty($feed_data["header"]["author-avatar"])) {
1559 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1561 if (!empty($feed_data["header"]["author-id"])) {
1562 $data["alias"] = $feed_data["header"]["author-id"];
1564 if (!empty($feed_data["header"]["author-location"])) {
1565 $data["location"] = $feed_data["header"]["author-location"];
1567 if (!empty($feed_data["header"]["author-about"])) {
1568 $data["about"] = $feed_data["header"]["author-about"];
1570 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1571 // So we take the value that we just fetched, although the other one worked as well
1572 if (!empty($feed_data["header"]["author-link"])) {
1573 $data["url"] = $feed_data["header"]["author-link"];
1576 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1577 $data['url'] = $data["alias"];
1578 $data["alias"] = '';
1581 /// @todo Fetch location and "about" from the feed as well
1586 * Fetch data from a pump.io profile page
1588 * @param string $profile_link Link to the profile page
1590 * @return array profile data
1592 private static function pumpioProfileData($profile_link)
1594 $curlResult = Network::curl($profile_link);
1595 if (!$curlResult->isSuccess()) {
1599 $doc = new DOMDocument();
1600 if (!@$doc->loadHTML($curlResult->getBody())) {
1604 $xpath = new DomXPath($doc);
1608 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1610 if ($data["name"] == '') {
1611 // This is ugly - but pump.io doesn't seem to know a better way for it
1612 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1613 $pos = strpos($data["name"], chr(10));
1615 $data["name"] = trim(substr($data["name"], 0, $pos));
1619 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1621 if ($data["location"] == '') {
1622 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1625 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1627 if ($data["about"] == '') {
1628 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1631 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1633 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1636 foreach ($avatar->attributes as $attribute) {
1637 if ($attribute->name == "src") {
1638 $data["photo"] = trim($attribute->value);
1647 * Check for pump.io contact
1649 * @param array $webfinger Webfinger data
1650 * @param string $addr
1651 * @return array pump.io data
1653 private static function pumpio($webfinger, $addr)
1656 // The array is reversed to take into account the order of preference for same-rel links
1657 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1658 foreach (array_reverse($webfinger["links"]) as $link) {
1659 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1660 && (($link["type"] ?? "") == "text/html")
1661 && ($link["href"] != "")
1663 $data["url"] = $link["href"];
1664 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1665 $data["notify"] = $link["href"];
1666 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1667 $data["poll"] = $link["href"];
1668 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1669 $data["dialback"] = $link["href"];
1672 if (isset($data["poll"]) && isset($data["notify"])
1673 && isset($data["dialback"])
1674 && isset($data["url"])
1676 // by now we use these fields only for the network type detection
1677 // So we unset all data that isn't used at the moment
1678 unset($data["dialback"]);
1680 $data["network"] = Protocol::PUMPIO;
1685 $profile_data = self::pumpioProfileData($data["url"]);
1687 if (!$profile_data) {
1691 $data = array_merge($data, $profile_data);
1693 if (($addr != '') && ($data['name'] != '')) {
1694 $name = trim(str_replace($addr, '', $data['name']));
1696 $data['name'] = $name;
1704 * Check for twitter contact
1706 * @param string $uri
1708 * @return array twitter data
1710 private static function twitter($uri)
1712 if (preg_match('=(.*)@twitter.com=i', $uri, $matches)) {
1713 $nick = $matches[1];
1714 } elseif (preg_match('=https?://twitter.com/(.*)=i', $uri, $matches)) {
1715 $nick = $matches[1];
1721 $data['url'] = 'https://twitter.com/' . $nick;
1722 $data['addr'] = $nick . '@twitter.com';
1723 $data['nick'] = $data['name'] = $nick;
1724 $data['network'] = Protocol::TWITTER;
1725 $data['baseurl'] = 'https://twitter.com';
1727 $curlResult = Network::curl($data['url'], false);
1728 if (!$curlResult->isSuccess()) {
1732 $body = $curlResult->getBody();
1733 $doc = new DOMDocument();
1734 @$doc->loadHTML($body);
1735 $xpath = new DOMXPath($doc);
1737 $list = $xpath->query('//img[@class]');
1738 foreach ($list as $node) {
1740 if ($node->attributes->length) {
1741 foreach ($node->attributes as $attribute) {
1742 $img_attr[$attribute->name] = $attribute->value;
1746 if (empty($img_attr['class'])) {
1750 if (strpos($img_attr['class'], 'ProfileAvatar-image') !== false) {
1751 if (!empty($img_attr['src'])) {
1752 $data['photo'] = $img_attr['src'];
1754 if (!empty($img_attr['alt'])) {
1755 $data['name'] = $img_attr['alt'];
1764 * Checks HTML page for RSS feed link
1766 * @param string $url Page link
1767 * @param string $body Page body string
1768 * @return string|false Feed link or false if body was invalid HTML document
1770 public static function getFeedLink(string $url, string $body)
1772 $doc = new DOMDocument();
1773 if (!@$doc->loadHTML($body)) {
1777 $xpath = new DOMXPath($doc);
1779 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1781 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1787 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1789 * Loosely based on RFC 1808
1791 * @see https://tools.ietf.org/html/rfc1808
1793 * @param string $href The potential relative href found in the HTML document
1794 * @param string $base The HTML document URL
1795 * @param DOMXPath $xpath The HTML document XPath
1798 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath)
1800 if (filter_var($href, FILTER_VALIDATE_URL)) {
1804 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1806 $baseParts = parse_url($base);
1808 // Naked domain case (scheme://basehost)
1809 $path = $baseParts['path'] ?? '/';
1811 // Remove the filename part of the path if it exists (/base/path/file)
1812 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1814 $hrefParts = parse_url($href);
1816 // Root path case (/path) including relative scheme case (//host/path)
1817 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1818 $path = $hrefParts['path'];
1820 $path = $path . '/' . $hrefParts['path'];
1822 // Resolve arbitrary relative path
1823 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1824 $parts = array_filter(explode('/', $path), 'strlen');
1825 $absolutes = array();
1826 foreach ($parts as $part) {
1827 if ('.' == $part) continue;
1828 if ('..' == $part) {
1829 array_pop($absolutes);
1831 $absolutes[] = $part;
1835 $path = '/' . implode('/', $absolutes);
1838 // Relative scheme case (//host/path)
1839 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1840 $baseParts['path'] = $path;
1841 unset($baseParts['query']);
1842 unset($baseParts['fragment']);
1844 return Network::unparseURL($baseParts);
1848 * Check for feed contact
1850 * @param string $url Profile link
1851 * @param boolean $probe Do a probe if the page contains a feed link
1853 * @return array feed data
1854 * @throws HTTPException\InternalServerErrorException
1856 private static function feed($url, $probe = true)
1858 $curlResult = Network::curl($url);
1859 if ($curlResult->isTimeout()) {
1860 self::$istimeout = true;
1863 $feed = $curlResult->getBody();
1864 $feed_data = Feed::import($feed);
1871 $feed_url = self::getFeedLink($url, $feed);
1877 return self::feed($feed_url, false);
1880 if (!empty($feed_data["header"]["author-name"])) {
1881 $data["name"] = $feed_data["header"]["author-name"];
1884 if (!empty($feed_data["header"]["author-nick"])) {
1885 $data["nick"] = $feed_data["header"]["author-nick"];
1888 if (!empty($feed_data["header"]["author-avatar"])) {
1889 $data["photo"] = $feed_data["header"]["author-avatar"];
1892 if (!empty($feed_data["header"]["author-id"])) {
1893 $data["alias"] = $feed_data["header"]["author-id"];
1896 $data["url"] = $url;
1897 $data["poll"] = $url;
1899 if (!empty($feed_data["header"]["author-link"])) {
1900 $data["baseurl"] = $feed_data["header"]["author-link"];
1902 $data["baseurl"] = $data["url"];
1905 $data["network"] = Protocol::FEED;
1911 * Check for mail contact
1913 * @param string $uri Profile link
1914 * @param integer $uid User ID
1916 * @return array mail data
1917 * @throws \Exception
1919 private static function mail($uri, $uid)
1921 if (!Network::isEmailDomainValid($uri)) {
1929 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1931 $condition = ["`uid` = ? AND `server` != ''", $uid];
1932 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1933 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1935 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1939 $mailbox = Email::constructMailboxName($mailacct);
1941 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1942 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1947 $msgs = Email::poll($mbox, $uri);
1948 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1950 if (!count($msgs)) {
1954 $phost = substr($uri, strpos($uri, '@') + 1);
1957 $data["addr"] = $uri;
1958 $data["network"] = Protocol::MAIL;
1959 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1960 $data["nick"] = $data["name"];
1961 $data["photo"] = Network::lookupAvatarByEmail($uri);
1962 $data["url"] = 'mailto:'.$uri;
1963 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1964 $data["poll"] = 'email ' . Strings::getRandomHex();
1966 $x = Email::messageMeta($mbox, $msgs[0]);
1967 if (stristr($x[0]->from, $uri)) {
1968 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1969 } elseif (stristr($x[0]->to, $uri)) {
1970 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1973 foreach ($adr as $feadr) {
1974 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1975 &&(strcasecmp($feadr->host, $phost) == 0)
1976 && (strlen($feadr->personal))
1978 $personal = imap_mime_header_decode($feadr->personal);
1980 foreach ($personal as $perspart) {
1981 if ($perspart->charset != "default") {
1982 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1984 $data["name"] .= $perspart->text;
1988 $data["name"] = Strings::escapeTags($data["name"]);
1992 if (!empty($mbox)) {
1999 * Mix two paths together to possibly fix missing parts
2001 * @param string $avatar Path to the avatar
2002 * @param string $base Another path that is hopefully complete
2004 * @return string fixed avatar path
2005 * @throws \Exception
2007 public static function fixAvatar($avatar, $base)
2009 $base_parts = parse_url($base);
2011 // Remove all parts that could create a problem
2012 unset($base_parts['path']);
2013 unset($base_parts['query']);
2014 unset($base_parts['fragment']);
2016 $avatar_parts = parse_url($avatar);
2019 $parts = array_merge($base_parts, $avatar_parts);
2021 // And put them together again
2022 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
2023 $host = isset($parts['host']) ? $parts['host'] : '';
2024 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
2025 $path = isset($parts['path']) ? $parts['path'] : '';
2026 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
2027 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
2029 $fixed = $scheme.$host.$port.$path.$query.$fragment;
2031 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);