3 * @copyright Copyright (C) 2010-2022, the Friendica project
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;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
33 use Friendica\Model\Contact;
34 use Friendica\Model\GServer;
35 use Friendica\Model\Profile;
36 use Friendica\Model\User;
37 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
38 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
39 use Friendica\Protocol\ActivityNamespace;
40 use Friendica\Protocol\ActivityPub;
41 use Friendica\Protocol\Email;
42 use Friendica\Protocol\Feed;
43 use Friendica\Util\Crypto;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\Network;
46 use Friendica\Util\Strings;
47 use Friendica\Util\XML;
48 use GuzzleHttp\Psr7\Uri;
51 * This class contain functions for probing URL
55 const WEBFINGER = '/.well-known/webfinger?resource={uri}';
57 private static $baseurl;
58 private static $istimeout;
61 * Remove stuff from an URI that doesn't belong there
63 * @param string $rawUri
64 * @return string Cleaned URI
66 public static function cleanURI(string $rawUri): string
68 $rawUri = Network::convertToIdn($rawUri);
70 // At first remove leading and trailing junk
71 $rawUri = trim($rawUri, "@#?:/ \t\n\r\0\x0B");
73 $uri = new Uri($rawUri);
74 if (!$uri->getScheme()) {
75 return $uri->__toString();
78 // Remove the URL fragment, since these shouldn't be part of any profile URL
79 $uri = $uri->withFragment('');
81 return $uri->__toString();
85 * Rearrange the array so that it always has the same order
87 * @param array $data Unordered data
89 * @return array Ordered data
91 private static function rearrangeData($data)
93 $fields = ["name", "nick", "guid", "url", "addr", "alias", "photo", "header",
94 "account-type", "community", "keywords", "location", "about", "xmpp", "matrix",
95 "hide", "batch", "notify", "poll", "request", "confirm", "subscribe", "poco",
96 "following", "followers", "inbox", "outbox", "sharedinbox",
97 "priority", "network", "pubkey", "manually-approve", "baseurl", "gsid"];
99 $numeric_fields = ["gsid", "hide", "account-type", "manually-approve"];
102 foreach ($fields as $field) {
103 if (isset($data[$field])) {
104 if (in_array($field, $numeric_fields)) {
105 $newdata[$field] = (int)$data[$field];
107 $newdata[$field] = $data[$field];
109 } elseif (!in_array($field, $numeric_fields)) {
110 $newdata[$field] = "";
112 $newdata[$field] = null;
116 // We don't use the "priority" field anymore and replace it with a dummy.
117 $newdata["priority"] = 0;
123 * Check if the hostname belongs to the own server
125 * @param string $host The hostname that is to be checked
127 * @return bool Does the testes hostname belongs to the own server?
129 private static function ownHost($host)
131 $own_host = DI::baseUrl()->getHostname();
133 $parts = parse_url($host);
135 if (!isset($parts['scheme'])) {
136 $parts = parse_url('http://'.$host);
139 if (!isset($parts['host'])) {
142 return $parts['host'] == $own_host;
146 * Probes for webfinger path via "host-meta"
148 * We have to check if the servers in the future still will offer this.
149 * It seems as if it was dropped from the standard.
151 * @param string $host The host part of an url
153 * @return array with template and type of the webfinger template for JSON or XML
154 * @throws HTTPException\InternalServerErrorException
156 private static function hostMeta($host)
158 // Reset the static variable
161 // Handles the case when the hostname contains the scheme
162 if (!parse_url($host, PHP_URL_SCHEME)) {
163 $ssl_url = "https://" . $host . "/.well-known/host-meta";
164 $url = "http://" . $host . "/.well-known/host-meta";
166 $ssl_url = $host . "/.well-known/host-meta";
170 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
172 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
175 $curlResult = DI::httpClient()->get($ssl_url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
176 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
177 if ($curlResult->isSuccess()) {
178 $xml = $curlResult->getBody();
179 $xrd = XML::parseString($xml, true);
181 $host_url = 'https://' . $host;
185 } elseif ($curlResult->isTimeout()) {
186 Logger::info('Probing timeout', ['url' => $ssl_url]);
187 self::$istimeout = true;
191 if (!is_object($xrd) && !empty($url)) {
192 $curlResult = DI::httpClient()->get($url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
193 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
194 if ($curlResult->isTimeout()) {
195 Logger::info('Probing timeout', ['url' => $url]);
196 self::$istimeout = true;
198 } elseif ($connection_error && $ssl_connection_error) {
199 self::$istimeout = true;
203 $xml = $curlResult->getBody();
204 $xrd = XML::parseString($xml, true);
205 $host_url = 'http://'.$host;
207 if (!is_object($xrd)) {
208 Logger::info('No xrd object found', ['host' => $host]);
212 $links = XML::elementToArray($xrd);
213 if (!isset($links["xrd"]["link"])) {
214 Logger::info('No xrd data found', ['host' => $host]);
220 foreach ($links["xrd"]["link"] as $value => $link) {
221 if (!empty($link["@attributes"])) {
222 $attributes = $link["@attributes"];
223 } elseif ($value == "@attributes") {
229 if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
230 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
232 $lrdd[$type] = $attributes["template"];
236 if (Network::isUrlBlocked($host_url)) {
237 Logger::info('Domain is blocked', ['url' => $host]);
241 self::$baseurl = $host_url;
243 Logger::info('Probing successful', ['host' => $host]);
249 * Check an URI for LRDD data
251 * @param string $uri Address that should be probed
253 * @return array uri data
254 * @throws HTTPException\InternalServerErrorException
256 public static function lrdd(string $uri)
258 $data = self::getWebfingerArray($uri);
262 $webfinger = $data['webfinger'];
264 if (empty($webfinger["links"])) {
265 Logger::info('No webfinger links found', ['uri' => $uri]);
271 foreach ($webfinger["links"] as $link) {
272 $data[] = ["@attributes" => $link];
275 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
276 foreach ($webfinger["aliases"] as $alias) {
277 $data[] = ["@attributes" =>
287 * Fetch information (protocol endpoints and user information) about a given uri
289 * @param string $uri Address that should be probed
290 * @param string $network Test for this specific network
291 * @param integer $uid User ID for the probe (only used for mails)
292 * @param boolean $cache Use cached values?
294 * @return array uri data
295 * @throws HTTPException\InternalServerErrorException
296 * @throws \ImagickException
298 public static function uri($uri, $network = '', $uid = -1)
300 // Local profiles aren't probed via network
301 if (empty($network) && Contact::isLocal($uri)) {
302 $data = self::localProbe($uri);
312 if (empty($network) || ($network == Protocol::ACTIVITYPUB)) {
313 $ap_profile = ActivityPub::probeProfile($uri);
318 self::$istimeout = false;
320 if ($network != Protocol::ACTIVITYPUB) {
321 $data = self::detect($uri, $network, $uid, $ap_profile);
322 if (!is_array($data)) {
325 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
327 } elseif (!empty($ap_profile)) {
328 $ap_profile['batch'] = '';
329 $data = array_merge($ap_profile, $data);
335 if (!isset($data['url'])) {
339 if (empty($data['photo'])) {
340 $data['photo'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
343 if (empty($data['name'])) {
344 if (!empty($data['nick'])) {
345 $data['name'] = $data['nick'];
348 if (empty($data['name'])) {
349 $data['name'] = $data['url'];
353 if (empty($data['nick'])) {
354 $data['nick'] = strtolower($data['name']);
356 if (strpos($data['nick'], ' ')) {
357 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
361 if (!empty($data['baseurl']) && empty($data['gsid'])) {
362 $data['gsid'] = GServer::getID($data['baseurl']);
365 if (empty($data['network'])) {
366 $data['network'] = Protocol::PHANTOM;
369 // Ensure that local connections always are DFRN
370 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
371 $data['network'] = Protocol::DFRN;
374 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
375 $data['hide'] = self::getHideStatus($data['url']);
378 return self::rearrangeData($data);
383 * Fetches the "hide" status from the profile
385 * @param string $url URL of the profile
387 * @return boolean "hide" status
389 private static function getHideStatus($url)
391 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::CONTENT_LENGTH => 1000000]);
392 if (!$curlResult->isSuccess()) {
396 // If it isn't a HTML file then exit
397 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
401 $body = $curlResult->getBody();
406 $doc = new DOMDocument();
407 @$doc->loadHTML($body);
409 $xpath = new DOMXPath($doc);
411 $list = $xpath->query('//meta[@name]');
412 foreach ($list as $node) {
414 if ($node->attributes->length) {
415 foreach ($node->attributes as $attribute) {
416 $meta_tag[$attribute->name] = $attribute->value;
420 if (empty($meta_tag['content'])) {
424 $content = strtolower(trim($meta_tag['content']));
426 switch (strtolower(trim($meta_tag['name']))) {
427 case 'dfrn-global-visibility':
428 if ($content == 'false') {
433 if (strpos($content, 'noindex') !== false) {
444 * Fetch the "subscribe" and add it to the result
446 * @param array $result
447 * @param array $webfinger
448 * @return array result
450 private static function getSubscribeLink(array $result, array $webfinger)
452 if (empty($webfinger['links'])) {
456 foreach ($webfinger['links'] as $link) {
457 if (!empty($link['template']) && ($link['rel'] === ActivityNamespace::OSTATUSSUB)) {
458 $result['subscribe'] = $link['template'];
466 * Get webfinger data from a given URI
470 * @throws HTTPException\InternalServerErrorException
472 private static function getWebfingerArray(string $uri): array
474 $parts = parse_url($uri);
476 if (!empty($parts['scheme']) && !empty($parts['host'])) {
477 $host = $parts['host'];
478 if (!empty($parts['port'])) {
479 $host .= ':' . $parts['port'];
482 $baseurl = $parts['scheme'] . '://' . $host;
487 $path_parts = explode('/', trim($parts['path'] ?? '', '/'));
488 if (!empty($path_parts)) {
489 $nick = ltrim(end($path_parts), '@');
490 $addr = $nick . '@' . $host;
493 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
494 if (empty($webfinger)) {
495 $lrdd = self::hostMeta($host);
498 if (empty($webfinger) && empty($lrdd)) {
499 while (empty($lrdd) && empty($webfinger) && (sizeof($path_parts) > 1)) {
500 $host .= '/' . array_shift($path_parts);
501 $baseurl = $parts['scheme'] . '://' . $host;
504 $addr = $nick . '@' . $host;
507 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
508 if (empty($webfinger)) {
509 $lrdd = self::hostMeta($host);
513 if (empty($lrdd) && empty($webfinger)) {
517 } elseif (strstr($uri, '@')) {
518 // Remove "acct:" from the URI
519 $uri = str_replace('acct:', '', $uri);
521 $host = substr($uri, strpos($uri, '@') + 1);
522 $nick = substr($uri, 0, strpos($uri, '@'));
525 $webfinger = self::getWebfinger('https://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
526 if (self::$istimeout) {
530 if (empty($webfinger)) {
531 $webfinger = self::getWebfinger('http://' . $host . self::WEBFINGER, HttpClientAccept::JRD_JSON, $uri, $addr);
532 if (self::$istimeout) {
536 $baseurl = 'https://' . $host;
539 if (empty($webfinger)) {
540 $lrdd = self::hostMeta($host);
541 if (self::$istimeout) {
544 $baseurl = self::$baseurl;
546 $baseurl = 'http://' . $host;
549 Logger::info('URI was not detectable', ['uri' => $uri]);
553 if (empty($webfinger)) {
554 foreach ($lrdd as $type => $template) {
559 $webfinger = self::getWebfinger($template, $type, $uri, $addr);
563 if (empty($webfinger)) {
567 if ($webfinger['detected'] == $addr) {
568 $webfinger['nick'] = $nick;
569 $webfinger['addr'] = $addr;
572 $webfinger['baseurl'] = $baseurl;
578 * Perform network request for webfinger data
580 * @param string $template
581 * @param string $type
583 * @param string $addr
584 * @return array webfinger results
586 private static function getWebfinger(string $template, string $type, string $uri, string $addr)
588 if (Network::isUrlBlocked($template)) {
589 Logger::info('Domain is blocked', ['url' => $template]);
593 // First try the address because this is the primary purpose of webfinger
596 $path = str_replace('{uri}', urlencode("acct:" . $addr), $template);
597 $webfinger = self::webfinger($path, $type);
598 if (self::$istimeout) {
604 if (empty($webfinger) && $uri != $addr) {
606 $path = str_replace('{uri}', urlencode($uri), $template);
607 $webfinger = self::webfinger($path, $type);
608 if (self::$istimeout) {
613 if (empty($webfinger)) {
617 return ['webfinger' => $webfinger, 'detected' => $detected];
621 * Fetch information (protocol endpoints and user information) about a given uri
623 * This function is only called by the "uri" function that adds caching and rearranging of data.
625 * @param string $uri Address that should be probed
626 * @param string $network Test for this specific network
627 * @param integer $uid User ID for the probe (only used for mails)
628 * @param array $ap_profile Previously probed AP profile
630 * @return array uri data
631 * @throws HTTPException\InternalServerErrorException
633 private static function detect(string $uri, string $network, int $uid, array $ap_profile)
637 'network' => $network,
642 Hook::callAll('probe_detect', $hookData);
644 if (isset($hookData['result'])) {
645 return is_array($hookData['result']) ? $hookData['result'] : [];
648 $parts = parse_url($uri);
649 if (empty($parts['scheme']) && empty($parts['host']) && !strstr($parts['path'], '@')) {
650 Logger::info('URI was not detectable', ['uri' => $uri]);
654 // If the URI starts with "mailto:" then jump directly to the mail detection
655 if (strpos($uri, 'mailto:') !== false) {
656 $uri = str_replace('mailto:', '', $uri);
657 return self::mail($uri, $uid);
660 if ($network == Protocol::MAIL) {
661 return self::mail($uri, $uid);
664 Logger::info('Probing start', ['uri' => $uri]);
666 if (!empty($ap_profile['addr']) && ($ap_profile['addr'] != $uri)) {
667 $data = self::getWebfingerArray($ap_profile['addr']);
671 $data = self::getWebfingerArray($uri);
675 if (!empty($parts['scheme'])) {
676 return self::feed($uri);
677 } elseif (!empty($uid)) {
678 return self::mail($uri, $uid);
684 $webfinger = $data['webfinger'];
685 $nick = $data['nick'] ?? '';
686 $addr = $data['addr'] ?? '';
687 $baseurl = $data['baseurl'] ?? '';
691 if (in_array($network, ["", Protocol::DFRN])) {
692 $result = self::dfrn($webfinger);
694 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
695 $result = self::diaspora($webfinger);
697 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
698 $result = self::ostatus($webfinger);
700 if (in_array($network, ['', Protocol::ZOT])) {
701 $result = self::zot($webfinger, $result, $baseurl);
703 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
704 $result = self::pumpio($webfinger, $addr);
706 if (empty($result['network']) && empty($ap_profile['network']) || ($network == Protocol::FEED)) {
707 $result = self::feed($uri);
709 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
710 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
711 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
712 $result["nick"] = $nick;
715 if (empty($result["addr"]) && ($addr != "")) {
716 $result["addr"] = $addr;
720 $result = self::getSubscribeLink($result, $webfinger);
722 if (empty($result["network"])) {
723 $result["network"] = Protocol::PHANTOM;
726 if (empty($result['baseurl']) && !empty($baseurl)) {
727 $result['baseurl'] = $baseurl;
730 if (empty($result["url"])) {
731 $result["url"] = $uri;
734 Logger::info('Probing done', ['uri' => $uri, 'network' => $result["network"]]);
740 * Check for Zot contact
742 * @param array $webfinger Webfinger data
743 * @param array $data previously probed data
745 * @return array Zot data
746 * @throws HTTPException\InternalServerErrorException
748 private static function zot($webfinger, $data, $baseurl)
750 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
751 foreach ($webfinger["aliases"] as $alias) {
752 if (substr($alias, 0, 5) == 'acct:') {
753 $data["addr"] = substr($alias, 5);
758 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
759 $data["addr"] = substr($webfinger["subject"], 5);
763 foreach ($webfinger['links'] as $link) {
764 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
765 $zot_url = $link['href'];
769 if (empty($zot_url) && !empty($data['addr']) && !empty($baseurl)) {
770 $condition = ['nurl' => Strings::normaliseLink($baseurl), 'platform' => ['hubzilla']];
771 if (!DBA::exists('gserver', $condition)) {
774 $zot_url = $baseurl . '/.well-known/zot-info?address=' . $data['addr'];
777 if (empty($zot_url)) {
781 $data = self::pollZot($zot_url, $data);
783 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
784 foreach ($webfinger['aliases'] as $alias) {
785 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
786 $data['alias'] = $alias;
794 public static function pollZot($url, $data)
796 $curlResult = DI::httpClient()->get($url, HttpClientAccept::JSON);
797 if ($curlResult->isTimeout()) {
800 $content = $curlResult->getBody();
805 $json = json_decode($content, true);
806 if (!is_array($json)) {
810 if (empty($data['network'])) {
811 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
812 $data['network'] = Protocol::ZOT;
813 } elseif (!isset($json['protocols'])) {
814 $data['network'] = Protocol::ZOT;
818 if (!empty($json['guid']) && empty($data['guid'])) {
819 $data['guid'] = $json['guid'];
821 if (!empty($json['key']) && empty($data['pubkey'])) {
822 $data['pubkey'] = $json['key'];
824 if (!empty($json['name'])) {
825 $data['name'] = $json['name'];
827 if (!empty($json['photo'])) {
828 $data['photo'] = $json['photo'];
829 if (!empty($json['photo_updated'])) {
830 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
833 if (!empty($json['address'])) {
834 $data['addr'] = $json['address'];
836 if (!empty($json['url'])) {
837 $data['url'] = $json['url'];
839 if (!empty($json['connections_url'])) {
840 $data['poco'] = $json['connections_url'];
842 if (isset($json['searchable'])) {
843 $data['hide'] = !$json['searchable'];
845 if (!empty($json['public_forum'])) {
846 $data['community'] = $json['public_forum'];
847 $data['account-type'] = User::PAGE_FLAGS_COMMUNITY;
850 if (!empty($json['profile'])) {
851 $profile = $json['profile'];
852 if (!empty($profile['description'])) {
853 $data['about'] = $profile['description'];
855 if (!empty($profile['keywords'])) {
856 $keywords = implode(', ', $profile['keywords']);
857 if (!empty($keywords)) {
858 $data['keywords'] = $keywords;
863 if (!empty($profile['region'])) {
864 $loc['region'] = $profile['region'];
866 if (!empty($profile['country'])) {
867 $loc['country-name'] = $profile['country'];
869 $location = Profile::formatLocation($loc);
870 if (!empty($location)) {
871 $data['location'] = $location;
879 * Perform a webfinger request.
881 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
883 * @param string $url Address that should be probed
884 * @param string $type type
886 * @return array webfinger data
887 * @throws HTTPException\InternalServerErrorException
889 public static function webfinger($url, $type)
891 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
893 $curlResult = DI::httpClient()->get($url, $type, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
894 if ($curlResult->isTimeout()) {
895 self::$istimeout = true;
898 $data = $curlResult->getBody();
900 $webfinger = json_decode($data, true);
901 if (!empty($webfinger)) {
902 if (!isset($webfinger["links"])) {
903 Logger::info('No json webfinger links', ['url' => $url]);
909 // If it is not JSON, maybe it is XML
910 $xrd = XML::parseString($data, true);
911 if (!is_object($xrd)) {
912 Logger::info('No webfinger data retrievable', ['url' => $url]);
916 $xrd_arr = XML::elementToArray($xrd);
917 if (!isset($xrd_arr["xrd"]["link"])) {
918 Logger::info('No XML webfinger links', ['url' => $url]);
924 if (!empty($xrd_arr["xrd"]["subject"])) {
925 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
928 if (!empty($xrd_arr["xrd"]["alias"])) {
929 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
932 $webfinger["links"] = [];
934 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
935 if (!empty($data["@attributes"])) {
936 $attributes = $data["@attributes"];
937 } elseif ($value == "@attributes") {
943 $webfinger["links"][] = $attributes;
949 * Poll the Friendica specific noscrape page.
951 * "noscrape" is a faster alternative to fetch the data from the hcard.
952 * This functionality was originally created for the directory.
954 * @param string $noscrape_url Link to the noscrape page
955 * @param array $data The already fetched data
957 * @return array noscrape data
958 * @throws HTTPException\InternalServerErrorException
960 private static function pollNoscrape($noscrape_url, $data)
962 $curlResult = DI::httpClient()->get($noscrape_url, HttpClientAccept::JSON);
963 if ($curlResult->isTimeout()) {
964 self::$istimeout = true;
967 $content = $curlResult->getBody();
969 Logger::info('Empty body', ['url' => $noscrape_url]);
973 $json = json_decode($content, true);
974 if (!is_array($json)) {
975 Logger::info('No json data', ['url' => $noscrape_url]);
979 if (!empty($json["fn"])) {
980 $data["name"] = $json["fn"];
983 if (!empty($json["addr"])) {
984 $data["addr"] = $json["addr"];
987 if (!empty($json["nick"])) {
988 $data["nick"] = $json["nick"];
991 if (!empty($json["guid"])) {
992 $data["guid"] = $json["guid"];
995 if (!empty($json["comm"])) {
996 $data["community"] = $json["comm"];
999 if (!empty($json["tags"])) {
1000 $keywords = implode(", ", $json["tags"]);
1001 if ($keywords != "") {
1002 $data["keywords"] = $keywords;
1006 $location = Profile::formatLocation($json);
1008 $data["location"] = $location;
1011 if (!empty($json["about"])) {
1012 $data["about"] = $json["about"];
1015 if (!empty($json["xmpp"])) {
1016 $data["xmpp"] = $json["xmpp"];
1019 if (!empty($json["matrix"])) {
1020 $data["matrix"] = $json["matrix"];
1023 if (!empty($json["key"])) {
1024 $data["pubkey"] = $json["key"];
1027 if (!empty($json["photo"])) {
1028 $data["photo"] = $json["photo"];
1031 if (!empty($json["dfrn-request"])) {
1032 $data["request"] = $json["dfrn-request"];
1035 if (!empty($json["dfrn-confirm"])) {
1036 $data["confirm"] = $json["dfrn-confirm"];
1039 if (!empty($json["dfrn-notify"])) {
1040 $data["notify"] = $json["dfrn-notify"];
1043 if (!empty($json["dfrn-poll"])) {
1044 $data["poll"] = $json["dfrn-poll"];
1047 if (isset($json["hide"])) {
1048 $data["hide"] = (bool)$json["hide"];
1050 $data["hide"] = false;
1057 * Check for valid DFRN data
1059 * @param array $data DFRN data
1061 * @return int Number of errors
1063 public static function validDfrn($data)
1066 if (!isset($data['key'])) {
1069 if (!isset($data['dfrn-request'])) {
1072 if (!isset($data['dfrn-confirm'])) {
1075 if (!isset($data['dfrn-notify'])) {
1078 if (!isset($data['dfrn-poll'])) {
1085 * Fetch data from a DFRN profile page and via "noscrape"
1087 * @param string $profile_link Link to the profile page
1089 * @return array profile data
1090 * @throws HTTPException\InternalServerErrorException
1091 * @throws \ImagickException
1093 public static function profile($profile_link)
1097 Logger::info('Check profile', ['link' => $profile_link]);
1099 // Fetch data via noscrape - this is faster
1100 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1101 $data = self::pollNoscrape($noscrape_url, $data);
1103 if (!isset($data["notify"])
1104 || !isset($data["confirm"])
1105 || !isset($data["request"])
1106 || !isset($data["poll"])
1107 || !isset($data["name"])
1108 || !isset($data["photo"])
1110 $data = self::pollHcard($profile_link, $data, true);
1115 if (empty($data["addr"]) || empty($data["nick"])) {
1116 $probe_data = self::uri($profile_link);
1117 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1118 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1121 $prof_data["addr"] = $data["addr"];
1122 $prof_data["nick"] = $data["nick"];
1123 $prof_data["dfrn-request"] = $data['request'] ?? null;
1124 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1125 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1126 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1127 $prof_data["photo"] = $data['photo'] ?? null;
1128 $prof_data["fn"] = $data['name'] ?? null;
1129 $prof_data["key"] = $data['pubkey'] ?? null;
1131 Logger::debug('Result', ['link' => $profile_link, 'data' => $prof_data]);
1137 * Check for DFRN contact
1139 * @param array $webfinger Webfinger data
1141 * @return array DFRN data
1142 * @throws HTTPException\InternalServerErrorException
1144 private static function dfrn($webfinger)
1148 // The array is reversed to take into account the order of preference for same-rel links
1149 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1150 foreach (array_reverse($webfinger["links"]) as $link) {
1151 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1152 $data["network"] = Protocol::DFRN;
1153 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1154 $data["poll"] = $link["href"];
1155 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1156 $data["url"] = $link["href"];
1157 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1158 $hcard_url = $link["href"];
1159 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1160 $data["poco"] = $link["href"];
1161 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1162 $data["photo"] = $link["href"];
1163 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1164 $data["baseurl"] = trim($link["href"], '/');
1165 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1166 $data["guid"] = $link["href"];
1167 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1168 $data["pubkey"] = base64_decode($link["href"]);
1170 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1171 if (strstr($data["pubkey"], 'RSA ')) {
1172 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1177 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1178 foreach ($webfinger["aliases"] as $alias) {
1179 if (empty($data["url"]) && !strstr($alias, "@")) {
1180 $data["url"] = $alias;
1181 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1182 $data["alias"] = $alias;
1183 } elseif (substr($alias, 0, 5) == 'acct:') {
1184 $data["addr"] = substr($alias, 5);
1189 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1190 $data["addr"] = substr($webfinger["subject"], 5);
1193 if (!isset($data["network"]) || ($hcard_url == "")) {
1197 // Fetch data via noscrape - this is faster
1198 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1199 $data = self::pollNoscrape($noscrape_url, $data);
1201 if (isset($data["notify"])
1202 && isset($data["confirm"])
1203 && isset($data["request"])
1204 && isset($data["poll"])
1205 && isset($data["name"])
1206 && isset($data["photo"])
1211 $data = self::pollHcard($hcard_url, $data, true);
1217 * Poll the hcard page (Diaspora and Friendica specific)
1219 * @param string $hcard_url Link to the hcard page
1220 * @param array $data The already fetched data
1221 * @param boolean $dfrn Poll DFRN specific data
1223 * @return array hcard data
1224 * @throws HTTPException\InternalServerErrorException
1226 private static function pollHcard($hcard_url, $data, $dfrn = false)
1228 $curlResult = DI::httpClient()->get($hcard_url, HttpClientAccept::HTML);
1229 if ($curlResult->isTimeout()) {
1230 self::$istimeout = true;
1233 $content = $curlResult->getBody();
1234 if (empty($content)) {
1238 $doc = new DOMDocument();
1239 if (!@$doc->loadHTML($content)) {
1243 $xpath = new DomXPath($doc);
1245 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1246 if (!is_object($vcards)) {
1250 if (!isset($data["baseurl"])) {
1251 $data["baseurl"] = "";
1254 if ($vcards->length > 0) {
1255 $vcard = $vcards->item(0);
1257 // We have to discard the guid from the hcard in favour of the guid from lrdd
1258 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1259 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1260 if (($search->length > 0) && empty($data["guid"])) {
1261 $data["guid"] = $search->item(0)->nodeValue;
1264 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1265 if ($search->length > 0) {
1266 $data["nick"] = $search->item(0)->nodeValue;
1269 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1270 if ($search->length > 0) {
1271 $data["name"] = $search->item(0)->nodeValue;
1274 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1275 if ($search->length > 0) {
1276 $data["searchable"] = $search->item(0)->nodeValue;
1279 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1280 if ($search->length > 0) {
1281 $data["pubkey"] = $search->item(0)->nodeValue;
1282 if (strstr($data["pubkey"], 'RSA ')) {
1283 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1287 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1288 if ($search->length > 0) {
1289 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1294 if (!empty($vcard)) {
1295 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1296 foreach ($photos as $photo) {
1298 foreach ($photo->attributes as $attribute) {
1299 $attr[$attribute->name] = trim($attribute->value);
1302 if (isset($attr["src"]) && isset($attr["width"])) {
1303 $avatar[$attr["width"]] = $attr["src"];
1306 // We don't have a width. So we just take everything that we got.
1307 // This is a Hubzilla workaround which doesn't send a width.
1308 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1309 $avatar[] = $attr["src"];
1314 if (sizeof($avatar)) {
1316 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1320 // Poll DFRN specific data
1321 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1322 if ($search->length > 0) {
1323 foreach ($search as $link) {
1324 //$data["request"] = $search->item(0)->nodeValue;
1326 foreach ($link->attributes as $attribute) {
1327 $attr[$attribute->name] = trim($attribute->value);
1330 $data[substr($attr["rel"], 5)] = $attr["href"];
1334 // Older Friendica versions had used the "uid" field differently than newer versions
1335 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1336 unset($data["guid"]);
1345 * Check for Diaspora contact
1347 * @param array $webfinger Webfinger data
1349 * @return array Diaspora data
1350 * @throws HTTPException\InternalServerErrorException
1352 private static function diaspora($webfinger)
1357 // The array is reversed to take into account the order of preference for same-rel links
1358 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1359 foreach (array_reverse($webfinger["links"]) as $link) {
1360 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1361 $hcard_url = $link["href"];
1362 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1363 $data["baseurl"] = trim($link["href"], '/');
1364 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1365 $data["guid"] = $link["href"];
1366 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1367 $data["url"] = $link["href"];
1368 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && empty($link["type"]) && !empty($link["href"])) {
1369 $profile_url = $link["href"];
1370 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1371 $data["poll"] = $link["href"];
1372 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1373 $data["poco"] = $link["href"];
1374 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1375 $data["notify"] = $link["href"];
1376 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1377 $data["pubkey"] = base64_decode($link["href"]);
1379 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1380 if (strstr($data["pubkey"], 'RSA ')) {
1381 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1386 if (empty($data["url"]) && !empty($profile_url)) {
1387 $data["url"] = $profile_url;
1390 if (empty($data["url"]) || empty($hcard_url)) {
1394 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1395 foreach ($webfinger["aliases"] as $alias) {
1396 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1397 $data["alias"] = $alias;
1398 } elseif (substr($alias, 0, 5) == 'acct:') {
1399 $data["addr"] = substr($alias, 5);
1404 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1405 $data["addr"] = substr($webfinger["subject"], 5);
1408 // Fetch further information from the hcard
1409 $data = self::pollHcard($hcard_url, $data);
1415 if (!empty($data["url"])
1416 && !empty($data["guid"])
1417 && !empty($data["baseurl"])
1418 && !empty($data["pubkey"])
1419 && !empty($hcard_url)
1421 $data["network"] = Protocol::DIASPORA;
1422 $data["manually-approve"] = false;
1424 // The Diaspora handle must always be lowercase
1425 if (!empty($data["addr"])) {
1426 $data["addr"] = strtolower($data["addr"]);
1429 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1430 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1431 $data["batch"] = $data["baseurl"] . "/receive/public";
1440 * Check for OStatus contact
1442 * @param array $webfinger Webfinger data
1443 * @param bool $short Short detection mode
1445 * @return array|bool OStatus data or "false" on error or "true" on short mode
1446 * @throws HTTPException\InternalServerErrorException
1448 private static function ostatus($webfinger, $short = false)
1452 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1453 foreach ($webfinger["aliases"] as $alias) {
1454 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1455 $data["addr"] = str_replace('acct:', '', $alias);
1460 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1461 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1463 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1466 if (!empty($webfinger["links"])) {
1467 // The array is reversed to take into account the order of preference for same-rel links
1468 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1469 foreach (array_reverse($webfinger["links"]) as $link) {
1470 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1471 && (($link["type"] ?? "") == "text/html")
1472 && ($link["href"] != "")
1474 $data["url"] = $data["alias"] = $link["href"];
1475 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1476 $data["notify"] = $link["href"];
1477 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1478 $data["poll"] = $link["href"];
1479 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1480 $pubkey = $link["href"];
1482 if (substr($pubkey, 0, 5) === 'data:') {
1483 if (strstr($pubkey, ',')) {
1484 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1486 $pubkey = substr($pubkey, 5);
1488 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1489 $curlResult = DI::httpClient()->get($pubkey, HttpClientAccept::MAGIC_KEY);
1490 if ($curlResult->isTimeout()) {
1491 self::$istimeout = true;
1492 return $short ? false : [];
1494 Logger::debug('Fetched public key', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $pubkey]);
1495 $pubkey = $curlResult->getBody();
1498 $key = explode(".", $pubkey);
1500 if (sizeof($key) >= 3) {
1501 $m = Strings::base64UrlDecode($key[1]);
1502 $e = Strings::base64UrlDecode($key[2]);
1503 $data["pubkey"] = Crypto::meToPem($m, $e);
1509 if (isset($data["notify"]) && isset($data["pubkey"])
1510 && isset($data["poll"])
1511 && isset($data["url"])
1513 $data["network"] = Protocol::OSTATUS;
1514 $data["manually-approve"] = false;
1516 return $short ? false : [];
1523 // Fetch all additional data from the feed
1524 $curlResult = DI::httpClient()->get($data["poll"], HttpClientAccept::FEED_XML);
1525 if ($curlResult->isTimeout()) {
1526 self::$istimeout = true;
1529 $feed = $curlResult->getBody();
1530 $feed_data = Feed::import($feed);
1535 if (!empty($feed_data["header"]["author-name"])) {
1536 $data["name"] = $feed_data["header"]["author-name"];
1538 if (!empty($feed_data["header"]["author-nick"])) {
1539 $data["nick"] = $feed_data["header"]["author-nick"];
1541 if (!empty($feed_data["header"]["author-avatar"])) {
1542 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1544 if (!empty($feed_data["header"]["author-id"])) {
1545 $data["alias"] = $feed_data["header"]["author-id"];
1547 if (!empty($feed_data["header"]["author-location"])) {
1548 $data["location"] = $feed_data["header"]["author-location"];
1550 if (!empty($feed_data["header"]["author-about"])) {
1551 $data["about"] = $feed_data["header"]["author-about"];
1553 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1554 // So we take the value that we just fetched, although the other one worked as well
1555 if (!empty($feed_data["header"]["author-link"])) {
1556 $data["url"] = $feed_data["header"]["author-link"];
1559 if ($data["url"] == $data["alias"]) {
1560 $data["alias"] = '';
1563 /// @todo Fetch location and "about" from the feed as well
1568 * Fetch data from a pump.io profile page
1570 * @param string $profile_link Link to the profile page
1572 * @return array profile data
1574 private static function pumpioProfileData($profile_link)
1576 $curlResult = DI::httpClient()->get($profile_link, HttpClientAccept::HTML);
1577 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
1581 $doc = new DOMDocument();
1582 if (!@$doc->loadHTML($curlResult->getBody())) {
1586 $xpath = new DomXPath($doc);
1590 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1592 if ($data["name"] == '') {
1593 // This is ugly - but pump.io doesn't seem to know a better way for it
1594 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1595 $pos = strpos($data["name"], chr(10));
1597 $data["name"] = trim(substr($data["name"], 0, $pos));
1601 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1603 if ($data["location"] == '') {
1604 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1607 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1609 if ($data["about"] == '') {
1610 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1613 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1615 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1618 foreach ($avatar->attributes as $attribute) {
1619 if ($attribute->name == "src") {
1620 $data["photo"] = trim($attribute->value);
1629 * Check for pump.io contact
1631 * @param array $webfinger Webfinger data
1632 * @param string $addr
1633 * @return array pump.io data
1635 private static function pumpio($webfinger, $addr)
1638 // The array is reversed to take into account the order of preference for same-rel links
1639 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1640 foreach (array_reverse($webfinger["links"]) as $link) {
1641 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1642 && (($link["type"] ?? "") == "text/html")
1643 && ($link["href"] != "")
1645 $data["url"] = $link["href"];
1646 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1647 $data["notify"] = $link["href"];
1648 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1649 $data["poll"] = $link["href"];
1650 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1651 $data["dialback"] = $link["href"];
1654 if (isset($data["poll"]) && isset($data["notify"])
1655 && isset($data["dialback"])
1656 && isset($data["url"])
1658 // by now we use these fields only for the network type detection
1659 // So we unset all data that isn't used at the moment
1660 unset($data["dialback"]);
1662 $data["network"] = Protocol::PUMPIO;
1667 $profile_data = self::pumpioProfileData($data["url"]);
1669 if (!$profile_data) {
1673 $data = array_merge($data, $profile_data);
1675 if (($addr != '') && ($data['name'] != '')) {
1676 $name = trim(str_replace($addr, '', $data['name']));
1678 $data['name'] = $name;
1686 * Checks HTML page for RSS feed link
1688 * @param string $url Page link
1689 * @param string $body Page body string
1690 * @return string|false Feed link or false if body was invalid HTML document
1692 public static function getFeedLink(string $url, string $body)
1698 $doc = new DOMDocument();
1699 if (!@$doc->loadHTML($body)) {
1703 $xpath = new DOMXPath($doc);
1705 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1707 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1713 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1715 * Loosely based on RFC 1808
1717 * @see https://tools.ietf.org/html/rfc1808
1719 * @param string $href The potential relative href found in the HTML document
1720 * @param string $base The HTML document URL
1721 * @param DOMXPath $xpath The HTML document XPath
1724 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath)
1726 if (filter_var($href, FILTER_VALIDATE_URL)) {
1730 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1732 $baseParts = parse_url($base);
1733 if (empty($baseParts['host'])) {
1737 // Naked domain case (scheme://basehost)
1738 $path = $baseParts['path'] ?? '/';
1740 // Remove the filename part of the path if it exists (/base/path/file)
1741 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1743 $hrefParts = parse_url($href);
1745 if (!empty($hrefParts['path'])) {
1746 // Root path case (/path) including relative scheme case (//host/path)
1747 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1748 $path = $hrefParts['path'];
1750 $path = $path . '/' . $hrefParts['path'];
1752 // Resolve arbitrary relative path
1753 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1754 $parts = array_filter(explode('/', $path), 'strlen');
1755 $absolutes = array();
1756 foreach ($parts as $part) {
1757 if ('.' == $part) continue;
1758 if ('..' == $part) {
1759 array_pop($absolutes);
1761 $absolutes[] = $part;
1765 $path = '/' . implode('/', $absolutes);
1769 // Relative scheme case (//host/path)
1770 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1771 $baseParts['path'] = $path;
1772 unset($baseParts['query']);
1773 unset($baseParts['fragment']);
1775 return Network::unparseURL($baseParts);
1779 * Check for feed contact
1781 * @param string $url Profile link
1782 * @param boolean $probe Do a probe if the page contains a feed link
1784 * @return array feed data
1785 * @throws HTTPException\InternalServerErrorException
1787 private static function feed($url, $probe = true)
1789 $curlResult = DI::httpClient()->get($url, HttpClientAccept::FEED_XML);
1790 if ($curlResult->isTimeout()) {
1791 self::$istimeout = true;
1794 $feed = $curlResult->getBody();
1795 $feed_data = Feed::import($feed);
1802 $feed_url = self::getFeedLink($url, $feed);
1808 return self::feed($feed_url, false);
1811 if (!empty($feed_data["header"]["author-name"])) {
1812 $data["name"] = $feed_data["header"]["author-name"];
1815 if (!empty($feed_data["header"]["author-nick"])) {
1816 $data["nick"] = $feed_data["header"]["author-nick"];
1819 if (!empty($feed_data["header"]["author-avatar"])) {
1820 $data["photo"] = $feed_data["header"]["author-avatar"];
1823 if (!empty($feed_data["header"]["author-id"])) {
1824 $data["alias"] = $feed_data["header"]["author-id"];
1827 $data["url"] = $url;
1828 $data["poll"] = $url;
1830 $data["network"] = Protocol::FEED;
1836 * Check for mail contact
1838 * @param string $uri Profile link
1839 * @param integer $uid User ID
1841 * @return array mail data
1842 * @throws \Exception
1844 private static function mail($uri, $uid)
1846 if (!Network::isEmailDomainValid($uri)) {
1854 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1856 $condition = ["`uid` = ? AND `server` != ''", $uid];
1857 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1858 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1860 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1864 $mailbox = Email::constructMailboxName($mailacct);
1866 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1867 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1872 $msgs = Email::poll($mbox, $uri);
1873 Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
1875 if (!count($msgs)) {
1879 $phost = substr($uri, strpos($uri, '@') + 1);
1882 $data["addr"] = $uri;
1883 $data["network"] = Protocol::MAIL;
1884 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1885 $data["nick"] = $data["name"];
1886 $data["photo"] = Network::lookupAvatarByEmail($uri);
1887 $data["url"] = 'mailto:'.$uri;
1888 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1889 $data["poll"] = 'email ' . Strings::getRandomHex();
1891 $x = Email::messageMeta($mbox, $msgs[0]);
1892 if (stristr($x[0]->from, $uri)) {
1893 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1894 } elseif (stristr($x[0]->to, $uri)) {
1895 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1898 foreach ($adr as $feadr) {
1899 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1900 &&(strcasecmp($feadr->host, $phost) == 0)
1901 && (strlen($feadr->personal))
1903 $personal = imap_mime_header_decode($feadr->personal);
1905 foreach ($personal as $perspart) {
1906 if ($perspart->charset != "default") {
1907 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1909 $data["name"] .= $perspart->text;
1915 if (!empty($mbox)) {
1922 * Mix two paths together to possibly fix missing parts
1924 * @param string $avatar Path to the avatar
1925 * @param string $base Another path that is hopefully complete
1927 * @return string fixed avatar path
1928 * @throws \Exception
1930 public static function fixAvatar($avatar, $base)
1932 $base_parts = parse_url($base);
1934 // Remove all parts that could create a problem
1935 unset($base_parts['path']);
1936 unset($base_parts['query']);
1937 unset($base_parts['fragment']);
1939 $avatar_parts = parse_url($avatar);
1942 $parts = array_merge($base_parts, $avatar_parts);
1944 // And put them together again
1945 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1946 $host = isset($parts['host']) ? $parts['host'] : '';
1947 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1948 $path = isset($parts['path']) ? $parts['path'] : '';
1949 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1950 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1952 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1954 Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
1960 * Fetch the last date that the contact had posted something (publically)
1962 * @param array $data probing result
1963 * @return string last activity
1965 public static function getLastUpdate(array $data)
1967 $uid = User::getIdForURL($data['url']);
1969 $contact = Contact::selectFirst(['url', 'last-item'], ['self' => true, 'uid' => $uid]);
1970 if (!empty($contact['last-item'])) {
1971 return $contact['last-item'];
1975 if ($lastUpdate = self::updateFromNoScrape($data)) {
1979 if (!empty($data['outbox'])) {
1980 return self::updateFromOutbox($data['outbox'], $data);
1981 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
1982 return self::updateFromOutbox($data['poll'], $data);
1983 } elseif (!empty($data['poll'])) {
1984 return self::updateFromFeed($data);
1991 * Fetch the last activity date from the "noscrape" endpoint
1993 * @param array $data Probing result
1994 * @return string last activity
1996 * @return bool 'true' if update was successful or the server was unreachable
1998 private static function updateFromNoScrape(array $data)
2000 if (empty($data['baseurl'])) {
2004 // Check the 'noscrape' endpoint when it is a Friendica server
2005 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
2006 Strings::normaliseLink($data['baseurl'])]);
2007 if (!DBA::isResult($gserver)) {
2011 $curlResult = DI::httpClient()->get($gserver['noscrape'] . '/' . $data['nick'], HttpClientAccept::JSON);
2013 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
2014 $noscrape = json_decode($curlResult->getBody(), true);
2015 if (!empty($noscrape) && !empty($noscrape['updated'])) {
2016 return DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2024 * Fetch the last activity date from an ActivityPub Outbox
2026 * @param string $feed
2027 * @param array $data Probing result
2028 * @return string last activity
2029 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2031 private static function updateFromOutbox(string $feed, array $data)
2033 $outbox = ActivityPub::fetchContent($feed);
2034 if (empty($outbox)) {
2038 if (!empty($outbox['orderedItems'])) {
2039 $items = $outbox['orderedItems'];
2040 } elseif (!empty($outbox['first']['orderedItems'])) {
2041 $items = $outbox['first']['orderedItems'];
2042 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2043 return self::updateFromOutbox($outbox['first']['href'], $data);
2044 } elseif (!empty($outbox['first'])) {
2045 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2046 return self::updateFromOutbox($outbox['first'], $data);
2048 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2056 foreach ($items as $activity) {
2057 if (!empty($activity['published'])) {
2058 $published = DateTimeFormat::utc($activity['published']);
2059 } elseif (!empty($activity['object']['published'])) {
2060 $published = DateTimeFormat::utc($activity['object']['published']);
2065 if ($last_updated < $published) {
2066 $last_updated = $published;
2070 if (!empty($last_updated)) {
2071 return $last_updated;
2078 * Fetch the last activity date from an XML feed
2080 * @param array $data Probing result
2081 * @return string last activity
2083 private static function updateFromFeed(array $data)
2085 // Search for the newest entry in the feed
2086 $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::ATOM_XML);
2087 if (!$curlResult->isSuccess() || !$curlResult->getBody()) {
2091 $doc = new DOMDocument();
2092 @$doc->loadXML($curlResult->getBody());
2094 $xpath = new DOMXPath($doc);
2095 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2097 $entries = $xpath->query('/atom:feed/atom:entry');
2101 foreach ($entries as $entry) {
2102 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2103 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
2104 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2105 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2107 if (empty($published) || empty($updated)) {
2108 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2112 if ($last_updated < $published) {
2113 $last_updated = $published;
2116 if ($last_updated < $updated) {
2117 $last_updated = $updated;
2121 if (!empty($last_updated)) {
2122 return $last_updated;
2129 * Probe data from local profiles without network traffic
2131 * @param string $url
2132 * @return array probed data
2133 * @throws HTTPException\InternalServerErrorException
2134 * @throws HTTPException\NotFoundException
2136 private static function localProbe(string $url): array
2139 $uid = User::getIdForURL($url);
2141 throw new HTTPException\NotFoundException('User not found.');
2144 $owner = User::getOwnerDataById($uid);
2145 $approfile = ActivityPub\Transmitter::getProfile($uid);
2147 if (empty($owner['gsid'])) {
2148 $owner['gsid'] = GServer::getID($approfile['generator']['url']);
2152 'name' => $owner['name'], 'nick' => $owner['nick'], 'guid' => $approfile['diaspora:guid'] ?? '',
2153 'url' => $owner['url'], 'addr' => $owner['addr'], 'alias' => $owner['alias'],
2154 'photo' => User::getAvatarUrl($owner),
2155 'header' => $owner['header'] ? Contact::getHeaderUrlForId($owner['id'], $owner['updated']) : '',
2156 'account-type' => $owner['contact-type'], 'community' => ($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY),
2157 'keywords' => $owner['keywords'], 'location' => $owner['location'], 'about' => $owner['about'],
2158 'xmpp' => $owner['xmpp'], 'matrix' => $owner['matrix'],
2159 'hide' => !$owner['net-publish'], 'batch' => '', 'notify' => $owner['notify'],
2160 'poll' => $owner['poll'], 'request' => $owner['request'], 'confirm' => $owner['confirm'],
2161 'subscribe' => $approfile['generator']['url'] . '/follow?url={uri}', 'poco' => $owner['poco'],
2162 'following' => $approfile['following'], 'followers' => $approfile['followers'],
2163 'inbox' => $approfile['inbox'], 'outbox' => $approfile['outbox'],
2164 'sharedinbox' => $approfile['endpoints']['sharedInbox'], 'network' => Protocol::DFRN,
2165 'pubkey' => $owner['upubkey'], 'baseurl' => $approfile['generator']['url'], 'gsid' => $owner['gsid'],
2166 'manually-approve' => in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP])
2168 } catch (Exception $e) {
2169 // Default values for non existing targets
2171 'name' => $url, 'nick' => $url, 'url' => $url, 'network' => Protocol::PHANTOM,
2172 'photo' => DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO
2176 return self::rearrangeData($data);