3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Network;
26 use Friendica\Core\Cache\Duration;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
33 use Friendica\Model\GServer;
34 use Friendica\Model\Profile;
35 use Friendica\Model\User;
36 use Friendica\Protocol\ActivityNamespace;
37 use Friendica\Protocol\ActivityPub;
38 use Friendica\Protocol\Email;
39 use Friendica\Protocol\Feed;
40 use Friendica\Util\Crypto;
41 use Friendica\Util\DateTimeFormat;
42 use Friendica\Util\Network;
43 use Friendica\Util\Strings;
44 use Friendica\Util\XML;
47 * This class contain functions for probing URL
51 const WEBFINGER = '/.well-known/webfinger?resource={uri}';
53 private static $baseurl;
54 private static $istimeout;
57 * Remove stuff from an URI that doesn't belong there
60 * @return string Cleaned URI
62 public static function cleanURI(string $URI)
64 // At first remove leading and trailing junk
65 $URI = trim($URI, "@#?:/ \t\n\r\0\x0B");
67 $parts = parse_url($URI);
69 if (empty($parts['scheme'])) {
73 // Remove the URL fragment, since these shouldn't be part of any profile URL
74 unset($parts['fragment']);
76 $URI = Network::unparseURL($parts);
82 * Rearrange the array so that it always has the same order
84 * @param array $data Unordered data
86 * @return array Ordered data
88 private static function rearrangeData($data)
90 $fields = ["name", "nick", "guid", "url", "addr", "alias", "photo", "account-type",
91 "community", "keywords", "location", "about", "hide",
92 "batch", "notify", "poll", "request", "confirm", "subscribe", "poco",
93 "following", "followers", "inbox", "outbox", "sharedinbox",
94 "priority", "network", "pubkey", "baseurl", "gsid"];
97 foreach ($fields as $field) {
98 if (isset($data[$field])) {
99 if (in_array($field, ["gsid", "hide", "account-type"])) {
100 $newdata[$field] = (int)$data[$field];
102 $newdata[$field] = $data[$field];
104 } elseif ($field != "gsid") {
105 $newdata[$field] = "";
107 $newdata[$field] = null;
111 // We don't use the "priority" field anymore and replace it with a dummy.
112 $newdata["priority"] = 0;
118 * Check if the hostname belongs to the own server
120 * @param string $host The hostname that is to be checked
122 * @return bool Does the testes hostname belongs to the own server?
124 private static function ownHost($host)
126 $own_host = DI::baseUrl()->getHostname();
128 $parts = parse_url($host);
130 if (!isset($parts['scheme'])) {
131 $parts = parse_url('http://'.$host);
134 if (!isset($parts['host'])) {
137 return $parts['host'] == $own_host;
141 * Probes for webfinger path via "host-meta"
143 * We have to check if the servers in the future still will offer this.
144 * It seems as if it was dropped from the standard.
146 * @param string $host The host part of an url
148 * @return array with template and type of the webfinger template for JSON or XML
149 * @throws HTTPException\InternalServerErrorException
151 private static function hostMeta($host)
153 // Reset the static variable
156 // Handles the case when the hostname contains the scheme
157 if (!parse_url($host, PHP_URL_SCHEME)) {
158 $ssl_url = "https://" . $host . "/.well-known/host-meta";
159 $url = "http://" . $host . "/.well-known/host-meta";
161 $ssl_url = $host . "/.well-known/host-meta";
165 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
167 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
170 $curlResult = DI::httpRequest()->get($ssl_url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
171 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
172 if ($curlResult->isSuccess()) {
173 $xml = $curlResult->getBody();
174 $xrd = XML::parseString($xml, true);
176 $host_url = 'https://' . $host;
180 } elseif ($curlResult->isTimeout()) {
181 Logger::info('Probing timeout', ['url' => $ssl_url]);
182 self::$istimeout = true;
186 if (!is_object($xrd) && !empty($url)) {
187 $curlResult = DI::httpRequest()->get($url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
188 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
189 if ($curlResult->isTimeout()) {
190 Logger::info('Probing timeout', ['url' => $url]);
191 self::$istimeout = true;
193 } elseif ($connection_error && $ssl_connection_error) {
194 self::$istimeout = true;
198 $xml = $curlResult->getBody();
199 $xrd = XML::parseString($xml, true);
200 $host_url = 'http://'.$host;
202 if (!is_object($xrd)) {
203 Logger::info('No xrd object found', ['host' => $host]);
207 $links = XML::elementToArray($xrd);
208 if (!isset($links["xrd"]["link"])) {
209 Logger::info('No xrd data found', ['host' => $host]);
215 foreach ($links["xrd"]["link"] as $value => $link) {
216 if (!empty($link["@attributes"])) {
217 $attributes = $link["@attributes"];
218 } elseif ($value == "@attributes") {
224 if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
225 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
227 $lrdd[$type] = $attributes["template"];
231 self::$baseurl = $host_url;
233 Logger::info('Probing successful', ['host' => $host]);
239 * Perform Webfinger lookup and return DFRN data
241 * Given an email style address, perform webfinger lookup and
242 * return the resulting DFRN profile URL, or if no DFRN profile URL
243 * is located, returns an OStatus subscription template (prefixed
244 * with the string 'stat:' to identify it as on OStatus template).
245 * If this isn't an email style address just return $webbie.
246 * Return an empty string if email-style addresses but webfinger fails,
247 * or if the resultant personal XRD doesn't contain a supported
248 * subscription/friend-request attribute.
250 * amended 7/9/2011 to return an hcard which could save potentially loading
251 * a lengthy content page to scrape dfrn attributes
253 * @param string $webbie Address that should be probed
254 * @param string $hcard_url Link to the hcard - is returned by reference
256 * @return string profile link
257 * @throws HTTPException\InternalServerErrorException
259 public static function webfingerDfrn($webbie, &$hcard_url)
263 $links = self::lrdd($webbie);
264 Logger::debug('Result', ['url' => $webbie, 'links' => $links]);
265 if (!empty($links) && is_array($links)) {
266 foreach ($links as $link) {
267 if ($link['@attributes']['rel'] === ActivityNamespace::DFRN) {
268 $profile_link = $link['@attributes']['href'];
270 if (($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) && ($profile_link == "")) {
271 $profile_link = 'stat:'.$link['@attributes']['template'];
273 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
274 $hcard_url = $link['@attributes']['href'];
278 return $profile_link;
282 * Check an URI for LRDD data
284 * @param string $uri Address that should be probed
286 * @return array uri data
287 * @throws HTTPException\InternalServerErrorException
289 public static function lrdd(string $uri)
291 $data = self::getWebfingerArray($uri);
295 $webfinger = $data['webfinger'];
297 if (empty($webfinger["links"])) {
298 Logger::info('No webfinger links found', ['uri' => $uri]);
304 foreach ($webfinger["links"] as $link) {
305 $data[] = ["@attributes" => $link];
308 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
309 foreach ($webfinger["aliases"] as $alias) {
310 $data[] = ["@attributes" =>
320 * Fetch information (protocol endpoints and user information) about a given uri
322 * @param string $uri Address that should be probed
323 * @param string $network Test for this specific network
324 * @param integer $uid User ID for the probe (only used for mails)
325 * @param boolean $cache Use cached values?
327 * @return array uri data
328 * @throws HTTPException\InternalServerErrorException
329 * @throws \ImagickException
331 public static function uri($uri, $network = '', $uid = -1)
337 if (empty($network) || ($network == Protocol::ACTIVITYPUB)) {
338 $ap_profile = ActivityPub::probeProfile($uri);
343 self::$istimeout = false;
345 if ($network != Protocol::ACTIVITYPUB) {
346 $data = self::detect($uri, $network, $uid, $ap_profile);
347 if (!is_array($data)) {
350 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
352 } elseif (!empty($ap_profile)) {
353 $ap_profile['batch'] = '';
354 $data = array_merge($ap_profile, $data);
360 if (!isset($data['url'])) {
364 if (empty($data['photo'])) {
365 $data['photo'] = DI::baseUrl() . '/images/person-300.jpg';
368 if (empty($data['name'])) {
369 if (!empty($data['nick'])) {
370 $data['name'] = $data['nick'];
373 if (empty($data['name'])) {
374 $data['name'] = $data['url'];
378 if (empty($data['nick'])) {
379 $data['nick'] = strtolower($data['name']);
381 if (strpos($data['nick'], ' ')) {
382 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
386 if (!empty($data['baseurl']) && empty($data['gsid'])) {
387 $data['gsid'] = GServer::getID($data['baseurl']);
390 if (empty($data['network'])) {
391 $data['network'] = Protocol::PHANTOM;
394 // Ensure that local connections always are DFRN
395 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
396 $data['network'] = Protocol::DFRN;
399 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
400 $data['hide'] = self::getHideStatus($data['url']);
403 return self::rearrangeData($data);
408 * Fetches the "hide" status from the profile
410 * @param string $url URL of the profile
412 * @return boolean "hide" status
414 private static function getHideStatus($url)
416 $curlResult = DI::httpRequest()->get($url);
417 if (!$curlResult->isSuccess()) {
421 // If the file is too large then exit
422 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
426 // If it isn't a HTML file then exit
427 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
431 $body = $curlResult->getBody();
433 $doc = new DOMDocument();
434 @$doc->loadHTML($body);
436 $xpath = new DOMXPath($doc);
438 $list = $xpath->query('//meta[@name]');
439 foreach ($list as $node) {
441 if ($node->attributes->length) {
442 foreach ($node->attributes as $attribute) {
443 $meta_tag[$attribute->name] = $attribute->value;
447 if (empty($meta_tag['content'])) {
451 $content = strtolower(trim($meta_tag['content']));
453 switch (strtolower(trim($meta_tag['name']))) {
454 case 'dfrn-global-visibility':
455 if ($content == 'false') {
460 if (strpos($content, 'noindex') !== false) {
471 * Fetch the "subscribe" and add it to the result
473 * @param array $result
474 * @param array $webfinger
475 * @return array result
477 private static function getSubscribeLink(array $result, array $webfinger)
479 if (empty($webfinger['links'])) {
483 foreach ($webfinger['links'] as $link) {
484 if (!empty($link['template']) && ($link['rel'] === ActivityNamespace::OSTATUSSUB)) {
485 $result['subscribe'] = $link['template'];
493 * Get webfinger data from a given URI
496 * @return array Webfinger array
498 private static function getWebfingerArray(string $uri)
500 $parts = parse_url($uri);
502 if (!empty($parts['scheme']) && !empty($parts['host'])) {
503 $host = $parts['host'];
504 if (!empty($parts['port'])) {
505 $host .= ':'.$parts['port'];
508 $baseurl = $parts['scheme'] . '://' . $host;
513 $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
514 if (!empty($path_parts)) {
515 $nick = ltrim(end($path_parts), '@');
516 // When the last part of the URI is numeric then it is most likely an ID and not a nick name
517 if (!is_numeric($nick)) {
518 $addr = $nick."@".$host;
524 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
525 if (empty($webfinger)) {
526 $lrdd = self::hostMeta($host);
529 if (empty($webfinger) && empty($lrdd)) {
530 while (empty($lrdd) && empty($webfinger) && (sizeof($path_parts) > 1)) {
531 $host .= "/".array_shift($path_parts);
532 $baseurl = $parts['scheme'] . '://' . $host;
535 $addr = $nick."@".$host;
538 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
539 if (empty($webfinger)) {
540 $lrdd = self::hostMeta($host);
544 if (empty($lrdd) && empty($webfinger)) {
548 } elseif (strstr($uri, '@')) {
549 // Remove "acct:" from the URI
550 $uri = str_replace('acct:', '', $uri);
552 $host = substr($uri, strpos($uri, '@') + 1);
553 $nick = substr($uri, 0, strpos($uri, '@'));
556 $webfinger = self::getWebfinger('https://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
557 if (self::$istimeout) {
561 if (empty($webfinger)) {
562 $webfinger = self::getWebfinger('http://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
563 if (self::$istimeout) {
567 $baseurl = 'https://' . $host;
570 if (empty($webfinger)) {
571 $lrdd = self::hostMeta($host);
572 if (self::$istimeout) {
575 $baseurl = self::$baseurl;
577 $baseurl = 'http://' . $host;
580 Logger::info('URI was not detectable', ['uri' => $uri]);
584 if (empty($webfinger)) {
585 foreach ($lrdd as $type => $template) {
590 $webfinger = self::getWebfinger($template, $type, $uri, $addr);
594 if (empty($webfinger)) {
598 if ($webfinger['detected'] == $addr) {
599 $webfinger['nick'] = $nick;
600 $webfinger['addr'] = $addr;
603 $webfinger['baseurl'] = $baseurl;
609 * Perform network request for webfinger data
611 * @param string $template
612 * @param string $type
614 * @param string $addr
615 * @return array webfinger results
617 private static function getWebfinger(string $template, string $type, string $uri, string $addr)
619 // First try the address because this is the primary purpose of webfinger
622 $path = str_replace('{uri}', urlencode("acct:" . $addr), $template);
623 $webfinger = self::webfinger($path, $type);
624 if (self::$istimeout) {
630 if (empty($webfinger) && $uri != $addr) {
632 $path = str_replace('{uri}', urlencode($uri), $template);
633 $webfinger = self::webfinger($path, $type);
634 if (self::$istimeout) {
639 if (empty($webfinger)) {
643 return ['webfinger' => $webfinger, 'detected' => $detected];
647 * Fetch information (protocol endpoints and user information) about a given uri
649 * This function is only called by the "uri" function that adds caching and rearranging of data.
651 * @param string $uri Address that should be probed
652 * @param string $network Test for this specific network
653 * @param integer $uid User ID for the probe (only used for mails)
654 * @param array $ap_profile Previously probed AP profile
656 * @return array uri data
657 * @throws HTTPException\InternalServerErrorException
659 private static function detect(string $uri, string $network, int $uid, array $ap_profile)
663 'network' => $network,
668 Hook::callAll('probe_detect', $hookData);
670 if ($hookData['result']) {
671 if (!is_array($hookData['result'])) {
674 return $hookData['result'];
678 $parts = parse_url($uri);
680 if (!empty($parts['scheme']) && !empty($parts['host'])) {
681 if (in_array($parts['host'], ['twitter.com', 'mobile.twitter.com'])) {
682 return self::twitter($uri);
684 } elseif (strstr($uri, '@')) {
685 // If the URI starts with "mailto:" then jump directly to the mail detection
686 if (strpos($uri, 'mailto:') !== false) {
687 $uri = str_replace('mailto:', '', $uri);
688 return self::mail($uri, $uid);
691 if ($network == Protocol::MAIL) {
692 return self::mail($uri, $uid);
695 if (Strings::endsWith($uri, '@twitter.com')
696 || Strings::endsWith($uri, '@mobile.twitter.com')
698 return self::twitter($uri);
701 Logger::info('URI was not detectable', ['uri' => $uri]);
705 Logger::info('Probing start', ['uri' => $uri]);
707 $data = self::getWebfingerArray($uri);
709 if (!empty($parts['scheme'])) {
710 return self::feed($uri);
711 } elseif (!empty($uid)) {
712 return self::mail($uri, $uid);
718 $webfinger = $data['webfinger'];
719 $nick = $data['nick'] ?? '';
720 $addr = $data['addr'] ?? '';
721 $baseurl = $data['baseurl'] ?? '';
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, $baseurl);
737 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
738 $result = self::pumpio($webfinger, $addr);
740 if (empty($result['network']) && empty($ap_profile['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 $result = self::getSubscribeLink($result, $webfinger);
756 if (empty($result["network"])) {
757 $result["network"] = Protocol::PHANTOM;
760 if (empty($result['baseurl']) && !empty($baseurl)) {
761 $result['baseurl'] = $baseurl;
764 if (empty($result["url"])) {
765 $result["url"] = $uri;
768 Logger::info('Probing done', ['uri' => $uri, 'network' => $result["network"]]);
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, $baseurl)
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($baseurl)) {
804 $condition = ['nurl' => Strings::normaliseLink($baseurl), 'platform' => ['hubzilla']];
805 if (!DBA::exists('gserver', $condition)) {
808 $zot_url = $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 = DI::httpRequest()->get($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'] = User::PAGE_FLAGS_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 public static function webfinger($url, $type)
925 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
927 $curlResult = DI::httpRequest()->get($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 (!empty($webfinger)) {
936 if (!isset($webfinger["links"])) {
937 Logger::info('No json webfinger links', ['url' => $url]);
943 // If it is not JSON, maybe it is XML
944 $xrd = XML::parseString($data, true);
945 if (!is_object($xrd)) {
946 Logger::info('No webfinger data retrievable', ['url' => $url]);
950 $xrd_arr = XML::elementToArray($xrd);
951 if (!isset($xrd_arr["xrd"]["link"])) {
952 Logger::info('No XML webfinger links', ['url' => $url]);
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 = DI::httpRequest()->get($noscrape_url);
997 if ($curlResult->isTimeout()) {
998 self::$istimeout = true;
1001 $content = $curlResult->getBody();
1003 Logger::info('Empty body', ['url' => $noscrape_url]);
1007 $json = json_decode($content, true);
1008 if (!is_array($json)) {
1009 Logger::info('No json data', ['url' => $noscrape_url]);
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::info('Check profile', ['link' => $profile_link]);
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::debug('Result', ['link' => $profile_link, 'data' => $prof_data]);
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 = DI::httpRequest()->get($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 (!empty($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"] = $data["alias"] = $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 = DI::httpRequest()->get($pubkey);
1509 if ($curlResult->isTimeout()) {
1510 self::$istimeout = true;
1511 return $short ? false : [];
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;
1533 return $short ? false : [];
1540 // Fetch all additional data from the feed
1541 $curlResult = DI::httpRequest()->get($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["url"] == $data["alias"]) {
1577 $data["alias"] = '';
1580 /// @todo Fetch location and "about" from the feed as well
1585 * Fetch data from a pump.io profile page
1587 * @param string $profile_link Link to the profile page
1589 * @return array profile data
1591 private static function pumpioProfileData($profile_link)
1593 $curlResult = DI::httpRequest()->get($profile_link);
1594 if (!$curlResult->isSuccess()) {
1598 $doc = new DOMDocument();
1599 if (!@$doc->loadHTML($curlResult->getBody())) {
1603 $xpath = new DomXPath($doc);
1607 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1609 if ($data["name"] == '') {
1610 // This is ugly - but pump.io doesn't seem to know a better way for it
1611 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1612 $pos = strpos($data["name"], chr(10));
1614 $data["name"] = trim(substr($data["name"], 0, $pos));
1618 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1620 if ($data["location"] == '') {
1621 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1624 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1626 if ($data["about"] == '') {
1627 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1630 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1632 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1635 foreach ($avatar->attributes as $attribute) {
1636 if ($attribute->name == "src") {
1637 $data["photo"] = trim($attribute->value);
1646 * Check for pump.io contact
1648 * @param array $webfinger Webfinger data
1649 * @param string $addr
1650 * @return array pump.io data
1652 private static function pumpio($webfinger, $addr)
1655 // The array is reversed to take into account the order of preference for same-rel links
1656 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1657 foreach (array_reverse($webfinger["links"]) as $link) {
1658 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1659 && (($link["type"] ?? "") == "text/html")
1660 && ($link["href"] != "")
1662 $data["url"] = $link["href"];
1663 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1664 $data["notify"] = $link["href"];
1665 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1666 $data["poll"] = $link["href"];
1667 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1668 $data["dialback"] = $link["href"];
1671 if (isset($data["poll"]) && isset($data["notify"])
1672 && isset($data["dialback"])
1673 && isset($data["url"])
1675 // by now we use these fields only for the network type detection
1676 // So we unset all data that isn't used at the moment
1677 unset($data["dialback"]);
1679 $data["network"] = Protocol::PUMPIO;
1684 $profile_data = self::pumpioProfileData($data["url"]);
1686 if (!$profile_data) {
1690 $data = array_merge($data, $profile_data);
1692 if (($addr != '') && ($data['name'] != '')) {
1693 $name = trim(str_replace($addr, '', $data['name']));
1695 $data['name'] = $name;
1703 * Check for twitter contact
1705 * @param string $uri
1707 * @return array twitter data
1709 private static function twitter($uri)
1711 if (preg_match('=([^@]+)@(?:mobile\.)?twitter\.com$=i', $uri, $matches)) {
1712 $nick = $matches[1];
1713 } elseif (preg_match('=^https?://(?:mobile\.)?twitter\.com/(.+)=i', $uri, $matches)) {
1714 $nick = $matches[1];
1720 $data['url'] = 'https://twitter.com/' . $nick;
1721 $data['addr'] = $nick . '@twitter.com';
1722 $data['nick'] = $data['name'] = $nick;
1723 $data['network'] = Protocol::TWITTER;
1724 $data['baseurl'] = 'https://twitter.com';
1730 * Checks HTML page for RSS feed link
1732 * @param string $url Page link
1733 * @param string $body Page body string
1734 * @return string|false Feed link or false if body was invalid HTML document
1736 public static function getFeedLink(string $url, string $body)
1738 $doc = new DOMDocument();
1739 if (!@$doc->loadHTML($body)) {
1743 $xpath = new DOMXPath($doc);
1745 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1747 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1753 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1755 * Loosely based on RFC 1808
1757 * @see https://tools.ietf.org/html/rfc1808
1759 * @param string $href The potential relative href found in the HTML document
1760 * @param string $base The HTML document URL
1761 * @param DOMXPath $xpath The HTML document XPath
1764 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath)
1766 if (filter_var($href, FILTER_VALIDATE_URL)) {
1770 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1772 $baseParts = parse_url($base);
1773 if (empty($baseParts['host'])) {
1777 // Naked domain case (scheme://basehost)
1778 $path = $baseParts['path'] ?? '/';
1780 // Remove the filename part of the path if it exists (/base/path/file)
1781 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1783 $hrefParts = parse_url($href);
1785 // Root path case (/path) including relative scheme case (//host/path)
1786 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1787 $path = $hrefParts['path'];
1789 $path = $path . '/' . $hrefParts['path'];
1791 // Resolve arbitrary relative path
1792 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1793 $parts = array_filter(explode('/', $path), 'strlen');
1794 $absolutes = array();
1795 foreach ($parts as $part) {
1796 if ('.' == $part) continue;
1797 if ('..' == $part) {
1798 array_pop($absolutes);
1800 $absolutes[] = $part;
1804 $path = '/' . implode('/', $absolutes);
1807 // Relative scheme case (//host/path)
1808 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1809 $baseParts['path'] = $path;
1810 unset($baseParts['query']);
1811 unset($baseParts['fragment']);
1813 return Network::unparseURL($baseParts);
1817 * Check for feed contact
1819 * @param string $url Profile link
1820 * @param boolean $probe Do a probe if the page contains a feed link
1822 * @return array feed data
1823 * @throws HTTPException\InternalServerErrorException
1825 private static function feed($url, $probe = true)
1827 $curlResult = DI::httpRequest()->get($url);
1828 if ($curlResult->isTimeout()) {
1829 self::$istimeout = true;
1832 $feed = $curlResult->getBody();
1833 $feed_data = Feed::import($feed);
1840 $feed_url = self::getFeedLink($url, $feed);
1846 return self::feed($feed_url, false);
1849 if (!empty($feed_data["header"]["author-name"])) {
1850 $data["name"] = $feed_data["header"]["author-name"];
1853 if (!empty($feed_data["header"]["author-nick"])) {
1854 $data["nick"] = $feed_data["header"]["author-nick"];
1857 if (!empty($feed_data["header"]["author-avatar"])) {
1858 $data["photo"] = $feed_data["header"]["author-avatar"];
1861 if (!empty($feed_data["header"]["author-id"])) {
1862 $data["alias"] = $feed_data["header"]["author-id"];
1865 $data["url"] = $url;
1866 $data["poll"] = $url;
1868 $data["network"] = Protocol::FEED;
1874 * Check for mail contact
1876 * @param string $uri Profile link
1877 * @param integer $uid User ID
1879 * @return array mail data
1880 * @throws \Exception
1882 private static function mail($uri, $uid)
1884 if (!Network::isEmailDomainValid($uri)) {
1892 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1894 $condition = ["`uid` = ? AND `server` != ''", $uid];
1895 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1896 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1898 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1902 $mailbox = Email::constructMailboxName($mailacct);
1904 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1905 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1910 $msgs = Email::poll($mbox, $uri);
1911 Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
1913 if (!count($msgs)) {
1917 $phost = substr($uri, strpos($uri, '@') + 1);
1920 $data["addr"] = $uri;
1921 $data["network"] = Protocol::MAIL;
1922 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1923 $data["nick"] = $data["name"];
1924 $data["photo"] = Network::lookupAvatarByEmail($uri);
1925 $data["url"] = 'mailto:'.$uri;
1926 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1927 $data["poll"] = 'email ' . Strings::getRandomHex();
1929 $x = Email::messageMeta($mbox, $msgs[0]);
1930 if (stristr($x[0]->from, $uri)) {
1931 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1932 } elseif (stristr($x[0]->to, $uri)) {
1933 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1936 foreach ($adr as $feadr) {
1937 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1938 &&(strcasecmp($feadr->host, $phost) == 0)
1939 && (strlen($feadr->personal))
1941 $personal = imap_mime_header_decode($feadr->personal);
1943 foreach ($personal as $perspart) {
1944 if ($perspart->charset != "default") {
1945 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1947 $data["name"] .= $perspart->text;
1951 $data["name"] = Strings::escapeTags($data["name"]);
1955 if (!empty($mbox)) {
1962 * Mix two paths together to possibly fix missing parts
1964 * @param string $avatar Path to the avatar
1965 * @param string $base Another path that is hopefully complete
1967 * @return string fixed avatar path
1968 * @throws \Exception
1970 public static function fixAvatar($avatar, $base)
1972 $base_parts = parse_url($base);
1974 // Remove all parts that could create a problem
1975 unset($base_parts['path']);
1976 unset($base_parts['query']);
1977 unset($base_parts['fragment']);
1979 $avatar_parts = parse_url($avatar);
1982 $parts = array_merge($base_parts, $avatar_parts);
1984 // And put them together again
1985 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1986 $host = isset($parts['host']) ? $parts['host'] : '';
1987 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1988 $path = isset($parts['path']) ? $parts['path'] : '';
1989 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1990 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1992 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1994 Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
2000 * Fetch the last date that the contact had posted something (publically)
2002 * @param string $data probing result
2003 * @return string last activity
2005 public static function getLastUpdate(array $data)
2007 if ($lastUpdate = self::updateFromNoScrape($data)) {
2011 if (!empty($data['outbox'])) {
2012 return self::updateFromOutbox($data['outbox'], $data);
2013 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
2014 return self::updateFromOutbox($data['poll'], $data);
2015 } elseif (!empty($data['poll'])) {
2016 return self::updateFromFeed($data);
2023 * Fetch the last activity date from the "noscrape" endpoint
2025 * @param array $data Probing result
2026 * @return string last activity
2028 * @return bool 'true' if update was successful or the server was unreachable
2030 private static function updateFromNoScrape(array $data)
2032 if (empty($data['baseurl'])) {
2036 // Check the 'noscrape' endpoint when it is a Friendica server
2037 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
2038 Strings::normaliseLink($data['baseurl'])]);
2039 if (!DBA::isResult($gserver)) {
2043 $curlResult = DI::httpRequest()->get($gserver['noscrape'] . '/' . $data['nick']);
2045 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
2046 $noscrape = json_decode($curlResult->getBody(), true);
2047 if (!empty($noscrape) && !empty($noscrape['updated'])) {
2048 return DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2056 * Fetch the last activity date from an ActivityPub Outbox
2058 * @param string $feed
2059 * @param array $data Probing result
2060 * @return string last activity
2061 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2063 private static function updateFromOutbox(string $feed, array $data)
2065 $outbox = ActivityPub::fetchContent($feed);
2066 if (empty($outbox)) {
2070 if (!empty($outbox['orderedItems'])) {
2071 $items = $outbox['orderedItems'];
2072 } elseif (!empty($outbox['first']['orderedItems'])) {
2073 $items = $outbox['first']['orderedItems'];
2074 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2075 return self::updateFromOutbox($outbox['first']['href'], $data);
2076 } elseif (!empty($outbox['first'])) {
2077 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2078 return self::updateFromOutbox($outbox['first'], $data);
2080 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2088 foreach ($items as $activity) {
2089 if (!empty($activity['published'])) {
2090 $published = DateTimeFormat::utc($activity['published']);
2091 } elseif (!empty($activity['object']['published'])) {
2092 $published = DateTimeFormat::utc($activity['object']['published']);
2097 if ($last_updated < $published) {
2098 $last_updated = $published;
2102 if (!empty($last_updated)) {
2103 return $last_updated;
2110 * Fetch the last activity date from an XML feed
2112 * @param array $data Probing result
2113 * @return string last activity
2115 private static function updateFromFeed(array $data)
2117 // Search for the newest entry in the feed
2118 $curlResult = DI::httpRequest()->get($data['poll']);
2119 if (!$curlResult->isSuccess()) {
2123 $doc = new DOMDocument();
2124 @$doc->loadXML($curlResult->getBody());
2126 $xpath = new DOMXPath($doc);
2127 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2129 $entries = $xpath->query('/atom:feed/atom:entry');
2133 foreach ($entries as $entry) {
2134 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2135 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
2136 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2137 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2139 if (empty($published) || empty($updated)) {
2140 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2144 if ($last_updated < $published) {
2145 $last_updated = $published;
2148 if ($last_updated < $updated) {
2149 $last_updated = $updated;
2153 if (!empty($last_updated)) {
2154 return $last_updated;