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\Contact;
34 use Friendica\Model\GServer;
35 use Friendica\Model\Profile;
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\Network;
42 use Friendica\Util\Strings;
43 use Friendica\Util\XML;
46 * This class contain functions for probing URL
50 const WEBFINGER = '/.well-known/webfinger?resource={uri}';
52 private static $baseurl;
53 private static $istimeout;
56 * Remove stuff from an URI that doesn't belong there
59 * @return string Cleaned URI
61 public static function cleanURI(string $URI)
63 // At first remove leading and trailing junk
64 $URI = trim($URI, "@#?:/ \t\n\r\0\x0B");
66 $parts = parse_url($URI);
68 if (empty($parts['scheme'])) {
72 // Remove the URL fragment, since these shouldn't be part of any profile URL
73 unset($parts['fragment']);
75 $URI = Network::unparseURL($parts);
81 * Rearrange the array so that it always has the same order
83 * @param array $data Unordered data
85 * @return array Ordered data
87 private static function rearrangeData($data)
89 $fields = ["name", "nick", "guid", "url", "addr", "alias", "photo", "account-type",
90 "community", "keywords", "location", "about", "hide",
91 "batch", "notify", "poll", "request", "confirm", "subscribe", "poco",
92 "following", "followers", "inbox", "outbox", "sharedinbox",
93 "priority", "network", "pubkey", "baseurl", "gsid"];
96 foreach ($fields as $field) {
97 if (isset($data[$field])) {
98 if (in_array($field, ["gsid", "hide", "account-type"])) {
99 $newdata[$field] = (int)$data[$field];
101 $newdata[$field] = $data[$field];
103 } elseif ($field != "gsid") {
104 $newdata[$field] = "";
106 $newdata[$field] = null;
110 // We don't use the "priority" field anymore and replace it with a dummy.
111 $newdata["priority"] = 0;
117 * Check if the hostname belongs to the own server
119 * @param string $host The hostname that is to be checked
121 * @return bool Does the testes hostname belongs to the own server?
123 private static function ownHost($host)
125 $own_host = DI::baseUrl()->getHostname();
127 $parts = parse_url($host);
129 if (!isset($parts['scheme'])) {
130 $parts = parse_url('http://'.$host);
133 if (!isset($parts['host'])) {
136 return $parts['host'] == $own_host;
140 * Probes for webfinger path via "host-meta"
142 * We have to check if the servers in the future still will offer this.
143 * It seems as if it was dropped from the standard.
145 * @param string $host The host part of an url
147 * @return array with template and type of the webfinger template for JSON or XML
148 * @throws HTTPException\InternalServerErrorException
150 private static function hostMeta($host)
152 // Reset the static variable
155 // Handles the case when the hostname contains the scheme
156 if (!parse_url($host, PHP_URL_SCHEME)) {
157 $ssl_url = "https://" . $host . "/.well-known/host-meta";
158 $url = "http://" . $host . "/.well-known/host-meta";
160 $ssl_url = $host . "/.well-known/host-meta";
164 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
166 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
169 $curlResult = Network::curl($ssl_url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
170 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
171 if ($curlResult->isSuccess()) {
172 $xml = $curlResult->getBody();
173 $xrd = XML::parseString($xml, true);
175 $host_url = 'https://' . $host;
179 } elseif ($curlResult->isTimeout()) {
180 Logger::info('Probing timeout', ['url' => $ssl_url], Logger::DEBUG);
181 self::$istimeout = true;
185 if (!is_object($xrd) && !empty($url)) {
186 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
187 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
188 if ($curlResult->isTimeout()) {
189 Logger::info('Probing timeout', ['url' => $url], Logger::DEBUG);
190 self::$istimeout = true;
192 } elseif ($connection_error && $ssl_connection_error) {
193 self::$istimeout = true;
197 $xml = $curlResult->getBody();
198 $xrd = XML::parseString($xml, true);
199 $host_url = 'http://'.$host;
201 if (!is_object($xrd)) {
202 Logger::log("No xrd object found for ".$host, Logger::DEBUG);
206 $links = XML::elementToArray($xrd);
207 if (!isset($links["xrd"]["link"])) {
208 Logger::log("No xrd data found for ".$host, Logger::DEBUG);
214 foreach ($links["xrd"]["link"] as $value => $link) {
215 if (!empty($link["@attributes"])) {
216 $attributes = $link["@attributes"];
217 } elseif ($value == "@attributes") {
223 if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
224 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
226 $lrdd[$type] = $attributes["template"];
230 self::$baseurl = $host_url;
232 Logger::log("Probing successful for ".$host, Logger::DEBUG);
238 * Perform Webfinger lookup and return DFRN data
240 * Given an email style address, perform webfinger lookup and
241 * return the resulting DFRN profile URL, or if no DFRN profile URL
242 * is located, returns an OStatus subscription template (prefixed
243 * with the string 'stat:' to identify it as on OStatus template).
244 * If this isn't an email style address just return $webbie.
245 * Return an empty string if email-style addresses but webfinger fails,
246 * or if the resultant personal XRD doesn't contain a supported
247 * subscription/friend-request attribute.
249 * amended 7/9/2011 to return an hcard which could save potentially loading
250 * a lengthy content page to scrape dfrn attributes
252 * @param string $webbie Address that should be probed
253 * @param string $hcard_url Link to the hcard - is returned by reference
255 * @return string profile link
256 * @throws HTTPException\InternalServerErrorException
258 public static function webfingerDfrn($webbie, &$hcard_url)
262 $links = self::lrdd($webbie);
263 Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA);
264 if (!empty($links) && is_array($links)) {
265 foreach ($links as $link) {
266 if ($link['@attributes']['rel'] === ActivityNamespace::DFRN) {
267 $profile_link = $link['@attributes']['href'];
269 if (($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) && ($profile_link == "")) {
270 $profile_link = 'stat:'.$link['@attributes']['template'];
272 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
273 $hcard_url = $link['@attributes']['href'];
277 return $profile_link;
281 * Check an URI for LRDD data
283 * @param string $uri Address that should be probed
285 * @return array uri data
286 * @throws HTTPException\InternalServerErrorException
288 public static function lrdd(string $uri)
290 $data = self::getWebfingerArray($uri);
294 $webfinger = $data['webfinger'];
296 if (empty($webfinger["links"])) {
297 Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
303 foreach ($webfinger["links"] as $link) {
304 $data[] = ["@attributes" => $link];
307 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
308 foreach ($webfinger["aliases"] as $alias) {
309 $data[] = ["@attributes" =>
319 * Fetch information (protocol endpoints and user information) about a given uri
321 * @param string $uri Address that should be probed
322 * @param string $network Test for this specific network
323 * @param integer $uid User ID for the probe (only used for mails)
324 * @param boolean $cache Use cached values?
326 * @return array uri data
327 * @throws HTTPException\InternalServerErrorException
328 * @throws \ImagickException
330 public static function uri($uri, $network = '', $uid = -1, $cache = true)
332 $cachekey = 'Probe::uri:' . $network . ':' . $uri;
334 $result = DI::cache()->get($cachekey);
335 if (!is_null($result)) {
344 if (empty($network) || ($network == Protocol::ACTIVITYPUB)) {
345 $ap_profile = ActivityPub::probeProfile($uri, !$cache);
350 self::$istimeout = false;
352 if ($network != Protocol::ACTIVITYPUB) {
353 $data = self::detect($uri, $network, $uid, $ap_profile);
354 if (!is_array($data)) {
357 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
359 } elseif (!empty($ap_profile)) {
360 $ap_profile['batch'] = '';
361 $data = array_merge($ap_profile, $data);
367 if (!isset($data['url'])) {
371 if (empty($data['photo'])) {
372 $data['photo'] = DI::baseUrl() . '/images/person-300.jpg';
375 if (empty($data['name'])) {
376 if (!empty($data['nick'])) {
377 $data['name'] = $data['nick'];
380 if (empty($data['name'])) {
381 $data['name'] = $data['url'];
385 if (empty($data['nick'])) {
386 $data['nick'] = strtolower($data['name']);
388 if (strpos($data['nick'], ' ')) {
389 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
393 if (!empty($data['baseurl']) && empty($data['gsid'])) {
394 $data['gsid'] = GServer::getID($data['baseurl']);
397 if (empty($data['network'])) {
398 $data['network'] = Protocol::PHANTOM;
401 // Ensure that local connections always are DFRN
402 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
403 $data['network'] = Protocol::DFRN;
406 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
407 $data['hide'] = self::getHideStatus($data['url']);
410 $data = self::rearrangeData($data);
412 // Only store into the cache if the value seems to be valid
413 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
414 DI::cache()->set($cachekey, $data, Duration::DAY);
422 * Fetches the "hide" status from the profile
424 * @param string $url URL of the profile
426 * @return boolean "hide" status
428 private static function getHideStatus($url)
430 $curlResult = Network::curl($url);
431 if (!$curlResult->isSuccess()) {
435 // If the file is too large then exit
436 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
440 // If it isn't a HTML file then exit
441 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
445 $body = $curlResult->getBody();
447 $doc = new DOMDocument();
448 @$doc->loadHTML($body);
450 $xpath = new DOMXPath($doc);
452 $list = $xpath->query('//meta[@name]');
453 foreach ($list as $node) {
455 if ($node->attributes->length) {
456 foreach ($node->attributes as $attribute) {
457 $meta_tag[$attribute->name] = $attribute->value;
461 if (empty($meta_tag['content'])) {
465 $content = strtolower(trim($meta_tag['content']));
467 switch (strtolower(trim($meta_tag['name']))) {
468 case 'dfrn-global-visibility':
469 if ($content == 'false') {
474 if (strpos($content, 'noindex') !== false) {
485 * Fetch the "subscribe" and add it to the result
487 * @param array $result
488 * @param array $webfinger
489 * @return array result
491 private static function getSubscribeLink(array $result, array $webfinger)
493 if (empty($webfinger['links'])) {
497 foreach ($webfinger['links'] as $link) {
498 if (!empty($link['template']) && ($link['rel'] === ActivityNamespace::OSTATUSSUB)) {
499 $result['subscribe'] = $link['template'];
507 * Get webfinger data from a given URI
510 * @return array Webfinger array
512 private static function getWebfingerArray(string $uri)
514 $parts = parse_url($uri);
516 if (!empty($parts['scheme']) && !empty($parts['host'])) {
517 $host = $parts['host'];
518 if (!empty($parts['port'])) {
519 $host .= ':'.$parts['port'];
522 $baseurl = $parts['scheme'] . '://' . $host;
527 $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
528 if (!empty($path_parts)) {
529 $nick = ltrim(end($path_parts), '@');
530 // When the last part of the URI is numeric then it is most likely an ID and not a nick name
531 if (!is_numeric($nick)) {
532 $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);
543 if (empty($webfinger) && empty($lrdd)) {
544 while (empty($lrdd) && empty($webfinger) && (sizeof($path_parts) > 1)) {
545 $host .= "/".array_shift($path_parts);
546 $baseurl = $parts['scheme'] . '://' . $host;
549 $addr = $nick."@".$host;
552 $webfinger = self::getWebfinger($parts['scheme'] . '://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
553 if (empty($webfinger)) {
554 $lrdd = self::hostMeta($host);
558 if (empty($lrdd) && empty($webfinger)) {
562 } elseif (strstr($uri, '@')) {
563 // Remove "acct:" from the URI
564 $uri = str_replace('acct:', '', $uri);
566 $host = substr($uri, strpos($uri, '@') + 1);
567 $nick = substr($uri, 0, strpos($uri, '@'));
570 $webfinger = self::getWebfinger('https://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
571 if (self::$istimeout) {
575 if (empty($webfinger)) {
576 $webfinger = self::getWebfinger('http://' . $host . self::WEBFINGER, 'application/jrd+json', $uri, $addr);
577 if (self::$istimeout) {
581 $baseurl = 'https://' . $host;
584 if (empty($webfinger)) {
585 $lrdd = self::hostMeta($host);
586 if (self::$istimeout) {
589 $baseurl = self::$baseurl;
591 $baseurl = 'http://' . $host;
594 Logger::info('URI was not detectable', ['uri' => $uri]);
598 if (empty($webfinger)) {
599 foreach ($lrdd as $type => $template) {
604 $webfinger = self::getWebfinger($template, $type, $uri, $addr);
608 if (empty($webfinger)) {
612 if ($webfinger['detected'] == $addr) {
613 $webfinger['nick'] = $nick;
614 $webfinger['addr'] = $addr;
617 $webfinger['baseurl'] = $baseurl;
623 * Perform network request for webfinger data
625 * @param string $template
626 * @param string $type
628 * @param string $addr
629 * @return array webfinger results
631 private static function getWebfinger(string $template, string $type, string $uri, string $addr)
633 // First try the address because this is the primary purpose of webfinger
636 $path = str_replace('{uri}', urlencode("acct:" . $addr), $template);
637 $webfinger = self::webfinger($path, $type);
638 if (self::$istimeout) {
644 if (empty($webfinger) && $uri != $addr) {
646 $path = str_replace('{uri}', urlencode($uri), $template);
647 $webfinger = self::webfinger($path, $type);
648 if (self::$istimeout) {
653 if (empty($webfinger)) {
657 return ['webfinger' => $webfinger, 'detected' => $detected];
661 * Fetch information (protocol endpoints and user information) about a given uri
663 * This function is only called by the "uri" function that adds caching and rearranging of data.
665 * @param string $uri Address that should be probed
666 * @param string $network Test for this specific network
667 * @param integer $uid User ID for the probe (only used for mails)
668 * @param array $ap_profile Previously probed AP profile
670 * @return array uri data
671 * @throws HTTPException\InternalServerErrorException
673 private static function detect(string $uri, string $network, int $uid, array $ap_profile)
677 'network' => $network,
682 Hook::callAll('probe_detect', $hookData);
684 if ($hookData['result']) {
685 if (!is_array($hookData['result'])) {
688 return $hookData['result'];
692 $parts = parse_url($uri);
694 if (!empty($parts['scheme']) && !empty($parts['host'])) {
695 if ($parts['host'] == 'twitter.com') {
696 return self::twitter($uri);
698 } elseif (strstr($uri, '@')) {
699 // If the URI starts with "mailto:" then jump directly to the mail detection
700 if (strpos($uri, 'mailto:') !== false) {
701 $uri = str_replace('mailto:', '', $uri);
702 return self::mail($uri, $uid);
705 if ($network == Protocol::MAIL) {
706 return self::mail($uri, $uid);
709 if (strpos($uri, '@twitter.com')) {
710 return self::twitter($uri);
713 Logger::info('URI was not detectable', ['uri' => $uri]);
717 Logger::info('Probing start', ['uri' => $uri]);
719 $data = self::getWebfingerArray($uri);
721 if (!empty($parts['scheme'])) {
722 return self::feed($uri);
723 } elseif (!empty($uid)) {
724 return self::mail($uri, $uid);
730 $webfinger = $data['webfinger'];
731 $nick = $data['nick'] ?? '';
732 $addr = $data['addr'] ?? '';
733 $baseurl = $data['baseurl'] ?? '';
737 if (in_array($network, ["", Protocol::DFRN])) {
738 $result = self::dfrn($webfinger);
740 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
741 $result = self::diaspora($webfinger);
743 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
744 $result = self::ostatus($webfinger);
746 if (in_array($network, ['', Protocol::ZOT])) {
747 $result = self::zot($webfinger, $result, $baseurl);
749 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
750 $result = self::pumpio($webfinger, $addr);
752 if (empty($result['network']) && empty($ap_profile['network']) || ($network == Protocol::FEED)) {
753 $result = self::feed($uri);
755 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
756 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
757 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
758 $result["nick"] = $nick;
761 if (empty($result["addr"]) && ($addr != "")) {
762 $result["addr"] = $addr;
766 $result = self::getSubscribeLink($result, $webfinger);
768 if (empty($result["network"])) {
769 $result["network"] = Protocol::PHANTOM;
772 if (empty($result['baseurl']) && !empty($baseurl)) {
773 $result['baseurl'] = $baseurl;
776 if (empty($result["url"])) {
777 $result["url"] = $uri;
780 Logger::info('Probing done', ['uri' => $uri, 'network' => $result["network"]]);
786 * Check for Zot contact
788 * @param array $webfinger Webfinger data
789 * @param array $data previously probed data
791 * @return array Zot data
792 * @throws HTTPException\InternalServerErrorException
794 private static function zot($webfinger, $data, $baseurl)
796 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
797 foreach ($webfinger["aliases"] as $alias) {
798 if (substr($alias, 0, 5) == 'acct:') {
799 $data["addr"] = substr($alias, 5);
804 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
805 $data["addr"] = substr($webfinger["subject"], 5);
809 foreach ($webfinger['links'] as $link) {
810 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
811 $zot_url = $link['href'];
815 if (empty($zot_url) && !empty($data['addr']) && !empty($baseurl)) {
816 $condition = ['nurl' => Strings::normaliseLink($baseurl), 'platform' => ['hubzilla']];
817 if (!DBA::exists('gserver', $condition)) {
820 $zot_url = $baseurl . '/.well-known/zot-info?address=' . $data['addr'];
823 if (empty($zot_url)) {
827 $data = self::pollZot($zot_url, $data);
829 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
830 foreach ($webfinger['aliases'] as $alias) {
831 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
832 $data['alias'] = $alias;
840 public static function pollZot($url, $data)
842 $curlResult = Network::curl($url);
843 if ($curlResult->isTimeout()) {
846 $content = $curlResult->getBody();
851 $json = json_decode($content, true);
852 if (!is_array($json)) {
856 if (empty($data['network'])) {
857 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
858 $data['network'] = Protocol::ZOT;
859 } elseif (!isset($json['protocols'])) {
860 $data['network'] = Protocol::ZOT;
864 if (!empty($json['guid']) && empty($data['guid'])) {
865 $data['guid'] = $json['guid'];
867 if (!empty($json['key']) && empty($data['pubkey'])) {
868 $data['pubkey'] = $json['key'];
870 if (!empty($json['name'])) {
871 $data['name'] = $json['name'];
873 if (!empty($json['photo'])) {
874 $data['photo'] = $json['photo'];
875 if (!empty($json['photo_updated'])) {
876 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
879 if (!empty($json['address'])) {
880 $data['addr'] = $json['address'];
882 if (!empty($json['url'])) {
883 $data['url'] = $json['url'];
885 if (!empty($json['connections_url'])) {
886 $data['poco'] = $json['connections_url'];
888 if (isset($json['searchable'])) {
889 $data['hide'] = !$json['searchable'];
891 if (!empty($json['public_forum'])) {
892 $data['community'] = $json['public_forum'];
893 $data['account-type'] = Contact::PAGE_COMMUNITY;
896 if (!empty($json['profile'])) {
897 $profile = $json['profile'];
898 if (!empty($profile['description'])) {
899 $data['about'] = $profile['description'];
901 if (!empty($profile['keywords'])) {
902 $keywords = implode(', ', $profile['keywords']);
903 if (!empty($keywords)) {
904 $data['keywords'] = $keywords;
909 if (!empty($profile['region'])) {
910 $loc['region'] = $profile['region'];
912 if (!empty($profile['country'])) {
913 $loc['country-name'] = $profile['country'];
915 $location = Profile::formatLocation($loc);
916 if (!empty($location)) {
917 $data['location'] = $location;
925 * Perform a webfinger request.
927 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
929 * @param string $url Address that should be probed
930 * @param string $type type
932 * @return array webfinger data
933 * @throws HTTPException\InternalServerErrorException
935 public static function webfinger($url, $type)
937 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
939 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
940 if ($curlResult->isTimeout()) {
941 self::$istimeout = true;
944 $data = $curlResult->getBody();
946 $webfinger = json_decode($data, true);
947 if (!empty($webfinger)) {
948 if (!isset($webfinger["links"])) {
949 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
955 // If it is not JSON, maybe it is XML
956 $xrd = XML::parseString($data, true);
957 if (!is_object($xrd)) {
958 Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
962 $xrd_arr = XML::elementToArray($xrd);
963 if (!isset($xrd_arr["xrd"]["link"])) {
964 Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
970 if (!empty($xrd_arr["xrd"]["subject"])) {
971 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
974 if (!empty($xrd_arr["xrd"]["alias"])) {
975 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
978 $webfinger["links"] = [];
980 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
981 if (!empty($data["@attributes"])) {
982 $attributes = $data["@attributes"];
983 } elseif ($value == "@attributes") {
989 $webfinger["links"][] = $attributes;
995 * Poll the Friendica specific noscrape page.
997 * "noscrape" is a faster alternative to fetch the data from the hcard.
998 * This functionality was originally created for the directory.
1000 * @param string $noscrape_url Link to the noscrape page
1001 * @param array $data The already fetched data
1003 * @return array noscrape data
1004 * @throws HTTPException\InternalServerErrorException
1006 private static function pollNoscrape($noscrape_url, $data)
1008 $curlResult = Network::curl($noscrape_url);
1009 if ($curlResult->isTimeout()) {
1010 self::$istimeout = true;
1013 $content = $curlResult->getBody();
1015 Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
1019 $json = json_decode($content, true);
1020 if (!is_array($json)) {
1021 Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
1025 if (!empty($json["fn"])) {
1026 $data["name"] = $json["fn"];
1029 if (!empty($json["addr"])) {
1030 $data["addr"] = $json["addr"];
1033 if (!empty($json["nick"])) {
1034 $data["nick"] = $json["nick"];
1037 if (!empty($json["guid"])) {
1038 $data["guid"] = $json["guid"];
1041 if (!empty($json["comm"])) {
1042 $data["community"] = $json["comm"];
1045 if (!empty($json["tags"])) {
1046 $keywords = implode(", ", $json["tags"]);
1047 if ($keywords != "") {
1048 $data["keywords"] = $keywords;
1052 $location = Profile::formatLocation($json);
1054 $data["location"] = $location;
1057 if (!empty($json["about"])) {
1058 $data["about"] = $json["about"];
1061 if (!empty($json["key"])) {
1062 $data["pubkey"] = $json["key"];
1065 if (!empty($json["photo"])) {
1066 $data["photo"] = $json["photo"];
1069 if (!empty($json["dfrn-request"])) {
1070 $data["request"] = $json["dfrn-request"];
1073 if (!empty($json["dfrn-confirm"])) {
1074 $data["confirm"] = $json["dfrn-confirm"];
1077 if (!empty($json["dfrn-notify"])) {
1078 $data["notify"] = $json["dfrn-notify"];
1081 if (!empty($json["dfrn-poll"])) {
1082 $data["poll"] = $json["dfrn-poll"];
1085 if (isset($json["hide"])) {
1086 $data["hide"] = (bool)$json["hide"];
1088 $data["hide"] = false;
1095 * Check for valid DFRN data
1097 * @param array $data DFRN data
1099 * @return int Number of errors
1101 public static function validDfrn($data)
1104 if (!isset($data['key'])) {
1107 if (!isset($data['dfrn-request'])) {
1110 if (!isset($data['dfrn-confirm'])) {
1113 if (!isset($data['dfrn-notify'])) {
1116 if (!isset($data['dfrn-poll'])) {
1123 * Fetch data from a DFRN profile page and via "noscrape"
1125 * @param string $profile_link Link to the profile page
1127 * @return array profile data
1128 * @throws HTTPException\InternalServerErrorException
1129 * @throws \ImagickException
1131 public static function profile($profile_link)
1135 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
1137 // Fetch data via noscrape - this is faster
1138 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1139 $data = self::pollNoscrape($noscrape_url, $data);
1141 if (!isset($data["notify"])
1142 || !isset($data["confirm"])
1143 || !isset($data["request"])
1144 || !isset($data["poll"])
1145 || !isset($data["name"])
1146 || !isset($data["photo"])
1148 $data = self::pollHcard($profile_link, $data, true);
1153 if (empty($data["addr"]) || empty($data["nick"])) {
1154 $probe_data = self::uri($profile_link);
1155 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1156 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1159 $prof_data["addr"] = $data["addr"];
1160 $prof_data["nick"] = $data["nick"];
1161 $prof_data["dfrn-request"] = $data['request'] ?? null;
1162 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1163 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1164 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1165 $prof_data["photo"] = $data['photo'] ?? null;
1166 $prof_data["fn"] = $data['name'] ?? null;
1167 $prof_data["key"] = $data['pubkey'] ?? null;
1169 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
1175 * Check for DFRN contact
1177 * @param array $webfinger Webfinger data
1179 * @return array DFRN data
1180 * @throws HTTPException\InternalServerErrorException
1182 private static function dfrn($webfinger)
1186 // The array is reversed to take into account the order of preference for same-rel links
1187 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1188 foreach (array_reverse($webfinger["links"]) as $link) {
1189 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1190 $data["network"] = Protocol::DFRN;
1191 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1192 $data["poll"] = $link["href"];
1193 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1194 $data["url"] = $link["href"];
1195 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1196 $hcard_url = $link["href"];
1197 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1198 $data["poco"] = $link["href"];
1199 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1200 $data["photo"] = $link["href"];
1201 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1202 $data["baseurl"] = trim($link["href"], '/');
1203 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1204 $data["guid"] = $link["href"];
1205 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1206 $data["pubkey"] = base64_decode($link["href"]);
1208 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1209 if (strstr($data["pubkey"], 'RSA ')) {
1210 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1215 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1216 foreach ($webfinger["aliases"] as $alias) {
1217 if (empty($data["url"]) && !strstr($alias, "@")) {
1218 $data["url"] = $alias;
1219 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1220 $data["alias"] = $alias;
1221 } elseif (substr($alias, 0, 5) == 'acct:') {
1222 $data["addr"] = substr($alias, 5);
1227 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1228 $data["addr"] = substr($webfinger["subject"], 5);
1231 if (!isset($data["network"]) || ($hcard_url == "")) {
1235 // Fetch data via noscrape - this is faster
1236 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1237 $data = self::pollNoscrape($noscrape_url, $data);
1239 if (isset($data["notify"])
1240 && isset($data["confirm"])
1241 && isset($data["request"])
1242 && isset($data["poll"])
1243 && isset($data["name"])
1244 && isset($data["photo"])
1249 $data = self::pollHcard($hcard_url, $data, true);
1255 * Poll the hcard page (Diaspora and Friendica specific)
1257 * @param string $hcard_url Link to the hcard page
1258 * @param array $data The already fetched data
1259 * @param boolean $dfrn Poll DFRN specific data
1261 * @return array hcard data
1262 * @throws HTTPException\InternalServerErrorException
1264 private static function pollHcard($hcard_url, $data, $dfrn = false)
1266 $curlResult = Network::curl($hcard_url);
1267 if ($curlResult->isTimeout()) {
1268 self::$istimeout = true;
1271 $content = $curlResult->getBody();
1276 $doc = new DOMDocument();
1277 if (!@$doc->loadHTML($content)) {
1281 $xpath = new DomXPath($doc);
1283 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1284 if (!is_object($vcards)) {
1288 if (!isset($data["baseurl"])) {
1289 $data["baseurl"] = "";
1292 if ($vcards->length > 0) {
1293 $vcard = $vcards->item(0);
1295 // We have to discard the guid from the hcard in favour of the guid from lrdd
1296 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1297 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1298 if (($search->length > 0) && empty($data["guid"])) {
1299 $data["guid"] = $search->item(0)->nodeValue;
1302 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1303 if ($search->length > 0) {
1304 $data["nick"] = $search->item(0)->nodeValue;
1307 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1308 if ($search->length > 0) {
1309 $data["name"] = $search->item(0)->nodeValue;
1312 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1313 if ($search->length > 0) {
1314 $data["searchable"] = $search->item(0)->nodeValue;
1317 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1318 if ($search->length > 0) {
1319 $data["pubkey"] = $search->item(0)->nodeValue;
1320 if (strstr($data["pubkey"], 'RSA ')) {
1321 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1325 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1326 if ($search->length > 0) {
1327 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1332 if (!empty($vcard)) {
1333 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1334 foreach ($photos as $photo) {
1336 foreach ($photo->attributes as $attribute) {
1337 $attr[$attribute->name] = trim($attribute->value);
1340 if (isset($attr["src"]) && isset($attr["width"])) {
1341 $avatar[$attr["width"]] = $attr["src"];
1344 // We don't have a width. So we just take everything that we got.
1345 // This is a Hubzilla workaround which doesn't send a width.
1346 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1347 $avatar[] = $attr["src"];
1352 if (sizeof($avatar)) {
1354 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1358 // Poll DFRN specific data
1359 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1360 if ($search->length > 0) {
1361 foreach ($search as $link) {
1362 //$data["request"] = $search->item(0)->nodeValue;
1364 foreach ($link->attributes as $attribute) {
1365 $attr[$attribute->name] = trim($attribute->value);
1368 $data[substr($attr["rel"], 5)] = $attr["href"];
1372 // Older Friendica versions had used the "uid" field differently than newer versions
1373 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1374 unset($data["guid"]);
1383 * Check for Diaspora contact
1385 * @param array $webfinger Webfinger data
1387 * @return array Diaspora data
1388 * @throws HTTPException\InternalServerErrorException
1390 private static function diaspora($webfinger)
1395 // The array is reversed to take into account the order of preference for same-rel links
1396 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1397 foreach (array_reverse($webfinger["links"]) as $link) {
1398 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1399 $hcard_url = $link["href"];
1400 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1401 $data["baseurl"] = trim($link["href"], '/');
1402 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1403 $data["guid"] = $link["href"];
1404 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1405 $data["url"] = $link["href"];
1406 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1407 $data["poll"] = $link["href"];
1408 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1409 $data["poco"] = $link["href"];
1410 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1411 $data["notify"] = $link["href"];
1412 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1413 $data["pubkey"] = base64_decode($link["href"]);
1415 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1416 if (strstr($data["pubkey"], 'RSA ')) {
1417 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1422 if (empty($data["url"]) || empty($hcard_url)) {
1426 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1427 foreach ($webfinger["aliases"] as $alias) {
1428 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1429 $data["alias"] = $alias;
1430 } elseif (substr($alias, 0, 5) == 'acct:') {
1431 $data["addr"] = substr($alias, 5);
1436 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1437 $data["addr"] = substr($webfinger["subject"], 5);
1440 // Fetch further information from the hcard
1441 $data = self::pollHcard($hcard_url, $data);
1447 if (!empty($data["url"])
1448 && !empty($data["guid"])
1449 && !empty($data["baseurl"])
1450 && !empty($data["pubkey"])
1451 && !empty($hcard_url)
1453 $data["network"] = Protocol::DIASPORA;
1455 // The Diaspora handle must always be lowercase
1456 if (!empty($data["addr"])) {
1457 $data["addr"] = strtolower($data["addr"]);
1460 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1461 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1462 $data["batch"] = $data["baseurl"] . "/receive/public";
1471 * Check for OStatus contact
1473 * @param array $webfinger Webfinger data
1474 * @param bool $short Short detection mode
1476 * @return array|bool OStatus data or "false" on error or "true" on short mode
1477 * @throws HTTPException\InternalServerErrorException
1479 private static function ostatus($webfinger, $short = false)
1483 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1484 foreach ($webfinger["aliases"] as $alias) {
1485 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1486 $data["addr"] = str_replace('acct:', '', $alias);
1491 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1492 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1494 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1497 if (!empty($webfinger["links"])) {
1498 // The array is reversed to take into account the order of preference for same-rel links
1499 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1500 foreach (array_reverse($webfinger["links"]) as $link) {
1501 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1502 && (($link["type"] ?? "") == "text/html")
1503 && ($link["href"] != "")
1505 $data["url"] = $data["alias"] = $link["href"];
1506 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1507 $data["notify"] = $link["href"];
1508 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1509 $data["poll"] = $link["href"];
1510 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1511 $pubkey = $link["href"];
1513 if (substr($pubkey, 0, 5) === 'data:') {
1514 if (strstr($pubkey, ',')) {
1515 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1517 $pubkey = substr($pubkey, 5);
1519 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1520 $curlResult = Network::curl($pubkey);
1521 if ($curlResult->isTimeout()) {
1522 self::$istimeout = true;
1523 return $short ? false : [];
1525 $pubkey = $curlResult->getBody();
1528 $key = explode(".", $pubkey);
1530 if (sizeof($key) >= 3) {
1531 $m = Strings::base64UrlDecode($key[1]);
1532 $e = Strings::base64UrlDecode($key[2]);
1533 $data["pubkey"] = Crypto::meToPem($m, $e);
1539 if (isset($data["notify"]) && isset($data["pubkey"])
1540 && isset($data["poll"])
1541 && isset($data["url"])
1543 $data["network"] = Protocol::OSTATUS;
1545 return $short ? false : [];
1552 // Fetch all additional data from the feed
1553 $curlResult = Network::curl($data["poll"]);
1554 if ($curlResult->isTimeout()) {
1555 self::$istimeout = true;
1558 $feed = $curlResult->getBody();
1559 $feed_data = Feed::import($feed);
1564 if (!empty($feed_data["header"]["author-name"])) {
1565 $data["name"] = $feed_data["header"]["author-name"];
1567 if (!empty($feed_data["header"]["author-nick"])) {
1568 $data["nick"] = $feed_data["header"]["author-nick"];
1570 if (!empty($feed_data["header"]["author-avatar"])) {
1571 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1573 if (!empty($feed_data["header"]["author-id"])) {
1574 $data["alias"] = $feed_data["header"]["author-id"];
1576 if (!empty($feed_data["header"]["author-location"])) {
1577 $data["location"] = $feed_data["header"]["author-location"];
1579 if (!empty($feed_data["header"]["author-about"])) {
1580 $data["about"] = $feed_data["header"]["author-about"];
1582 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1583 // So we take the value that we just fetched, although the other one worked as well
1584 if (!empty($feed_data["header"]["author-link"])) {
1585 $data["url"] = $feed_data["header"]["author-link"];
1588 if ($data["url"] == $data["alias"]) {
1589 $data["alias"] = '';
1592 /// @todo Fetch location and "about" from the feed as well
1597 * Fetch data from a pump.io profile page
1599 * @param string $profile_link Link to the profile page
1601 * @return array profile data
1603 private static function pumpioProfileData($profile_link)
1605 $curlResult = Network::curl($profile_link);
1606 if (!$curlResult->isSuccess()) {
1610 $doc = new DOMDocument();
1611 if (!@$doc->loadHTML($curlResult->getBody())) {
1615 $xpath = new DomXPath($doc);
1619 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1621 if ($data["name"] == '') {
1622 // This is ugly - but pump.io doesn't seem to know a better way for it
1623 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1624 $pos = strpos($data["name"], chr(10));
1626 $data["name"] = trim(substr($data["name"], 0, $pos));
1630 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1632 if ($data["location"] == '') {
1633 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1636 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1638 if ($data["about"] == '') {
1639 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1642 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1644 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1647 foreach ($avatar->attributes as $attribute) {
1648 if ($attribute->name == "src") {
1649 $data["photo"] = trim($attribute->value);
1658 * Check for pump.io contact
1660 * @param array $webfinger Webfinger data
1661 * @param string $addr
1662 * @return array pump.io data
1664 private static function pumpio($webfinger, $addr)
1667 // The array is reversed to take into account the order of preference for same-rel links
1668 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1669 foreach (array_reverse($webfinger["links"]) as $link) {
1670 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1671 && (($link["type"] ?? "") == "text/html")
1672 && ($link["href"] != "")
1674 $data["url"] = $link["href"];
1675 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1676 $data["notify"] = $link["href"];
1677 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1678 $data["poll"] = $link["href"];
1679 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1680 $data["dialback"] = $link["href"];
1683 if (isset($data["poll"]) && isset($data["notify"])
1684 && isset($data["dialback"])
1685 && isset($data["url"])
1687 // by now we use these fields only for the network type detection
1688 // So we unset all data that isn't used at the moment
1689 unset($data["dialback"]);
1691 $data["network"] = Protocol::PUMPIO;
1696 $profile_data = self::pumpioProfileData($data["url"]);
1698 if (!$profile_data) {
1702 $data = array_merge($data, $profile_data);
1704 if (($addr != '') && ($data['name'] != '')) {
1705 $name = trim(str_replace($addr, '', $data['name']));
1707 $data['name'] = $name;
1715 * Check for twitter contact
1717 * @param string $uri
1719 * @return array twitter data
1721 private static function twitter($uri)
1723 if (preg_match('=(.*)@twitter.com=i', $uri, $matches)) {
1724 $nick = $matches[1];
1725 } elseif (preg_match('=https?://twitter.com/(.*)=i', $uri, $matches)) {
1726 $nick = $matches[1];
1732 $data['url'] = 'https://twitter.com/' . $nick;
1733 $data['addr'] = $nick . '@twitter.com';
1734 $data['nick'] = $data['name'] = $nick;
1735 $data['network'] = Protocol::TWITTER;
1736 $data['baseurl'] = 'https://twitter.com';
1742 * Checks HTML page for RSS feed link
1744 * @param string $url Page link
1745 * @param string $body Page body string
1746 * @return string|false Feed link or false if body was invalid HTML document
1748 public static function getFeedLink(string $url, string $body)
1750 $doc = new DOMDocument();
1751 if (!@$doc->loadHTML($body)) {
1755 $xpath = new DOMXPath($doc);
1757 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1759 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1765 * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1767 * Loosely based on RFC 1808
1769 * @see https://tools.ietf.org/html/rfc1808
1771 * @param string $href The potential relative href found in the HTML document
1772 * @param string $base The HTML document URL
1773 * @param DOMXPath $xpath The HTML document XPath
1776 private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath)
1778 if (filter_var($href, FILTER_VALIDATE_URL)) {
1782 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1784 $baseParts = parse_url($base);
1786 // Naked domain case (scheme://basehost)
1787 $path = $baseParts['path'] ?? '/';
1789 // Remove the filename part of the path if it exists (/base/path/file)
1790 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1792 $hrefParts = parse_url($href);
1794 // Root path case (/path) including relative scheme case (//host/path)
1795 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1796 $path = $hrefParts['path'];
1798 $path = $path . '/' . $hrefParts['path'];
1800 // Resolve arbitrary relative path
1801 // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1802 $parts = array_filter(explode('/', $path), 'strlen');
1803 $absolutes = array();
1804 foreach ($parts as $part) {
1805 if ('.' == $part) continue;
1806 if ('..' == $part) {
1807 array_pop($absolutes);
1809 $absolutes[] = $part;
1813 $path = '/' . implode('/', $absolutes);
1816 // Relative scheme case (//host/path)
1817 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1818 $baseParts['path'] = $path;
1819 unset($baseParts['query']);
1820 unset($baseParts['fragment']);
1822 return Network::unparseURL($baseParts);
1826 * Check for feed contact
1828 * @param string $url Profile link
1829 * @param boolean $probe Do a probe if the page contains a feed link
1831 * @return array feed data
1832 * @throws HTTPException\InternalServerErrorException
1834 private static function feed($url, $probe = true)
1836 $curlResult = Network::curl($url);
1837 if ($curlResult->isTimeout()) {
1838 self::$istimeout = true;
1841 $feed = $curlResult->getBody();
1842 $feed_data = Feed::import($feed);
1849 $feed_url = self::getFeedLink($url, $feed);
1855 return self::feed($feed_url, false);
1858 if (!empty($feed_data["header"]["author-name"])) {
1859 $data["name"] = $feed_data["header"]["author-name"];
1862 if (!empty($feed_data["header"]["author-nick"])) {
1863 $data["nick"] = $feed_data["header"]["author-nick"];
1866 if (!empty($feed_data["header"]["author-avatar"])) {
1867 $data["photo"] = $feed_data["header"]["author-avatar"];
1870 if (!empty($feed_data["header"]["author-id"])) {
1871 $data["alias"] = $feed_data["header"]["author-id"];
1874 $data["url"] = $url;
1875 $data["poll"] = $url;
1877 $data["network"] = Protocol::FEED;
1883 * Check for mail contact
1885 * @param string $uri Profile link
1886 * @param integer $uid User ID
1888 * @return array mail data
1889 * @throws \Exception
1891 private static function mail($uri, $uid)
1893 if (!Network::isEmailDomainValid($uri)) {
1901 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1903 $condition = ["`uid` = ? AND `server` != ''", $uid];
1904 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1905 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1907 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1911 $mailbox = Email::constructMailboxName($mailacct);
1913 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1914 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1919 $msgs = Email::poll($mbox, $uri);
1920 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1922 if (!count($msgs)) {
1926 $phost = substr($uri, strpos($uri, '@') + 1);
1929 $data["addr"] = $uri;
1930 $data["network"] = Protocol::MAIL;
1931 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1932 $data["nick"] = $data["name"];
1933 $data["photo"] = Network::lookupAvatarByEmail($uri);
1934 $data["url"] = 'mailto:'.$uri;
1935 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1936 $data["poll"] = 'email ' . Strings::getRandomHex();
1938 $x = Email::messageMeta($mbox, $msgs[0]);
1939 if (stristr($x[0]->from, $uri)) {
1940 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1941 } elseif (stristr($x[0]->to, $uri)) {
1942 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1945 foreach ($adr as $feadr) {
1946 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1947 &&(strcasecmp($feadr->host, $phost) == 0)
1948 && (strlen($feadr->personal))
1950 $personal = imap_mime_header_decode($feadr->personal);
1952 foreach ($personal as $perspart) {
1953 if ($perspart->charset != "default") {
1954 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1956 $data["name"] .= $perspart->text;
1960 $data["name"] = Strings::escapeTags($data["name"]);
1964 if (!empty($mbox)) {
1971 * Mix two paths together to possibly fix missing parts
1973 * @param string $avatar Path to the avatar
1974 * @param string $base Another path that is hopefully complete
1976 * @return string fixed avatar path
1977 * @throws \Exception
1979 public static function fixAvatar($avatar, $base)
1981 $base_parts = parse_url($base);
1983 // Remove all parts that could create a problem
1984 unset($base_parts['path']);
1985 unset($base_parts['query']);
1986 unset($base_parts['fragment']);
1988 $avatar_parts = parse_url($avatar);
1991 $parts = array_merge($base_parts, $avatar_parts);
1993 // And put them together again
1994 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1995 $host = isset($parts['host']) ? $parts['host'] : '';
1996 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1997 $path = isset($parts['path']) ? $parts['path'] : '';
1998 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1999 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
2001 $fixed = $scheme.$host.$port.$path.$query.$fragment;
2003 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);