3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Network;
26 use Friendica\Core\Cache\Duration;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Database\DBA;
31 use Friendica\Model\Contact;
32 use Friendica\Model\Profile;
33 use Friendica\Protocol\ActivityNamespace;
34 use Friendica\Protocol\ActivityPub;
35 use Friendica\Protocol\Email;
36 use Friendica\Protocol\Feed;
37 use Friendica\Util\Crypto;
38 use Friendica\Util\Network;
39 use Friendica\Util\Strings;
40 use Friendica\Util\XML;
43 * This class contain functions for probing URL
47 private static $baseurl;
48 private static $istimeout;
51 * Rearrange the array so that it always has the same order
53 * @param array $data Unordered data
55 * @return array Ordered data
57 private static function rearrangeData($data)
59 $fields = ["name", "nick", "guid", "url", "addr", "alias", "photo", "account-type",
60 "community", "keywords", "location", "about", "gender", "hide",
61 "batch", "notify", "poll", "request", "confirm", "poco",
62 "following", "followers", "inbox", "outbox", "sharedinbox",
63 "priority", "network", "pubkey", "baseurl"];
66 foreach ($fields as $field) {
67 if (isset($data[$field])) {
68 $newdata[$field] = $data[$field];
70 $newdata[$field] = "";
74 // We don't use the "priority" field anymore and replace it with a dummy.
75 $newdata["priority"] = 0;
81 * Check if the hostname belongs to the own server
83 * @param string $host The hostname that is to be checked
85 * @return bool Does the testes hostname belongs to the own server?
87 private static function ownHost($host)
89 $own_host = DI::baseUrl()->getHostname();
91 $parts = parse_url($host);
93 if (!isset($parts['scheme'])) {
94 $parts = parse_url('http://'.$host);
97 if (!isset($parts['host'])) {
100 return $parts['host'] == $own_host;
104 * Probes for webfinger path via "host-meta"
106 * We have to check if the servers in the future still will offer this.
107 * It seems as if it was dropped from the standard.
109 * @param string $host The host part of an url
111 * @return array with template and type of the webfinger template for JSON or XML
112 * @throws HTTPException\InternalServerErrorException
114 private static function hostMeta($host)
116 // Reset the static variable
119 $ssl_url = "https://".$host."/.well-known/host-meta";
120 $url = "http://".$host."/.well-known/host-meta";
122 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
124 Logger::log("Probing for ".$host, Logger::DEBUG);
127 $curlResult = Network::curl($ssl_url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
128 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
129 if ($curlResult->isSuccess()) {
130 $xml = $curlResult->getBody();
131 $xrd = XML::parseString($xml, false);
132 $host_url = 'https://'.$host;
133 } elseif ($curlResult->isTimeout()) {
134 Logger::info('Probing timeout', ['url' => $ssl_url], Logger::DEBUG);
135 self::$istimeout = true;
139 if (!is_object($xrd)) {
140 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
141 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
142 if ($curlResult->isTimeout()) {
143 Logger::info('Probing timeout', ['url' => $url], Logger::DEBUG);
144 self::$istimeout = true;
146 } elseif ($connection_error && $ssl_connection_error) {
147 self::$istimeout = true;
151 $xml = $curlResult->getBody();
152 $xrd = XML::parseString($xml, false);
153 $host_url = 'http://'.$host;
155 if (!is_object($xrd)) {
156 Logger::log("No xrd object found for ".$host, Logger::DEBUG);
160 $links = XML::elementToArray($xrd);
161 if (!isset($links["xrd"]["link"])) {
162 Logger::log("No xrd data found for ".$host, Logger::DEBUG);
166 $lrdd = ['application/jrd+json' => $host_url . '/.well-known/webfinger?resource={uri}'];
168 foreach ($links["xrd"]["link"] as $value => $link) {
169 if (!empty($link["@attributes"])) {
170 $attributes = $link["@attributes"];
171 } elseif ($value == "@attributes") {
177 if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
178 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
180 $lrdd[$type] = $attributes["template"];
184 self::$baseurl = $host_url;
186 Logger::log("Probing successful for ".$host, Logger::DEBUG);
192 * Perform Webfinger lookup and return DFRN data
194 * Given an email style address, perform webfinger lookup and
195 * return the resulting DFRN profile URL, or if no DFRN profile URL
196 * is located, returns an OStatus subscription template (prefixed
197 * with the string 'stat:' to identify it as on OStatus template).
198 * If this isn't an email style address just return $webbie.
199 * Return an empty string if email-style addresses but webfinger fails,
200 * or if the resultant personal XRD doesn't contain a supported
201 * subscription/friend-request attribute.
203 * amended 7/9/2011 to return an hcard which could save potentially loading
204 * a lengthy content page to scrape dfrn attributes
206 * @param string $webbie Address that should be probed
207 * @param string $hcard_url Link to the hcard - is returned by reference
209 * @return string profile link
210 * @throws HTTPException\InternalServerErrorException
212 public static function webfingerDfrn($webbie, &$hcard_url)
216 $links = self::lrdd($webbie);
217 Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA);
218 if (!empty($links) && is_array($links)) {
219 foreach ($links as $link) {
220 if ($link['@attributes']['rel'] === ActivityNamespace::DFRN) {
221 $profile_link = $link['@attributes']['href'];
223 if (($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) && ($profile_link == "")) {
224 $profile_link = 'stat:'.$link['@attributes']['template'];
226 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
227 $hcard_url = $link['@attributes']['href'];
231 return $profile_link;
235 * Check an URI for LRDD data
237 * this is a replacement for the "lrdd" function.
238 * It isn't used in this class and has some redundancies in the code.
239 * When time comes we can check the existing calls for "lrdd" if we can rework them.
241 * @param string $uri Address that should be probed
243 * @return array uri data
244 * @throws HTTPException\InternalServerErrorException
246 public static function lrdd($uri)
248 $lrdd = self::hostMeta($uri);
251 if (is_bool($lrdd)) {
256 $parts = @parse_url($uri);
257 if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
261 $host = $parts["host"];
262 if (!empty($parts["port"])) {
263 $host .= ':'.$parts["port"];
266 $path_parts = explode("/", trim($parts["path"], "/"));
268 $nick = array_pop($path_parts);
271 $lrdd = self::hostMeta($host);
272 $host .= "/".array_shift($path_parts);
273 } while (!$lrdd && (sizeof($path_parts) > 0));
277 Logger::log("No lrdd data found for ".$uri, Logger::DEBUG);
281 foreach ($lrdd as $type => $template) {
286 $path = str_replace('{uri}', urlencode($uri), $template);
287 $webfinger = self::webfinger($path, $type);
289 if (!$webfinger && (strstr($uri, "@"))) {
290 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
291 $webfinger = self::webfinger($path, $type);
294 // Special treatment for Mastodon
295 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
296 // But the webfinger for this format fails.
297 if (!$webfinger && !empty($nick)) {
298 // Mastodon uses a "@" as prefix for usernames in their url format
299 $nick = ltrim($nick, '@');
301 $addr = $nick."@".$host;
303 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
304 $webfinger = self::webfinger($path, $type);
308 if (!is_array($webfinger["links"])) {
309 Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
315 foreach ($webfinger["links"] as $link) {
316 $data[] = ["@attributes" => $link];
319 if (is_array($webfinger["aliases"])) {
320 foreach ($webfinger["aliases"] as $alias) {
321 $data[] = ["@attributes" =>
331 * Fetch information (protocol endpoints and user information) about a given uri
333 * @param string $uri Address that should be probed
334 * @param string $network Test for this specific network
335 * @param integer $uid User ID for the probe (only used for mails)
336 * @param boolean $cache Use cached values?
338 * @return array uri data
339 * @throws HTTPException\InternalServerErrorException
340 * @throws \ImagickException
342 public static function uri($uri, $network = '', $uid = -1, $cache = true)
345 $result = DI::cache()->get('Probe::uri:' . $network . ':' . $uri);
346 if (!is_null($result)) {
355 self::$istimeout = false;
357 if ($network != Protocol::ACTIVITYPUB) {
358 $data = self::detect($uri, $network, $uid);
363 // When the previous detection process had got a time out
364 // we could falsely detect a Friendica profile as AP profile.
365 if (!self::$istimeout) {
366 $ap_profile = ActivityPub::probeProfile($uri);
368 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
370 } elseif (!empty($ap_profile)) {
371 $ap_profile['batch'] = '';
372 $data = array_merge($ap_profile, $data);
375 Logger::notice('Time out detected. AP will not be probed.', ['uri' => $uri]);
378 if (!isset($data['url'])) {
382 if (!empty($data['photo']) && !empty($data['baseurl'])) {
383 $data['baseurl'] = Network::getUrlMatch(Strings::normaliseLink($data['baseurl']), Strings::normaliseLink($data['photo']));
384 } elseif (empty($data['photo'])) {
385 $data['photo'] = DI::baseUrl() . '/images/person-300.jpg';
388 if (empty($data['name'])) {
389 if (!empty($data['nick'])) {
390 $data['name'] = $data['nick'];
393 if (empty($data['name'])) {
394 $data['name'] = $data['url'];
398 if (empty($data['nick'])) {
399 $data['nick'] = strtolower($data['name']);
401 if (strpos($data['nick'], ' ')) {
402 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
406 if (!empty(self::$baseurl)) {
407 $data['baseurl'] = self::$baseurl;
410 if (empty($data['network'])) {
411 $data['network'] = Protocol::PHANTOM;
414 // Ensure that local connections always are DFRN
415 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
416 $data['network'] = Protocol::DFRN;
419 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
420 $data['hide'] = self::getHideStatus($data['url']);
423 $data = self::rearrangeData($data);
425 // Only store into the cache if the value seems to be valid
426 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
427 DI::cache()->set('Probe::uri:' . $network . ':' . $uri, $data, Duration::DAY);
435 * Fetches the "hide" status from the profile
437 * @param string $url URL of the profile
439 * @return boolean "hide" status
441 private static function getHideStatus($url)
443 $curlResult = Network::curl($url);
444 if (!$curlResult->isSuccess()) {
448 // If the file is too large then exit
449 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
453 // If it isn't a HTML file then exit
454 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
458 $body = $curlResult->getBody();
460 $doc = new DOMDocument();
461 @$doc->loadHTML($body);
463 $xpath = new DOMXPath($doc);
465 $list = $xpath->query('//meta[@name]');
466 foreach ($list as $node) {
468 if ($node->attributes->length) {
469 foreach ($node->attributes as $attribute) {
470 $meta_tag[$attribute->name] = $attribute->value;
474 if (empty($meta_tag['content'])) {
478 $content = strtolower(trim($meta_tag['content']));
480 switch (strtolower(trim($meta_tag['name']))) {
481 case 'dfrn-global-visibility':
482 if ($content == 'false') {
487 if (strpos($content, 'noindex') !== false) {
498 * Checks if a profile url should be OStatus but only provides partial information
500 * @param array $webfinger Webfinger data
501 * @param string $lrdd Path template for webfinger request
502 * @param string $type type
504 * @return array fixed webfinger data
505 * @throws HTTPException\InternalServerErrorException
507 private static function fixOStatus($webfinger, $lrdd, $type)
509 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
516 foreach ($webfinger['links'] as $link) {
517 if ($link['rel'] == ActivityNamespace::OSTATUSSUB) {
520 if ($link['rel'] == 'magic-public-key') {
525 if (!$is_ostatus || $has_key) {
529 $url = Network::switchScheme($webfinger['subject']);
530 $path = str_replace('{uri}', urlencode($url), $lrdd);
531 $webfinger2 = self::webfinger($path, $type);
533 // Is the new webfinger detectable as OStatus?
534 if (self::ostatus($webfinger2, true)) {
535 $webfinger = $webfinger2;
542 * Fetch information (protocol endpoints and user information) about a given uri
544 * This function is only called by the "uri" function that adds caching and rearranging of data.
546 * @param string $uri Address that should be probed
547 * @param string $network Test for this specific network
548 * @param integer $uid User ID for the probe (only used for mails)
550 * @return array uri data
551 * @throws HTTPException\InternalServerErrorException
553 private static function detect($uri, $network, $uid)
555 $parts = parse_url($uri);
557 if (!empty($parts["scheme"]) && !empty($parts["host"])) {
558 $host = $parts["host"];
559 if (!empty($parts["port"])) {
560 $host .= ':'.$parts["port"];
563 if ($host == 'twitter.com') {
564 return self::twitter($uri);
566 $lrdd = self::hostMeta($host);
568 if (is_bool($lrdd)) {
572 $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
574 while (!$lrdd && (sizeof($path_parts) > 1)) {
575 $host .= "/".array_shift($path_parts);
576 $lrdd = self::hostMeta($host);
579 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
580 return self::feed($uri);
582 $nick = array_pop($path_parts);
584 // Mastodon uses a "@" as prefix for usernames in their url format
585 $nick = ltrim($nick, '@');
587 $addr = $nick."@".$host;
588 } elseif (strstr($uri, '@')) {
589 // If the URI starts with "mailto:" then jump directly to the mail detection
590 if (strpos($uri, 'mailto:') !== false) {
591 $uri = str_replace('mailto:', '', $uri);
592 return self::mail($uri, $uid);
595 if ($network == Protocol::MAIL) {
596 return self::mail($uri, $uid);
598 // Remove "acct:" from the URI
599 $uri = str_replace('acct:', '', $uri);
601 $host = substr($uri, strpos($uri, '@') + 1);
602 $nick = substr($uri, 0, strpos($uri, '@'));
604 if (strpos($uri, '@twitter.com')) {
605 return self::twitter($uri);
607 $lrdd = self::hostMeta($host);
609 if (is_bool($lrdd)) {
614 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
615 return self::mail($uri, $uid);
619 Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
625 /// @todo Do we need the prefix "acct:" or "acct://"?
627 foreach ($lrdd as $type => $template) {
632 // At first try it with the given uri
633 $path = str_replace('{uri}', urlencode($uri), $template);
634 $webfinger = self::webfinger($path, $type);
636 // Fix possible problems with GNU Social probing to wrong scheme
637 $webfinger = self::fixOStatus($webfinger, $template, $type);
639 // We cannot be sure that the detected address was correct, so we don't use the values
640 if ($webfinger && ($uri != $addr)) {
645 // Try webfinger with the address (user@domain.tld)
647 $path = str_replace('{uri}', urlencode($addr), $template);
648 $webfinger = self::webfinger($path, $type);
651 // Mastodon needs to have it with "acct:"
653 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
654 $webfinger = self::webfinger($path, $type);
659 return self::feed($uri);
664 Logger::log("Probing ".$uri, Logger::DEBUG);
666 if (in_array($network, ["", Protocol::DFRN])) {
667 $result = self::dfrn($webfinger);
669 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
670 $result = self::diaspora($webfinger);
672 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
673 $result = self::ostatus($webfinger);
675 if (in_array($network, ['', Protocol::ZOT])) {
676 $result = self::zot($webfinger, $result);
678 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
679 $result = self::pumpio($webfinger, $addr);
681 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
682 $result = self::feed($uri);
684 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
685 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
686 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
687 $result["nick"] = $nick;
690 if (empty($result["addr"]) && ($addr != "")) {
691 $result["addr"] = $addr;
695 if (empty($result["network"])) {
696 $result["network"] = Protocol::PHANTOM;
699 if (empty($result["url"])) {
700 $result["url"] = $uri;
703 Logger::log($uri." is ".$result["network"], Logger::DEBUG);
705 if (empty($result["baseurl"]) && ($result["network"] != Protocol::PHANTOM)) {
706 $pos = strpos($result["url"], $host);
708 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
715 * Check for Zot contact
717 * @param array $webfinger Webfinger data
718 * @param array $data previously probed data
720 * @return array Zot data
721 * @throws HTTPException\InternalServerErrorException
723 private static function zot($webfinger, $data)
725 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
726 foreach ($webfinger["aliases"] as $alias) {
727 if (substr($alias, 0, 5) == 'acct:') {
728 $data["addr"] = substr($alias, 5);
733 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
734 $data["addr"] = substr($webfinger["subject"], 5);
738 foreach ($webfinger['links'] as $link) {
739 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
740 $zot_url = $link['href'];
744 if (empty($zot_url) && !empty($data['addr']) && !empty(self::$baseurl)) {
745 $condition = ['nurl' => Strings::normaliseLink(self::$baseurl), 'platform' => ['hubzilla']];
746 if (!DBA::exists('gserver', $condition)) {
749 $zot_url = self::$baseurl . '/.well-known/zot-info?address=' . $data['addr'];
752 if (empty($zot_url)) {
756 $data = self::pollZot($zot_url, $data);
758 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
759 foreach ($webfinger['aliases'] as $alias) {
760 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
761 $data['alias'] = $alias;
769 public static function pollZot($url, $data)
771 $curlResult = Network::curl($url);
772 if ($curlResult->isTimeout()) {
775 $content = $curlResult->getBody();
780 $json = json_decode($content, true);
781 if (!is_array($json)) {
785 if (empty($data['network'])) {
786 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
787 $data['network'] = Protocol::ZOT;
788 } elseif (!isset($json['protocols'])) {
789 $data['network'] = Protocol::ZOT;
793 if (!empty($json['guid']) && empty($data['guid'])) {
794 $data['guid'] = $json['guid'];
796 if (!empty($json['key']) && empty($data['pubkey'])) {
797 $data['pubkey'] = $json['key'];
799 if (!empty($json['name'])) {
800 $data['name'] = $json['name'];
802 if (!empty($json['photo'])) {
803 $data['photo'] = $json['photo'];
804 if (!empty($json['photo_updated'])) {
805 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
808 if (!empty($json['address'])) {
809 $data['addr'] = $json['address'];
811 if (!empty($json['url'])) {
812 $data['url'] = $json['url'];
814 if (!empty($json['connections_url'])) {
815 $data['poco'] = $json['connections_url'];
817 if (isset($json['searchable'])) {
818 $data['hide'] = !$json['searchable'];
820 if (!empty($json['public_forum'])) {
821 $data['community'] = $json['public_forum'];
822 $data['account-type'] = Contact::PAGE_COMMUNITY;
825 if (!empty($json['profile'])) {
826 $profile = $json['profile'];
827 if (!empty($profile['description'])) {
828 $data['about'] = $profile['description'];
830 if (!empty($profile['gender'])) {
831 $data['gender'] = $profile['gender'];
833 if (!empty($profile['keywords'])) {
834 $keywords = implode(', ', $profile['keywords']);
835 if (!empty($keywords)) {
836 $data['keywords'] = $keywords;
841 if (!empty($profile['region'])) {
842 $loc['region'] = $profile['region'];
844 if (!empty($profile['country'])) {
845 $loc['country-name'] = $profile['country'];
847 $location = Profile::formatLocation($loc);
848 if (!empty($location)) {
849 $data['location'] = $location;
857 * Perform a webfinger request.
859 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
861 * @param string $url Address that should be probed
862 * @param string $type type
864 * @return array webfinger data
865 * @throws HTTPException\InternalServerErrorException
867 private static function webfinger($url, $type)
869 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
871 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
872 if ($curlResult->isTimeout()) {
873 self::$istimeout = true;
876 $data = $curlResult->getBody();
878 $webfinger = json_decode($data, true);
879 if (is_array($webfinger)) {
880 if (!isset($webfinger["links"])) {
881 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
887 // If it is not JSON, maybe it is XML
888 $xrd = XML::parseString($data, false);
889 if (!is_object($xrd)) {
890 Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
894 $xrd_arr = XML::elementToArray($xrd);
895 if (!isset($xrd_arr["xrd"]["link"])) {
896 Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
902 if (!empty($xrd_arr["xrd"]["subject"])) {
903 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
906 if (!empty($xrd_arr["xrd"]["alias"])) {
907 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
910 $webfinger["links"] = [];
912 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
913 if (!empty($data["@attributes"])) {
914 $attributes = $data["@attributes"];
915 } elseif ($value == "@attributes") {
921 $webfinger["links"][] = $attributes;
927 * Poll the Friendica specific noscrape page.
929 * "noscrape" is a faster alternative to fetch the data from the hcard.
930 * This functionality was originally created for the directory.
932 * @param string $noscrape_url Link to the noscrape page
933 * @param array $data The already fetched data
935 * @return array noscrape data
936 * @throws HTTPException\InternalServerErrorException
938 private static function pollNoscrape($noscrape_url, $data)
940 $curlResult = Network::curl($noscrape_url);
941 if ($curlResult->isTimeout()) {
942 self::$istimeout = true;
945 $content = $curlResult->getBody();
947 Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
951 $json = json_decode($content, true);
952 if (!is_array($json)) {
953 Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
957 if (!empty($json["fn"])) {
958 $data["name"] = $json["fn"];
961 if (!empty($json["addr"])) {
962 $data["addr"] = $json["addr"];
965 if (!empty($json["nick"])) {
966 $data["nick"] = $json["nick"];
969 if (!empty($json["guid"])) {
970 $data["guid"] = $json["guid"];
973 if (!empty($json["comm"])) {
974 $data["community"] = $json["comm"];
977 if (!empty($json["tags"])) {
978 $keywords = implode(", ", $json["tags"]);
979 if ($keywords != "") {
980 $data["keywords"] = $keywords;
984 $location = Profile::formatLocation($json);
986 $data["location"] = $location;
989 if (!empty($json["about"])) {
990 $data["about"] = $json["about"];
993 if (!empty($json["gender"])) {
994 $data["gender"] = $json["gender"];
997 if (!empty($json["key"])) {
998 $data["pubkey"] = $json["key"];
1001 if (!empty($json["photo"])) {
1002 $data["photo"] = $json["photo"];
1005 if (!empty($json["dfrn-request"])) {
1006 $data["request"] = $json["dfrn-request"];
1009 if (!empty($json["dfrn-confirm"])) {
1010 $data["confirm"] = $json["dfrn-confirm"];
1013 if (!empty($json["dfrn-notify"])) {
1014 $data["notify"] = $json["dfrn-notify"];
1017 if (!empty($json["dfrn-poll"])) {
1018 $data["poll"] = $json["dfrn-poll"];
1021 if (isset($json["hide"])) {
1022 $data["hide"] = (bool)$json["hide"];
1024 $data["hide"] = false;
1031 * Check for valid DFRN data
1033 * @param array $data DFRN data
1035 * @return int Number of errors
1037 public static function validDfrn($data)
1040 if (!isset($data['key'])) {
1043 if (!isset($data['dfrn-request'])) {
1046 if (!isset($data['dfrn-confirm'])) {
1049 if (!isset($data['dfrn-notify'])) {
1052 if (!isset($data['dfrn-poll'])) {
1059 * Fetch data from a DFRN profile page and via "noscrape"
1061 * @param string $profile_link Link to the profile page
1063 * @return array profile data
1064 * @throws HTTPException\InternalServerErrorException
1065 * @throws \ImagickException
1067 public static function profile($profile_link)
1071 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
1073 // Fetch data via noscrape - this is faster
1074 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1075 $data = self::pollNoscrape($noscrape_url, $data);
1077 if (!isset($data["notify"])
1078 || !isset($data["confirm"])
1079 || !isset($data["request"])
1080 || !isset($data["poll"])
1081 || !isset($data["name"])
1082 || !isset($data["photo"])
1084 $data = self::pollHcard($profile_link, $data, true);
1089 if (empty($data["addr"]) || empty($data["nick"])) {
1090 $probe_data = self::uri($profile_link);
1091 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1092 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1095 $prof_data["addr"] = $data["addr"];
1096 $prof_data["nick"] = $data["nick"];
1097 $prof_data["dfrn-request"] = $data['request'] ?? null;
1098 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1099 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1100 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1101 $prof_data["photo"] = $data['photo'] ?? null;
1102 $prof_data["fn"] = $data['name'] ?? null;
1103 $prof_data["key"] = $data['pubkey'] ?? null;
1105 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
1111 * Check for DFRN contact
1113 * @param array $webfinger Webfinger data
1115 * @return array DFRN data
1116 * @throws HTTPException\InternalServerErrorException
1118 private static function dfrn($webfinger)
1122 // The array is reversed to take into account the order of preference for same-rel links
1123 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1124 foreach (array_reverse($webfinger["links"]) as $link) {
1125 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1126 $data["network"] = Protocol::DFRN;
1127 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1128 $data["poll"] = $link["href"];
1129 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1130 $data["url"] = $link["href"];
1131 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1132 $hcard_url = $link["href"];
1133 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1134 $data["poco"] = $link["href"];
1135 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1136 $data["photo"] = $link["href"];
1137 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1138 $data["baseurl"] = trim($link["href"], '/');
1139 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1140 $data["guid"] = $link["href"];
1141 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1142 $data["pubkey"] = base64_decode($link["href"]);
1144 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1145 if (strstr($data["pubkey"], 'RSA ')) {
1146 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1151 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1152 foreach ($webfinger["aliases"] as $alias) {
1153 if (empty($data["url"]) && !strstr($alias, "@")) {
1154 $data["url"] = $alias;
1155 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1156 $data["alias"] = $alias;
1157 } elseif (substr($alias, 0, 5) == 'acct:') {
1158 $data["addr"] = substr($alias, 5);
1163 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1164 $data["addr"] = substr($webfinger["subject"], 5);
1167 if (!isset($data["network"]) || ($hcard_url == "")) {
1171 // Fetch data via noscrape - this is faster
1172 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1173 $data = self::pollNoscrape($noscrape_url, $data);
1175 if (isset($data["notify"])
1176 && isset($data["confirm"])
1177 && isset($data["request"])
1178 && isset($data["poll"])
1179 && isset($data["name"])
1180 && isset($data["photo"])
1185 $data = self::pollHcard($hcard_url, $data, true);
1191 * Poll the hcard page (Diaspora and Friendica specific)
1193 * @param string $hcard_url Link to the hcard page
1194 * @param array $data The already fetched data
1195 * @param boolean $dfrn Poll DFRN specific data
1197 * @return array hcard data
1198 * @throws HTTPException\InternalServerErrorException
1200 private static function pollHcard($hcard_url, $data, $dfrn = false)
1202 $curlResult = Network::curl($hcard_url);
1203 if ($curlResult->isTimeout()) {
1204 self::$istimeout = true;
1207 $content = $curlResult->getBody();
1212 $doc = new DOMDocument();
1213 if (!@$doc->loadHTML($content)) {
1217 $xpath = new DomXPath($doc);
1219 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1220 if (!is_object($vcards)) {
1224 if (!isset($data["baseurl"])) {
1225 $data["baseurl"] = "";
1228 if ($vcards->length > 0) {
1229 $vcard = $vcards->item(0);
1231 // We have to discard the guid from the hcard in favour of the guid from lrdd
1232 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1233 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1234 if (($search->length > 0) && empty($data["guid"])) {
1235 $data["guid"] = $search->item(0)->nodeValue;
1238 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1239 if ($search->length > 0) {
1240 $data["nick"] = $search->item(0)->nodeValue;
1243 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1244 if ($search->length > 0) {
1245 $data["name"] = $search->item(0)->nodeValue;
1248 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1249 if ($search->length > 0) {
1250 $data["searchable"] = $search->item(0)->nodeValue;
1253 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1254 if ($search->length > 0) {
1255 $data["pubkey"] = $search->item(0)->nodeValue;
1256 if (strstr($data["pubkey"], 'RSA ')) {
1257 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1261 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1262 if ($search->length > 0) {
1263 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1268 if (!empty($vcard)) {
1269 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1270 foreach ($photos as $photo) {
1272 foreach ($photo->attributes as $attribute) {
1273 $attr[$attribute->name] = trim($attribute->value);
1276 if (isset($attr["src"]) && isset($attr["width"])) {
1277 $avatar[$attr["width"]] = $attr["src"];
1280 // We don't have a width. So we just take everything that we got.
1281 // This is a Hubzilla workaround which doesn't send a width.
1282 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1283 $avatar[] = $attr["src"];
1288 if (sizeof($avatar)) {
1290 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1294 // Poll DFRN specific data
1295 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1296 if ($search->length > 0) {
1297 foreach ($search as $link) {
1298 //$data["request"] = $search->item(0)->nodeValue;
1300 foreach ($link->attributes as $attribute) {
1301 $attr[$attribute->name] = trim($attribute->value);
1304 $data[substr($attr["rel"], 5)] = $attr["href"];
1308 // Older Friendica versions had used the "uid" field differently than newer versions
1309 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1310 unset($data["guid"]);
1319 * Check for Diaspora contact
1321 * @param array $webfinger Webfinger data
1323 * @return array Diaspora data
1324 * @throws HTTPException\InternalServerErrorException
1326 private static function diaspora($webfinger)
1331 // The array is reversed to take into account the order of preference for same-rel links
1332 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1333 foreach (array_reverse($webfinger["links"]) as $link) {
1334 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1335 $hcard_url = $link["href"];
1336 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1337 $data["baseurl"] = trim($link["href"], '/');
1338 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1339 $data["guid"] = $link["href"];
1340 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1341 $data["url"] = $link["href"];
1342 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1343 $data["poll"] = $link["href"];
1344 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1345 $data["poco"] = $link["href"];
1346 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1347 $data["notify"] = $link["href"];
1348 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1349 $data["pubkey"] = base64_decode($link["href"]);
1351 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1352 if (strstr($data["pubkey"], 'RSA ')) {
1353 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1358 if (empty($data["url"]) || empty($hcard_url)) {
1362 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1363 foreach ($webfinger["aliases"] as $alias) {
1364 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1365 $data["alias"] = $alias;
1366 } elseif (substr($alias, 0, 5) == 'acct:') {
1367 $data["addr"] = substr($alias, 5);
1372 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1373 $data["addr"] = substr($webfinger["subject"], 5);
1376 // Fetch further information from the hcard
1377 $data = self::pollHcard($hcard_url, $data);
1383 if (!empty($data["url"])
1384 && !empty($data["guid"])
1385 && !empty($data["baseurl"])
1386 && !empty($data["pubkey"])
1387 && !empty($hcard_url)
1389 $data["network"] = Protocol::DIASPORA;
1391 // The Diaspora handle must always be lowercase
1392 if (!empty($data["addr"])) {
1393 $data["addr"] = strtolower($data["addr"]);
1396 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1397 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1398 $data["batch"] = $data["baseurl"] . "/receive/public";
1407 * Check for OStatus contact
1409 * @param array $webfinger Webfinger data
1410 * @param bool $short Short detection mode
1412 * @return array|bool OStatus data or "false" on error or "true" on short mode
1413 * @throws HTTPException\InternalServerErrorException
1415 private static function ostatus($webfinger, $short = false)
1419 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1420 foreach ($webfinger["aliases"] as $alias) {
1421 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1422 $data["addr"] = str_replace('acct:', '', $alias);
1427 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1428 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1430 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1433 if (is_array($webfinger["links"])) {
1434 // The array is reversed to take into account the order of preference for same-rel links
1435 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1436 foreach (array_reverse($webfinger["links"]) as $link) {
1437 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1438 && (($link["type"] ?? "") == "text/html")
1439 && ($link["href"] != "")
1441 $data["url"] = $link["href"];
1442 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1443 $data["notify"] = $link["href"];
1444 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1445 $data["poll"] = $link["href"];
1446 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1447 $pubkey = $link["href"];
1449 if (substr($pubkey, 0, 5) === 'data:') {
1450 if (strstr($pubkey, ',')) {
1451 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1453 $pubkey = substr($pubkey, 5);
1455 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1456 $curlResult = Network::curl($pubkey);
1457 if ($curlResult->isTimeout()) {
1458 self::$istimeout = true;
1461 $pubkey = $curlResult->getBody();
1464 $key = explode(".", $pubkey);
1466 if (sizeof($key) >= 3) {
1467 $m = Strings::base64UrlDecode($key[1]);
1468 $e = Strings::base64UrlDecode($key[2]);
1469 $data["pubkey"] = Crypto::meToPem($m, $e);
1475 if (isset($data["notify"]) && isset($data["pubkey"])
1476 && isset($data["poll"])
1477 && isset($data["url"])
1479 $data["network"] = Protocol::OSTATUS;
1488 // Fetch all additional data from the feed
1489 $curlResult = Network::curl($data["poll"]);
1490 if ($curlResult->isTimeout()) {
1491 self::$istimeout = true;
1494 $feed = $curlResult->getBody();
1495 $feed_data = Feed::import($feed);
1500 if (!empty($feed_data["header"]["author-name"])) {
1501 $data["name"] = $feed_data["header"]["author-name"];
1503 if (!empty($feed_data["header"]["author-nick"])) {
1504 $data["nick"] = $feed_data["header"]["author-nick"];
1506 if (!empty($feed_data["header"]["author-avatar"])) {
1507 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1509 if (!empty($feed_data["header"]["author-id"])) {
1510 $data["alias"] = $feed_data["header"]["author-id"];
1512 if (!empty($feed_data["header"]["author-location"])) {
1513 $data["location"] = $feed_data["header"]["author-location"];
1515 if (!empty($feed_data["header"]["author-about"])) {
1516 $data["about"] = $feed_data["header"]["author-about"];
1518 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1519 // So we take the value that we just fetched, although the other one worked as well
1520 if (!empty($feed_data["header"]["author-link"])) {
1521 $data["url"] = $feed_data["header"]["author-link"];
1524 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1525 $data['url'] = $data["alias"];
1526 $data["alias"] = '';
1529 /// @todo Fetch location and "about" from the feed as well
1534 * Fetch data from a pump.io profile page
1536 * @param string $profile_link Link to the profile page
1538 * @return array profile data
1540 private static function pumpioProfileData($profile_link)
1542 $curlResult = Network::curl($profile_link);
1543 if (!$curlResult->isSuccess()) {
1547 $doc = new DOMDocument();
1548 if (!@$doc->loadHTML($curlResult->getBody())) {
1552 $xpath = new DomXPath($doc);
1556 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1558 if ($data["name"] == '') {
1559 // This is ugly - but pump.io doesn't seem to know a better way for it
1560 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1561 $pos = strpos($data["name"], chr(10));
1563 $data["name"] = trim(substr($data["name"], 0, $pos));
1567 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1569 if ($data["location"] == '') {
1570 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1573 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1575 if ($data["about"] == '') {
1576 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1579 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1581 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1584 foreach ($avatar->attributes as $attribute) {
1585 if ($attribute->name == "src") {
1586 $data["photo"] = trim($attribute->value);
1595 * Check for pump.io contact
1597 * @param array $webfinger Webfinger data
1598 * @param string $addr
1599 * @return array pump.io data
1601 private static function pumpio($webfinger, $addr)
1604 // The array is reversed to take into account the order of preference for same-rel links
1605 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1606 foreach (array_reverse($webfinger["links"]) as $link) {
1607 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1608 && (($link["type"] ?? "") == "text/html")
1609 && ($link["href"] != "")
1611 $data["url"] = $link["href"];
1612 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1613 $data["notify"] = $link["href"];
1614 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1615 $data["poll"] = $link["href"];
1616 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1617 $data["dialback"] = $link["href"];
1620 if (isset($data["poll"]) && isset($data["notify"])
1621 && isset($data["dialback"])
1622 && isset($data["url"])
1624 // by now we use these fields only for the network type detection
1625 // So we unset all data that isn't used at the moment
1626 unset($data["dialback"]);
1628 $data["network"] = Protocol::PUMPIO;
1633 $profile_data = self::pumpioProfileData($data["url"]);
1635 if (!$profile_data) {
1639 $data = array_merge($data, $profile_data);
1641 if (($addr != '') && ($data['name'] != '')) {
1642 $name = trim(str_replace($addr, '', $data['name']));
1644 $data['name'] = $name;
1652 * Check for twitter contact
1654 * @param string $uri
1656 * @return array twitter data
1658 private static function twitter($uri)
1660 if (preg_match('=(.*)@twitter.com=i', $uri, $matches)) {
1661 $nick = $matches[1];
1662 } elseif (preg_match('=https?://twitter.com/(.*)=i', $uri, $matches)) {
1663 $nick = $matches[1];
1669 $data['url'] = 'https://twitter.com/' . $nick;
1670 $data['addr'] = $nick . '@twitter.com';
1671 $data['nick'] = $data['name'] = $nick;
1672 $data['network'] = Protocol::TWITTER;
1673 $data['baseurl'] = 'https://twitter.com';
1675 $curlResult = Network::curl($data['url'], false);
1676 if (!$curlResult->isSuccess()) {
1680 $body = $curlResult->getBody();
1681 $doc = new DOMDocument();
1682 @$doc->loadHTML($body);
1683 $xpath = new DOMXPath($doc);
1685 $list = $xpath->query('//img[@class]');
1686 foreach ($list as $node) {
1688 if ($node->attributes->length) {
1689 foreach ($node->attributes as $attribute) {
1690 $img_attr[$attribute->name] = $attribute->value;
1694 if (empty($img_attr['class'])) {
1698 if (strpos($img_attr['class'], 'ProfileAvatar-image') !== false) {
1699 if (!empty($img_attr['src'])) {
1700 $data['photo'] = $img_attr['src'];
1702 if (!empty($img_attr['alt'])) {
1703 $data['name'] = $img_attr['alt'];
1712 * Check page for feed link
1714 * @param string $url Page link
1716 * @return string feed link
1718 private static function getFeedLink($url)
1720 $curlResult = Network::curl($url);
1721 if (!$curlResult->isSuccess()) {
1725 $doc = new DOMDocument();
1726 if (!@$doc->loadHTML($curlResult->getBody())) {
1730 $xpath = new DomXPath($doc);
1732 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1733 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1734 if (!is_object($feeds)) {
1738 if ($feeds->length == 0) {
1744 foreach ($feeds as $feed) {
1746 foreach ($feed->attributes as $attribute) {
1747 $attr[$attribute->name] = trim($attribute->value);
1750 if (empty($feed_url) && !empty($attr['href'])) {
1751 $feed_url = $attr["href"];
1759 * Check for feed contact
1761 * @param string $url Profile link
1762 * @param boolean $probe Do a probe if the page contains a feed link
1764 * @return array feed data
1765 * @throws HTTPException\InternalServerErrorException
1767 private static function feed($url, $probe = true)
1769 $curlResult = Network::curl($url);
1770 if ($curlResult->isTimeout()) {
1771 self::$istimeout = true;
1774 $feed = $curlResult->getBody();
1775 $feed_data = Feed::import($feed);
1782 $feed_url = self::getFeedLink($url);
1788 return self::feed($feed_url, false);
1791 if (!empty($feed_data["header"]["author-name"])) {
1792 $data["name"] = $feed_data["header"]["author-name"];
1795 if (!empty($feed_data["header"]["author-nick"])) {
1796 $data["nick"] = $feed_data["header"]["author-nick"];
1799 if (!empty($feed_data["header"]["author-avatar"])) {
1800 $data["photo"] = $feed_data["header"]["author-avatar"];
1803 if (!empty($feed_data["header"]["author-id"])) {
1804 $data["alias"] = $feed_data["header"]["author-id"];
1807 $data["url"] = $url;
1808 $data["poll"] = $url;
1810 if (!empty($feed_data["header"]["author-link"])) {
1811 $data["baseurl"] = $feed_data["header"]["author-link"];
1813 $data["baseurl"] = $data["url"];
1816 $data["network"] = Protocol::FEED;
1822 * Check for mail contact
1824 * @param string $uri Profile link
1825 * @param integer $uid User ID
1827 * @return array mail data
1828 * @throws \Exception
1830 private static function mail($uri, $uid)
1832 if (!Network::isEmailDomainValid($uri)) {
1840 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1842 $condition = ["`uid` = ? AND `server` != ''", $uid];
1843 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1844 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1846 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1850 $mailbox = Email::constructMailboxName($mailacct);
1852 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1853 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1858 $msgs = Email::poll($mbox, $uri);
1859 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1861 if (!count($msgs)) {
1865 $phost = substr($uri, strpos($uri, '@') + 1);
1868 $data["addr"] = $uri;
1869 $data["network"] = Protocol::MAIL;
1870 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1871 $data["nick"] = $data["name"];
1872 $data["photo"] = Network::lookupAvatarByEmail($uri);
1873 $data["url"] = 'mailto:'.$uri;
1874 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1875 $data["poll"] = 'email ' . Strings::getRandomHex();
1877 $x = Email::messageMeta($mbox, $msgs[0]);
1878 if (stristr($x[0]->from, $uri)) {
1879 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1880 } elseif (stristr($x[0]->to, $uri)) {
1881 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1884 foreach ($adr as $feadr) {
1885 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1886 &&(strcasecmp($feadr->host, $phost) == 0)
1887 && (strlen($feadr->personal))
1889 $personal = imap_mime_header_decode($feadr->personal);
1891 foreach ($personal as $perspart) {
1892 if ($perspart->charset != "default") {
1893 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1895 $data["name"] .= $perspart->text;
1899 $data["name"] = Strings::escapeTags($data["name"]);
1903 if (!empty($mbox)) {
1910 * Mix two paths together to possibly fix missing parts
1912 * @param string $avatar Path to the avatar
1913 * @param string $base Another path that is hopefully complete
1915 * @return string fixed avatar path
1916 * @throws \Exception
1918 public static function fixAvatar($avatar, $base)
1920 $base_parts = parse_url($base);
1922 // Remove all parts that could create a problem
1923 unset($base_parts['path']);
1924 unset($base_parts['query']);
1925 unset($base_parts['fragment']);
1927 $avatar_parts = parse_url($avatar);
1930 $parts = array_merge($base_parts, $avatar_parts);
1932 // And put them together again
1933 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1934 $host = isset($parts['host']) ? $parts['host'] : '';
1935 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1936 $path = isset($parts['path']) ? $parts['path'] : '';
1937 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1938 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1940 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1942 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);