3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Network;
26 use Friendica\Core\Cache\Duration;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\System;
30 use Friendica\Database\DBA;
32 use Friendica\Model\Contact;
33 use Friendica\Model\Profile;
34 use Friendica\Protocol\ActivityNamespace;
35 use Friendica\Protocol\ActivityPub;
36 use Friendica\Protocol\Email;
37 use Friendica\Protocol\Feed;
38 use Friendica\Util\Crypto;
39 use Friendica\Util\Network;
40 use Friendica\Util\Strings;
41 use Friendica\Util\XML;
44 * This class contain functions for probing URL
48 private static $baseurl;
49 private static $istimeout;
52 * Remove stuff from an URI that doesn't belong there
55 * @return string Cleaned URI
57 public static function cleanURI(string $URI)
59 // At first remove leading and trailing junk
60 $URI = trim($URI, "@#?:/ \t\n\r\0\x0B");
62 $parts = parse_url($URI);
64 if (empty($parts['scheme'])) {
68 // Remove the URL fragment, since these shouldn't be part of any profile URL
69 unset($parts['fragment']);
71 $URI = Network::unparseURL($parts);
77 * Rearrange the array so that it always has the same order
79 * @param array $data Unordered data
81 * @return array Ordered data
83 private static function rearrangeData($data)
85 $fields = ["name", "nick", "guid", "url", "addr", "alias", "photo", "account-type",
86 "community", "keywords", "location", "about", "hide",
87 "batch", "notify", "poll", "request", "confirm", "poco",
88 "following", "followers", "inbox", "outbox", "sharedinbox",
89 "priority", "network", "pubkey", "baseurl"];
92 foreach ($fields as $field) {
93 if (isset($data[$field])) {
94 $newdata[$field] = $data[$field];
96 $newdata[$field] = "";
100 // We don't use the "priority" field anymore and replace it with a dummy.
101 $newdata["priority"] = 0;
107 * Check if the hostname belongs to the own server
109 * @param string $host The hostname that is to be checked
111 * @return bool Does the testes hostname belongs to the own server?
113 private static function ownHost($host)
115 $own_host = DI::baseUrl()->getHostname();
117 $parts = parse_url($host);
119 if (!isset($parts['scheme'])) {
120 $parts = parse_url('http://'.$host);
123 if (!isset($parts['host'])) {
126 return $parts['host'] == $own_host;
130 * Probes for webfinger path via "host-meta"
132 * We have to check if the servers in the future still will offer this.
133 * It seems as if it was dropped from the standard.
135 * @param string $host The host part of an url
137 * @return array with template and type of the webfinger template for JSON or XML
138 * @throws HTTPException\InternalServerErrorException
140 private static function hostMeta($host)
142 // Reset the static variable
145 // Handles the case when the hostname contains the scheme
146 if (!parse_url($host, PHP_URL_SCHEME)) {
147 $ssl_url = "https://" . $host . "/.well-known/host-meta";
148 $url = "http://" . $host . "/.well-known/host-meta";
150 $ssl_url = $host . "/.well-known/host-meta";
154 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
156 Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url, 'callstack' => System::callstack(20)]);
159 $curlResult = Network::curl($ssl_url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
160 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
161 if ($curlResult->isSuccess()) {
162 $xml = $curlResult->getBody();
163 $xrd = XML::parseString($xml, false);
164 $host_url = 'https://'.$host;
165 } elseif ($curlResult->isTimeout()) {
166 Logger::info('Probing timeout', ['url' => $ssl_url], Logger::DEBUG);
167 self::$istimeout = true;
171 if (!is_object($xrd) && !empty($url)) {
172 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
173 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
174 if ($curlResult->isTimeout()) {
175 Logger::info('Probing timeout', ['url' => $url], Logger::DEBUG);
176 self::$istimeout = true;
178 } elseif ($connection_error && $ssl_connection_error) {
179 self::$istimeout = true;
183 $xml = $curlResult->getBody();
184 $xrd = XML::parseString($xml, false);
185 $host_url = 'http://'.$host;
187 if (!is_object($xrd)) {
188 Logger::log("No xrd object found for ".$host, Logger::DEBUG);
192 $links = XML::elementToArray($xrd);
193 if (!isset($links["xrd"]["link"])) {
194 Logger::log("No xrd data found for ".$host, Logger::DEBUG);
198 $lrdd = ['application/jrd+json' => $host_url . '/.well-known/webfinger?resource={uri}'];
200 foreach ($links["xrd"]["link"] as $value => $link) {
201 if (!empty($link["@attributes"])) {
202 $attributes = $link["@attributes"];
203 } elseif ($value == "@attributes") {
209 if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
210 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
212 $lrdd[$type] = $attributes["template"];
216 self::$baseurl = $host_url;
218 Logger::log("Probing successful for ".$host, Logger::DEBUG);
224 * Perform Webfinger lookup and return DFRN data
226 * Given an email style address, perform webfinger lookup and
227 * return the resulting DFRN profile URL, or if no DFRN profile URL
228 * is located, returns an OStatus subscription template (prefixed
229 * with the string 'stat:' to identify it as on OStatus template).
230 * If this isn't an email style address just return $webbie.
231 * Return an empty string if email-style addresses but webfinger fails,
232 * or if the resultant personal XRD doesn't contain a supported
233 * subscription/friend-request attribute.
235 * amended 7/9/2011 to return an hcard which could save potentially loading
236 * a lengthy content page to scrape dfrn attributes
238 * @param string $webbie Address that should be probed
239 * @param string $hcard_url Link to the hcard - is returned by reference
241 * @return string profile link
242 * @throws HTTPException\InternalServerErrorException
244 public static function webfingerDfrn($webbie, &$hcard_url)
248 $links = self::lrdd($webbie);
249 Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA);
250 if (!empty($links) && is_array($links)) {
251 foreach ($links as $link) {
252 if ($link['@attributes']['rel'] === ActivityNamespace::DFRN) {
253 $profile_link = $link['@attributes']['href'];
255 if (($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) && ($profile_link == "")) {
256 $profile_link = 'stat:'.$link['@attributes']['template'];
258 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
259 $hcard_url = $link['@attributes']['href'];
263 return $profile_link;
267 * Get the link for the remote follow page for a given profile link
269 * @param sting $profile
270 * @return string Remote follow page link
272 public static function getRemoteFollowLink(string $profile)
276 $links = self::lrdd($profile);
278 if (!empty($links) && is_array($links)) {
279 foreach ($links as $link) {
280 if ($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) {
281 $follow_link = $link['@attributes']['template'];
289 * Check an URI for LRDD data
291 * @param string $uri Address that should be probed
293 * @return array uri data
294 * @throws HTTPException\InternalServerErrorException
296 public static function lrdd($uri)
298 $lrdd = self::hostMeta($uri);
301 if (is_bool($lrdd)) {
306 $parts = @parse_url($uri);
307 if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
311 $host = $parts['scheme'] . '://' . $parts["host"];
312 if (!empty($parts["port"])) {
313 $host .= ':'.$parts["port"];
316 $path_parts = explode("/", trim($parts["path"], "/"));
318 $nick = array_pop($path_parts);
321 $lrdd = self::hostMeta($host);
322 $host .= "/".array_shift($path_parts);
323 } while (!$lrdd && (sizeof($path_parts) > 0));
327 Logger::log("No lrdd data found for ".$uri, Logger::DEBUG);
331 foreach ($lrdd as $type => $template) {
336 $path = str_replace('{uri}', urlencode($uri), $template);
337 $webfinger = self::webfinger($path, $type);
339 if (!$webfinger && (strstr($uri, "@"))) {
340 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
341 $webfinger = self::webfinger($path, $type);
344 // Special treatment for Mastodon
345 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
346 // But the webfinger for this format fails.
347 if (!$webfinger && !empty($nick)) {
348 // Mastodon uses a "@" as prefix for usernames in their url format
349 $nick = ltrim($nick, '@');
351 $addr = $nick."@".$host;
353 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
354 $webfinger = self::webfinger($path, $type);
358 if (!is_array($webfinger["links"])) {
359 Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
365 foreach ($webfinger["links"] as $link) {
366 $data[] = ["@attributes" => $link];
369 if (is_array($webfinger["aliases"])) {
370 foreach ($webfinger["aliases"] as $alias) {
371 $data[] = ["@attributes" =>
381 * Fetch information (protocol endpoints and user information) about a given uri
383 * @param string $uri Address that should be probed
384 * @param string $network Test for this specific network
385 * @param integer $uid User ID for the probe (only used for mails)
386 * @param boolean $cache Use cached values?
388 * @return array uri data
389 * @throws HTTPException\InternalServerErrorException
390 * @throws \ImagickException
392 public static function uri($uri, $network = '', $uid = -1, $cache = true)
395 $result = DI::cache()->get('Probe::uri:' . $network . ':' . $uri);
396 if (!is_null($result)) {
405 self::$istimeout = false;
407 if ($network != Protocol::ACTIVITYPUB) {
408 $data = self::detect($uri, $network, $uid);
413 // When the previous detection process had got a time out
414 // we could falsely detect a Friendica profile as AP profile.
415 if (!self::$istimeout) {
416 $ap_profile = ActivityPub::probeProfile($uri);
418 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
420 } elseif (!empty($ap_profile)) {
421 $ap_profile['batch'] = '';
422 $data = array_merge($ap_profile, $data);
425 Logger::notice('Time out detected. AP will not be probed.', ['uri' => $uri]);
428 if (!isset($data['url'])) {
432 if (!empty($data['photo']) && !empty($data['baseurl'])) {
433 $data['baseurl'] = Network::getUrlMatch(Strings::normaliseLink($data['baseurl']), Strings::normaliseLink($data['photo']));
434 } elseif (empty($data['photo'])) {
435 $data['photo'] = DI::baseUrl() . '/images/person-300.jpg';
438 if (empty($data['name'])) {
439 if (!empty($data['nick'])) {
440 $data['name'] = $data['nick'];
443 if (empty($data['name'])) {
444 $data['name'] = $data['url'];
448 if (empty($data['nick'])) {
449 $data['nick'] = strtolower($data['name']);
451 if (strpos($data['nick'], ' ')) {
452 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
456 if (!empty(self::$baseurl)) {
457 $data['baseurl'] = self::$baseurl;
460 if (empty($data['network'])) {
461 $data['network'] = Protocol::PHANTOM;
464 // Ensure that local connections always are DFRN
465 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
466 $data['network'] = Protocol::DFRN;
469 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
470 $data['hide'] = self::getHideStatus($data['url']);
473 $data = self::rearrangeData($data);
475 // Only store into the cache if the value seems to be valid
476 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
477 DI::cache()->set('Probe::uri:' . $network . ':' . $uri, $data, Duration::DAY);
485 * Fetches the "hide" status from the profile
487 * @param string $url URL of the profile
489 * @return boolean "hide" status
491 private static function getHideStatus($url)
493 $curlResult = Network::curl($url);
494 if (!$curlResult->isSuccess()) {
498 // If the file is too large then exit
499 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
503 // If it isn't a HTML file then exit
504 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
508 $body = $curlResult->getBody();
510 $doc = new DOMDocument();
511 @$doc->loadHTML($body);
513 $xpath = new DOMXPath($doc);
515 $list = $xpath->query('//meta[@name]');
516 foreach ($list as $node) {
518 if ($node->attributes->length) {
519 foreach ($node->attributes as $attribute) {
520 $meta_tag[$attribute->name] = $attribute->value;
524 if (empty($meta_tag['content'])) {
528 $content = strtolower(trim($meta_tag['content']));
530 switch (strtolower(trim($meta_tag['name']))) {
531 case 'dfrn-global-visibility':
532 if ($content == 'false') {
537 if (strpos($content, 'noindex') !== false) {
548 * Checks if a profile url should be OStatus but only provides partial information
550 * @param array $webfinger Webfinger data
551 * @param string $lrdd Path template for webfinger request
552 * @param string $type type
554 * @return array fixed webfinger data
555 * @throws HTTPException\InternalServerErrorException
557 private static function fixOStatus($webfinger, $lrdd, $type)
559 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
566 foreach ($webfinger['links'] as $link) {
567 if ($link['rel'] == ActivityNamespace::OSTATUSSUB) {
570 if ($link['rel'] == 'magic-public-key') {
575 if (!$is_ostatus || $has_key) {
579 $url = Network::switchScheme($webfinger['subject']);
580 $path = str_replace('{uri}', urlencode($url), $lrdd);
581 $webfinger2 = self::webfinger($path, $type);
583 // Is the new webfinger detectable as OStatus?
584 if (self::ostatus($webfinger2, true)) {
585 $webfinger = $webfinger2;
592 * Fetch information (protocol endpoints and user information) about a given uri
594 * This function is only called by the "uri" function that adds caching and rearranging of data.
596 * @param string $uri Address that should be probed
597 * @param string $network Test for this specific network
598 * @param integer $uid User ID for the probe (only used for mails)
600 * @return array uri data
601 * @throws HTTPException\InternalServerErrorException
603 private static function detect($uri, $network, $uid)
605 $parts = parse_url($uri);
607 if (!empty($parts["scheme"]) && !empty($parts["host"])) {
608 $host = $parts["host"];
609 if (!empty($parts["port"])) {
610 $host .= ':'.$parts["port"];
613 if ($host == 'twitter.com') {
614 return self::twitter($uri);
616 $lrdd = self::hostMeta($host);
618 if (is_bool($lrdd)) {
622 $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
624 while (!$lrdd && (sizeof($path_parts) > 1)) {
625 $host .= "/".array_shift($path_parts);
626 $lrdd = self::hostMeta($host);
629 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
630 return self::feed($uri);
632 $nick = array_pop($path_parts);
634 // Mastodon uses a "@" as prefix for usernames in their url format
635 $nick = ltrim($nick, '@');
637 $addr = $nick."@".$host;
638 } elseif (strstr($uri, '@')) {
639 // If the URI starts with "mailto:" then jump directly to the mail detection
640 if (strpos($uri, 'mailto:') !== false) {
641 $uri = str_replace('mailto:', '', $uri);
642 return self::mail($uri, $uid);
645 if ($network == Protocol::MAIL) {
646 return self::mail($uri, $uid);
648 // Remove "acct:" from the URI
649 $uri = str_replace('acct:', '', $uri);
651 $host = substr($uri, strpos($uri, '@') + 1);
652 $nick = substr($uri, 0, strpos($uri, '@'));
654 if (strpos($uri, '@twitter.com')) {
655 return self::twitter($uri);
657 $lrdd = self::hostMeta($host);
659 if (is_bool($lrdd)) {
664 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
665 return self::mail($uri, $uid);
669 Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
675 /// @todo Do we need the prefix "acct:" or "acct://"?
677 foreach ($lrdd as $type => $template) {
682 // At first try it with the given uri
683 $path = str_replace('{uri}', urlencode($uri), $template);
684 $webfinger = self::webfinger($path, $type);
686 // Fix possible problems with GNU Social probing to wrong scheme
687 $webfinger = self::fixOStatus($webfinger, $template, $type);
689 // We cannot be sure that the detected address was correct, so we don't use the values
690 if ($webfinger && ($uri != $addr)) {
695 // Try webfinger with the address (user@domain.tld)
697 $path = str_replace('{uri}', urlencode($addr), $template);
698 $webfinger = self::webfinger($path, $type);
701 // Mastodon needs to have it with "acct:"
703 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
704 $webfinger = self::webfinger($path, $type);
709 return self::feed($uri);
714 Logger::log("Probing ".$uri, Logger::DEBUG);
716 if (in_array($network, ["", Protocol::DFRN])) {
717 $result = self::dfrn($webfinger);
719 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
720 $result = self::diaspora($webfinger);
722 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
723 $result = self::ostatus($webfinger);
725 if (in_array($network, ['', Protocol::ZOT])) {
726 $result = self::zot($webfinger, $result);
728 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
729 $result = self::pumpio($webfinger, $addr);
731 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
732 $result = self::feed($uri);
734 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
735 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
736 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
737 $result["nick"] = $nick;
740 if (empty($result["addr"]) && ($addr != "")) {
741 $result["addr"] = $addr;
745 if (empty($result["network"])) {
746 $result["network"] = Protocol::PHANTOM;
749 if (empty($result["url"])) {
750 $result["url"] = $uri;
753 Logger::log($uri." is ".$result["network"], Logger::DEBUG);
755 if (empty($result["baseurl"]) && ($result["network"] != Protocol::PHANTOM)) {
756 $pos = strpos($result["url"], $host);
758 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
765 * Check for Zot contact
767 * @param array $webfinger Webfinger data
768 * @param array $data previously probed data
770 * @return array Zot data
771 * @throws HTTPException\InternalServerErrorException
773 private static function zot($webfinger, $data)
775 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
776 foreach ($webfinger["aliases"] as $alias) {
777 if (substr($alias, 0, 5) == 'acct:') {
778 $data["addr"] = substr($alias, 5);
783 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
784 $data["addr"] = substr($webfinger["subject"], 5);
788 foreach ($webfinger['links'] as $link) {
789 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
790 $zot_url = $link['href'];
794 if (empty($zot_url) && !empty($data['addr']) && !empty(self::$baseurl)) {
795 $condition = ['nurl' => Strings::normaliseLink(self::$baseurl), 'platform' => ['hubzilla']];
796 if (!DBA::exists('gserver', $condition)) {
799 $zot_url = self::$baseurl . '/.well-known/zot-info?address=' . $data['addr'];
802 if (empty($zot_url)) {
806 $data = self::pollZot($zot_url, $data);
808 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
809 foreach ($webfinger['aliases'] as $alias) {
810 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
811 $data['alias'] = $alias;
819 public static function pollZot($url, $data)
821 $curlResult = Network::curl($url);
822 if ($curlResult->isTimeout()) {
825 $content = $curlResult->getBody();
830 $json = json_decode($content, true);
831 if (!is_array($json)) {
835 if (empty($data['network'])) {
836 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
837 $data['network'] = Protocol::ZOT;
838 } elseif (!isset($json['protocols'])) {
839 $data['network'] = Protocol::ZOT;
843 if (!empty($json['guid']) && empty($data['guid'])) {
844 $data['guid'] = $json['guid'];
846 if (!empty($json['key']) && empty($data['pubkey'])) {
847 $data['pubkey'] = $json['key'];
849 if (!empty($json['name'])) {
850 $data['name'] = $json['name'];
852 if (!empty($json['photo'])) {
853 $data['photo'] = $json['photo'];
854 if (!empty($json['photo_updated'])) {
855 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
858 if (!empty($json['address'])) {
859 $data['addr'] = $json['address'];
861 if (!empty($json['url'])) {
862 $data['url'] = $json['url'];
864 if (!empty($json['connections_url'])) {
865 $data['poco'] = $json['connections_url'];
867 if (isset($json['searchable'])) {
868 $data['hide'] = !$json['searchable'];
870 if (!empty($json['public_forum'])) {
871 $data['community'] = $json['public_forum'];
872 $data['account-type'] = Contact::PAGE_COMMUNITY;
875 if (!empty($json['profile'])) {
876 $profile = $json['profile'];
877 if (!empty($profile['description'])) {
878 $data['about'] = $profile['description'];
880 if (!empty($profile['keywords'])) {
881 $keywords = implode(', ', $profile['keywords']);
882 if (!empty($keywords)) {
883 $data['keywords'] = $keywords;
888 if (!empty($profile['region'])) {
889 $loc['region'] = $profile['region'];
891 if (!empty($profile['country'])) {
892 $loc['country-name'] = $profile['country'];
894 $location = Profile::formatLocation($loc);
895 if (!empty($location)) {
896 $data['location'] = $location;
904 * Perform a webfinger request.
906 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
908 * @param string $url Address that should be probed
909 * @param string $type type
911 * @return array webfinger data
912 * @throws HTTPException\InternalServerErrorException
914 private static function webfinger($url, $type)
916 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
918 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
919 if ($curlResult->isTimeout()) {
920 self::$istimeout = true;
923 $data = $curlResult->getBody();
925 $webfinger = json_decode($data, true);
926 if (is_array($webfinger)) {
927 if (!isset($webfinger["links"])) {
928 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
934 // If it is not JSON, maybe it is XML
935 $xrd = XML::parseString($data, false);
936 if (!is_object($xrd)) {
937 Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
941 $xrd_arr = XML::elementToArray($xrd);
942 if (!isset($xrd_arr["xrd"]["link"])) {
943 Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
949 if (!empty($xrd_arr["xrd"]["subject"])) {
950 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
953 if (!empty($xrd_arr["xrd"]["alias"])) {
954 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
957 $webfinger["links"] = [];
959 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
960 if (!empty($data["@attributes"])) {
961 $attributes = $data["@attributes"];
962 } elseif ($value == "@attributes") {
968 $webfinger["links"][] = $attributes;
974 * Poll the Friendica specific noscrape page.
976 * "noscrape" is a faster alternative to fetch the data from the hcard.
977 * This functionality was originally created for the directory.
979 * @param string $noscrape_url Link to the noscrape page
980 * @param array $data The already fetched data
982 * @return array noscrape data
983 * @throws HTTPException\InternalServerErrorException
985 private static function pollNoscrape($noscrape_url, $data)
987 $curlResult = Network::curl($noscrape_url);
988 if ($curlResult->isTimeout()) {
989 self::$istimeout = true;
992 $content = $curlResult->getBody();
994 Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
998 $json = json_decode($content, true);
999 if (!is_array($json)) {
1000 Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
1004 if (!empty($json["fn"])) {
1005 $data["name"] = $json["fn"];
1008 if (!empty($json["addr"])) {
1009 $data["addr"] = $json["addr"];
1012 if (!empty($json["nick"])) {
1013 $data["nick"] = $json["nick"];
1016 if (!empty($json["guid"])) {
1017 $data["guid"] = $json["guid"];
1020 if (!empty($json["comm"])) {
1021 $data["community"] = $json["comm"];
1024 if (!empty($json["tags"])) {
1025 $keywords = implode(", ", $json["tags"]);
1026 if ($keywords != "") {
1027 $data["keywords"] = $keywords;
1031 $location = Profile::formatLocation($json);
1033 $data["location"] = $location;
1036 if (!empty($json["about"])) {
1037 $data["about"] = $json["about"];
1040 if (!empty($json["key"])) {
1041 $data["pubkey"] = $json["key"];
1044 if (!empty($json["photo"])) {
1045 $data["photo"] = $json["photo"];
1048 if (!empty($json["dfrn-request"])) {
1049 $data["request"] = $json["dfrn-request"];
1052 if (!empty($json["dfrn-confirm"])) {
1053 $data["confirm"] = $json["dfrn-confirm"];
1056 if (!empty($json["dfrn-notify"])) {
1057 $data["notify"] = $json["dfrn-notify"];
1060 if (!empty($json["dfrn-poll"])) {
1061 $data["poll"] = $json["dfrn-poll"];
1064 if (isset($json["hide"])) {
1065 $data["hide"] = (bool)$json["hide"];
1067 $data["hide"] = false;
1074 * Check for valid DFRN data
1076 * @param array $data DFRN data
1078 * @return int Number of errors
1080 public static function validDfrn($data)
1083 if (!isset($data['key'])) {
1086 if (!isset($data['dfrn-request'])) {
1089 if (!isset($data['dfrn-confirm'])) {
1092 if (!isset($data['dfrn-notify'])) {
1095 if (!isset($data['dfrn-poll'])) {
1102 * Fetch data from a DFRN profile page and via "noscrape"
1104 * @param string $profile_link Link to the profile page
1106 * @return array profile data
1107 * @throws HTTPException\InternalServerErrorException
1108 * @throws \ImagickException
1110 public static function profile($profile_link)
1114 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
1116 // Fetch data via noscrape - this is faster
1117 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1118 $data = self::pollNoscrape($noscrape_url, $data);
1120 if (!isset($data["notify"])
1121 || !isset($data["confirm"])
1122 || !isset($data["request"])
1123 || !isset($data["poll"])
1124 || !isset($data["name"])
1125 || !isset($data["photo"])
1127 $data = self::pollHcard($profile_link, $data, true);
1132 if (empty($data["addr"]) || empty($data["nick"])) {
1133 $probe_data = self::uri($profile_link);
1134 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1135 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1138 $prof_data["addr"] = $data["addr"];
1139 $prof_data["nick"] = $data["nick"];
1140 $prof_data["dfrn-request"] = $data['request'] ?? null;
1141 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1142 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1143 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1144 $prof_data["photo"] = $data['photo'] ?? null;
1145 $prof_data["fn"] = $data['name'] ?? null;
1146 $prof_data["key"] = $data['pubkey'] ?? null;
1148 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
1154 * Check for DFRN contact
1156 * @param array $webfinger Webfinger data
1158 * @return array DFRN data
1159 * @throws HTTPException\InternalServerErrorException
1161 private static function dfrn($webfinger)
1165 // The array is reversed to take into account the order of preference for same-rel links
1166 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1167 foreach (array_reverse($webfinger["links"]) as $link) {
1168 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1169 $data["network"] = Protocol::DFRN;
1170 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1171 $data["poll"] = $link["href"];
1172 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1173 $data["url"] = $link["href"];
1174 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1175 $hcard_url = $link["href"];
1176 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1177 $data["poco"] = $link["href"];
1178 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1179 $data["photo"] = $link["href"];
1180 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1181 $data["baseurl"] = trim($link["href"], '/');
1182 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1183 $data["guid"] = $link["href"];
1184 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1185 $data["pubkey"] = base64_decode($link["href"]);
1187 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1188 if (strstr($data["pubkey"], 'RSA ')) {
1189 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1194 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1195 foreach ($webfinger["aliases"] as $alias) {
1196 if (empty($data["url"]) && !strstr($alias, "@")) {
1197 $data["url"] = $alias;
1198 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1199 $data["alias"] = $alias;
1200 } elseif (substr($alias, 0, 5) == 'acct:') {
1201 $data["addr"] = substr($alias, 5);
1206 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1207 $data["addr"] = substr($webfinger["subject"], 5);
1210 if (!isset($data["network"]) || ($hcard_url == "")) {
1214 // Fetch data via noscrape - this is faster
1215 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1216 $data = self::pollNoscrape($noscrape_url, $data);
1218 if (isset($data["notify"])
1219 && isset($data["confirm"])
1220 && isset($data["request"])
1221 && isset($data["poll"])
1222 && isset($data["name"])
1223 && isset($data["photo"])
1228 $data = self::pollHcard($hcard_url, $data, true);
1234 * Poll the hcard page (Diaspora and Friendica specific)
1236 * @param string $hcard_url Link to the hcard page
1237 * @param array $data The already fetched data
1238 * @param boolean $dfrn Poll DFRN specific data
1240 * @return array hcard data
1241 * @throws HTTPException\InternalServerErrorException
1243 private static function pollHcard($hcard_url, $data, $dfrn = false)
1245 $curlResult = Network::curl($hcard_url);
1246 if ($curlResult->isTimeout()) {
1247 self::$istimeout = true;
1250 $content = $curlResult->getBody();
1255 $doc = new DOMDocument();
1256 if (!@$doc->loadHTML($content)) {
1260 $xpath = new DomXPath($doc);
1262 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1263 if (!is_object($vcards)) {
1267 if (!isset($data["baseurl"])) {
1268 $data["baseurl"] = "";
1271 if ($vcards->length > 0) {
1272 $vcard = $vcards->item(0);
1274 // We have to discard the guid from the hcard in favour of the guid from lrdd
1275 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1276 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1277 if (($search->length > 0) && empty($data["guid"])) {
1278 $data["guid"] = $search->item(0)->nodeValue;
1281 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1282 if ($search->length > 0) {
1283 $data["nick"] = $search->item(0)->nodeValue;
1286 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1287 if ($search->length > 0) {
1288 $data["name"] = $search->item(0)->nodeValue;
1291 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1292 if ($search->length > 0) {
1293 $data["searchable"] = $search->item(0)->nodeValue;
1296 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1297 if ($search->length > 0) {
1298 $data["pubkey"] = $search->item(0)->nodeValue;
1299 if (strstr($data["pubkey"], 'RSA ')) {
1300 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1304 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1305 if ($search->length > 0) {
1306 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1311 if (!empty($vcard)) {
1312 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1313 foreach ($photos as $photo) {
1315 foreach ($photo->attributes as $attribute) {
1316 $attr[$attribute->name] = trim($attribute->value);
1319 if (isset($attr["src"]) && isset($attr["width"])) {
1320 $avatar[$attr["width"]] = $attr["src"];
1323 // We don't have a width. So we just take everything that we got.
1324 // This is a Hubzilla workaround which doesn't send a width.
1325 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1326 $avatar[] = $attr["src"];
1331 if (sizeof($avatar)) {
1333 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1337 // Poll DFRN specific data
1338 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1339 if ($search->length > 0) {
1340 foreach ($search as $link) {
1341 //$data["request"] = $search->item(0)->nodeValue;
1343 foreach ($link->attributes as $attribute) {
1344 $attr[$attribute->name] = trim($attribute->value);
1347 $data[substr($attr["rel"], 5)] = $attr["href"];
1351 // Older Friendica versions had used the "uid" field differently than newer versions
1352 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1353 unset($data["guid"]);
1362 * Check for Diaspora contact
1364 * @param array $webfinger Webfinger data
1366 * @return array Diaspora data
1367 * @throws HTTPException\InternalServerErrorException
1369 private static function diaspora($webfinger)
1374 // The array is reversed to take into account the order of preference for same-rel links
1375 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1376 foreach (array_reverse($webfinger["links"]) as $link) {
1377 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1378 $hcard_url = $link["href"];
1379 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1380 $data["baseurl"] = trim($link["href"], '/');
1381 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1382 $data["guid"] = $link["href"];
1383 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1384 $data["url"] = $link["href"];
1385 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1386 $data["poll"] = $link["href"];
1387 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1388 $data["poco"] = $link["href"];
1389 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1390 $data["notify"] = $link["href"];
1391 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1392 $data["pubkey"] = base64_decode($link["href"]);
1394 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1395 if (strstr($data["pubkey"], 'RSA ')) {
1396 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1401 if (empty($data["url"]) || empty($hcard_url)) {
1405 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1406 foreach ($webfinger["aliases"] as $alias) {
1407 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1408 $data["alias"] = $alias;
1409 } elseif (substr($alias, 0, 5) == 'acct:') {
1410 $data["addr"] = substr($alias, 5);
1415 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1416 $data["addr"] = substr($webfinger["subject"], 5);
1419 // Fetch further information from the hcard
1420 $data = self::pollHcard($hcard_url, $data);
1426 if (!empty($data["url"])
1427 && !empty($data["guid"])
1428 && !empty($data["baseurl"])
1429 && !empty($data["pubkey"])
1430 && !empty($hcard_url)
1432 $data["network"] = Protocol::DIASPORA;
1434 // The Diaspora handle must always be lowercase
1435 if (!empty($data["addr"])) {
1436 $data["addr"] = strtolower($data["addr"]);
1439 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1440 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1441 $data["batch"] = $data["baseurl"] . "/receive/public";
1450 * Check for OStatus contact
1452 * @param array $webfinger Webfinger data
1453 * @param bool $short Short detection mode
1455 * @return array|bool OStatus data or "false" on error or "true" on short mode
1456 * @throws HTTPException\InternalServerErrorException
1458 private static function ostatus($webfinger, $short = false)
1462 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1463 foreach ($webfinger["aliases"] as $alias) {
1464 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1465 $data["addr"] = str_replace('acct:', '', $alias);
1470 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1471 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1473 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1476 if (is_array($webfinger["links"])) {
1477 // The array is reversed to take into account the order of preference for same-rel links
1478 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1479 foreach (array_reverse($webfinger["links"]) as $link) {
1480 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1481 && (($link["type"] ?? "") == "text/html")
1482 && ($link["href"] != "")
1484 $data["url"] = $link["href"];
1485 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1486 $data["notify"] = $link["href"];
1487 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1488 $data["poll"] = $link["href"];
1489 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1490 $pubkey = $link["href"];
1492 if (substr($pubkey, 0, 5) === 'data:') {
1493 if (strstr($pubkey, ',')) {
1494 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1496 $pubkey = substr($pubkey, 5);
1498 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1499 $curlResult = Network::curl($pubkey);
1500 if ($curlResult->isTimeout()) {
1501 self::$istimeout = true;
1504 $pubkey = $curlResult->getBody();
1507 $key = explode(".", $pubkey);
1509 if (sizeof($key) >= 3) {
1510 $m = Strings::base64UrlDecode($key[1]);
1511 $e = Strings::base64UrlDecode($key[2]);
1512 $data["pubkey"] = Crypto::meToPem($m, $e);
1518 if (isset($data["notify"]) && isset($data["pubkey"])
1519 && isset($data["poll"])
1520 && isset($data["url"])
1522 $data["network"] = Protocol::OSTATUS;
1531 // Fetch all additional data from the feed
1532 $curlResult = Network::curl($data["poll"]);
1533 if ($curlResult->isTimeout()) {
1534 self::$istimeout = true;
1537 $feed = $curlResult->getBody();
1538 $feed_data = Feed::import($feed);
1543 if (!empty($feed_data["header"]["author-name"])) {
1544 $data["name"] = $feed_data["header"]["author-name"];
1546 if (!empty($feed_data["header"]["author-nick"])) {
1547 $data["nick"] = $feed_data["header"]["author-nick"];
1549 if (!empty($feed_data["header"]["author-avatar"])) {
1550 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1552 if (!empty($feed_data["header"]["author-id"])) {
1553 $data["alias"] = $feed_data["header"]["author-id"];
1555 if (!empty($feed_data["header"]["author-location"])) {
1556 $data["location"] = $feed_data["header"]["author-location"];
1558 if (!empty($feed_data["header"]["author-about"])) {
1559 $data["about"] = $feed_data["header"]["author-about"];
1561 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1562 // So we take the value that we just fetched, although the other one worked as well
1563 if (!empty($feed_data["header"]["author-link"])) {
1564 $data["url"] = $feed_data["header"]["author-link"];
1567 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1568 $data['url'] = $data["alias"];
1569 $data["alias"] = '';
1572 /// @todo Fetch location and "about" from the feed as well
1577 * Fetch data from a pump.io profile page
1579 * @param string $profile_link Link to the profile page
1581 * @return array profile data
1583 private static function pumpioProfileData($profile_link)
1585 $curlResult = Network::curl($profile_link);
1586 if (!$curlResult->isSuccess()) {
1590 $doc = new DOMDocument();
1591 if (!@$doc->loadHTML($curlResult->getBody())) {
1595 $xpath = new DomXPath($doc);
1599 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1601 if ($data["name"] == '') {
1602 // This is ugly - but pump.io doesn't seem to know a better way for it
1603 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1604 $pos = strpos($data["name"], chr(10));
1606 $data["name"] = trim(substr($data["name"], 0, $pos));
1610 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1612 if ($data["location"] == '') {
1613 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1616 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1618 if ($data["about"] == '') {
1619 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1622 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1624 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1627 foreach ($avatar->attributes as $attribute) {
1628 if ($attribute->name == "src") {
1629 $data["photo"] = trim($attribute->value);
1638 * Check for pump.io contact
1640 * @param array $webfinger Webfinger data
1641 * @param string $addr
1642 * @return array pump.io data
1644 private static function pumpio($webfinger, $addr)
1647 // The array is reversed to take into account the order of preference for same-rel links
1648 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1649 foreach (array_reverse($webfinger["links"]) as $link) {
1650 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1651 && (($link["type"] ?? "") == "text/html")
1652 && ($link["href"] != "")
1654 $data["url"] = $link["href"];
1655 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1656 $data["notify"] = $link["href"];
1657 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1658 $data["poll"] = $link["href"];
1659 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1660 $data["dialback"] = $link["href"];
1663 if (isset($data["poll"]) && isset($data["notify"])
1664 && isset($data["dialback"])
1665 && isset($data["url"])
1667 // by now we use these fields only for the network type detection
1668 // So we unset all data that isn't used at the moment
1669 unset($data["dialback"]);
1671 $data["network"] = Protocol::PUMPIO;
1676 $profile_data = self::pumpioProfileData($data["url"]);
1678 if (!$profile_data) {
1682 $data = array_merge($data, $profile_data);
1684 if (($addr != '') && ($data['name'] != '')) {
1685 $name = trim(str_replace($addr, '', $data['name']));
1687 $data['name'] = $name;
1695 * Check for twitter contact
1697 * @param string $uri
1699 * @return array twitter data
1701 private static function twitter($uri)
1703 if (preg_match('=(.*)@twitter.com=i', $uri, $matches)) {
1704 $nick = $matches[1];
1705 } elseif (preg_match('=https?://twitter.com/(.*)=i', $uri, $matches)) {
1706 $nick = $matches[1];
1712 $data['url'] = 'https://twitter.com/' . $nick;
1713 $data['addr'] = $nick . '@twitter.com';
1714 $data['nick'] = $data['name'] = $nick;
1715 $data['network'] = Protocol::TWITTER;
1716 $data['baseurl'] = 'https://twitter.com';
1718 $curlResult = Network::curl($data['url'], false);
1719 if (!$curlResult->isSuccess()) {
1723 $body = $curlResult->getBody();
1724 $doc = new DOMDocument();
1725 @$doc->loadHTML($body);
1726 $xpath = new DOMXPath($doc);
1728 $list = $xpath->query('//img[@class]');
1729 foreach ($list as $node) {
1731 if ($node->attributes->length) {
1732 foreach ($node->attributes as $attribute) {
1733 $img_attr[$attribute->name] = $attribute->value;
1737 if (empty($img_attr['class'])) {
1741 if (strpos($img_attr['class'], 'ProfileAvatar-image') !== false) {
1742 if (!empty($img_attr['src'])) {
1743 $data['photo'] = $img_attr['src'];
1745 if (!empty($img_attr['alt'])) {
1746 $data['name'] = $img_attr['alt'];
1755 * Check page for feed link
1757 * @param string $url Page link
1759 * @return string feed link
1761 private static function getFeedLink($url)
1763 $curlResult = Network::curl($url);
1764 if (!$curlResult->isSuccess()) {
1768 $doc = new DOMDocument();
1769 if (!@$doc->loadHTML($curlResult->getBody())) {
1773 $xpath = new DomXPath($doc);
1775 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1776 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1777 if (!is_object($feeds)) {
1781 if ($feeds->length == 0) {
1787 foreach ($feeds as $feed) {
1789 foreach ($feed->attributes as $attribute) {
1790 $attr[$attribute->name] = trim($attribute->value);
1793 if (empty($feed_url) && !empty($attr['href'])) {
1794 $feed_url = $attr["href"];
1802 * Check for feed contact
1804 * @param string $url Profile link
1805 * @param boolean $probe Do a probe if the page contains a feed link
1807 * @return array feed data
1808 * @throws HTTPException\InternalServerErrorException
1810 private static function feed($url, $probe = true)
1812 $curlResult = Network::curl($url);
1813 if ($curlResult->isTimeout()) {
1814 self::$istimeout = true;
1817 $feed = $curlResult->getBody();
1818 $feed_data = Feed::import($feed);
1825 $feed_url = self::getFeedLink($url);
1831 return self::feed($feed_url, false);
1834 if (!empty($feed_data["header"]["author-name"])) {
1835 $data["name"] = $feed_data["header"]["author-name"];
1838 if (!empty($feed_data["header"]["author-nick"])) {
1839 $data["nick"] = $feed_data["header"]["author-nick"];
1842 if (!empty($feed_data["header"]["author-avatar"])) {
1843 $data["photo"] = $feed_data["header"]["author-avatar"];
1846 if (!empty($feed_data["header"]["author-id"])) {
1847 $data["alias"] = $feed_data["header"]["author-id"];
1850 $data["url"] = $url;
1851 $data["poll"] = $url;
1853 if (!empty($feed_data["header"]["author-link"])) {
1854 $data["baseurl"] = $feed_data["header"]["author-link"];
1856 $data["baseurl"] = $data["url"];
1859 $data["network"] = Protocol::FEED;
1865 * Check for mail contact
1867 * @param string $uri Profile link
1868 * @param integer $uid User ID
1870 * @return array mail data
1871 * @throws \Exception
1873 private static function mail($uri, $uid)
1875 if (!Network::isEmailDomainValid($uri)) {
1883 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1885 $condition = ["`uid` = ? AND `server` != ''", $uid];
1886 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1887 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1889 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1893 $mailbox = Email::constructMailboxName($mailacct);
1895 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1896 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1901 $msgs = Email::poll($mbox, $uri);
1902 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1904 if (!count($msgs)) {
1908 $phost = substr($uri, strpos($uri, '@') + 1);
1911 $data["addr"] = $uri;
1912 $data["network"] = Protocol::MAIL;
1913 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1914 $data["nick"] = $data["name"];
1915 $data["photo"] = Network::lookupAvatarByEmail($uri);
1916 $data["url"] = 'mailto:'.$uri;
1917 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1918 $data["poll"] = 'email ' . Strings::getRandomHex();
1920 $x = Email::messageMeta($mbox, $msgs[0]);
1921 if (stristr($x[0]->from, $uri)) {
1922 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1923 } elseif (stristr($x[0]->to, $uri)) {
1924 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1927 foreach ($adr as $feadr) {
1928 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1929 &&(strcasecmp($feadr->host, $phost) == 0)
1930 && (strlen($feadr->personal))
1932 $personal = imap_mime_header_decode($feadr->personal);
1934 foreach ($personal as $perspart) {
1935 if ($perspart->charset != "default") {
1936 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1938 $data["name"] .= $perspart->text;
1942 $data["name"] = Strings::escapeTags($data["name"]);
1946 if (!empty($mbox)) {
1953 * Mix two paths together to possibly fix missing parts
1955 * @param string $avatar Path to the avatar
1956 * @param string $base Another path that is hopefully complete
1958 * @return string fixed avatar path
1959 * @throws \Exception
1961 public static function fixAvatar($avatar, $base)
1963 $base_parts = parse_url($base);
1965 // Remove all parts that could create a problem
1966 unset($base_parts['path']);
1967 unset($base_parts['query']);
1968 unset($base_parts['fragment']);
1970 $avatar_parts = parse_url($avatar);
1973 $parts = array_merge($base_parts, $avatar_parts);
1975 // And put them together again
1976 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1977 $host = isset($parts['host']) ? $parts['host'] : '';
1978 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1979 $path = isset($parts['path']) ? $parts['path'] : '';
1980 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1981 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1983 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1985 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);