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 * Remove stuff from an URI that doesn't belong there
54 * @return string Cleaned URI
56 public static function cleanURI(string $URI)
58 // At first remove leading and trailing junk
59 $URI = trim($URI, "@#?:/ \t\n\r\0\x0B");
61 $parts = parse_url($URI);
63 if (empty($parts['scheme'])) {
67 // Remove the URL fragment, since these shouldn't be part of any profile URL
68 unset($parts['fragment']);
70 $URI = Network::unparseURL($parts);
76 * Rearrange the array so that it always has the same order
78 * @param array $data Unordered data
80 * @return array Ordered data
82 private static function rearrangeData($data)
84 $fields = ["name", "nick", "guid", "url", "addr", "alias", "photo", "account-type",
85 "community", "keywords", "location", "about", "hide",
86 "batch", "notify", "poll", "request", "confirm", "poco",
87 "following", "followers", "inbox", "outbox", "sharedinbox",
88 "priority", "network", "pubkey", "baseurl"];
91 foreach ($fields as $field) {
92 if (isset($data[$field])) {
93 $newdata[$field] = $data[$field];
95 $newdata[$field] = "";
99 // We don't use the "priority" field anymore and replace it with a dummy.
100 $newdata["priority"] = 0;
106 * Check if the hostname belongs to the own server
108 * @param string $host The hostname that is to be checked
110 * @return bool Does the testes hostname belongs to the own server?
112 private static function ownHost($host)
114 $own_host = DI::baseUrl()->getHostname();
116 $parts = parse_url($host);
118 if (!isset($parts['scheme'])) {
119 $parts = parse_url('http://'.$host);
122 if (!isset($parts['host'])) {
125 return $parts['host'] == $own_host;
129 * Probes for webfinger path via "host-meta"
131 * We have to check if the servers in the future still will offer this.
132 * It seems as if it was dropped from the standard.
134 * @param string $host The host part of an url
136 * @return array with template and type of the webfinger template for JSON or XML
137 * @throws HTTPException\InternalServerErrorException
139 private static function hostMeta($host)
141 // Reset the static variable
144 $ssl_url = "https://".$host."/.well-known/host-meta";
145 $url = "http://".$host."/.well-known/host-meta";
147 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
149 Logger::log("Probing for ".$host, Logger::DEBUG);
152 $curlResult = Network::curl($ssl_url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
153 $ssl_connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
154 if ($curlResult->isSuccess()) {
155 $xml = $curlResult->getBody();
156 $xrd = XML::parseString($xml, false);
157 $host_url = 'https://'.$host;
158 } elseif ($curlResult->isTimeout()) {
159 Logger::info('Probing timeout', ['url' => $ssl_url], Logger::DEBUG);
160 self::$istimeout = true;
164 if (!is_object($xrd)) {
165 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
166 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
167 if ($curlResult->isTimeout()) {
168 Logger::info('Probing timeout', ['url' => $url], Logger::DEBUG);
169 self::$istimeout = true;
171 } elseif ($connection_error && $ssl_connection_error) {
172 self::$istimeout = true;
176 $xml = $curlResult->getBody();
177 $xrd = XML::parseString($xml, false);
178 $host_url = 'http://'.$host;
180 if (!is_object($xrd)) {
181 Logger::log("No xrd object found for ".$host, Logger::DEBUG);
185 $links = XML::elementToArray($xrd);
186 if (!isset($links["xrd"]["link"])) {
187 Logger::log("No xrd data found for ".$host, Logger::DEBUG);
191 $lrdd = ['application/jrd+json' => $host_url . '/.well-known/webfinger?resource={uri}'];
193 foreach ($links["xrd"]["link"] as $value => $link) {
194 if (!empty($link["@attributes"])) {
195 $attributes = $link["@attributes"];
196 } elseif ($value == "@attributes") {
202 if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
203 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
205 $lrdd[$type] = $attributes["template"];
209 self::$baseurl = $host_url;
211 Logger::log("Probing successful for ".$host, Logger::DEBUG);
217 * Perform Webfinger lookup and return DFRN data
219 * Given an email style address, perform webfinger lookup and
220 * return the resulting DFRN profile URL, or if no DFRN profile URL
221 * is located, returns an OStatus subscription template (prefixed
222 * with the string 'stat:' to identify it as on OStatus template).
223 * If this isn't an email style address just return $webbie.
224 * Return an empty string if email-style addresses but webfinger fails,
225 * or if the resultant personal XRD doesn't contain a supported
226 * subscription/friend-request attribute.
228 * amended 7/9/2011 to return an hcard which could save potentially loading
229 * a lengthy content page to scrape dfrn attributes
231 * @param string $webbie Address that should be probed
232 * @param string $hcard_url Link to the hcard - is returned by reference
234 * @return string profile link
235 * @throws HTTPException\InternalServerErrorException
237 public static function webfingerDfrn($webbie, &$hcard_url)
241 $links = self::lrdd($webbie);
242 Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA);
243 if (!empty($links) && is_array($links)) {
244 foreach ($links as $link) {
245 if ($link['@attributes']['rel'] === ActivityNamespace::DFRN) {
246 $profile_link = $link['@attributes']['href'];
248 if (($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) && ($profile_link == "")) {
249 $profile_link = 'stat:'.$link['@attributes']['template'];
251 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
252 $hcard_url = $link['@attributes']['href'];
256 return $profile_link;
260 * Get the link for the remote follow page for a given profile link
262 * @param sting $profile
263 * @return string Remote follow page link
265 public static function getRemoteFollowLink(string $profile)
269 $links = self::lrdd($profile);
271 if (!empty($links) && is_array($links)) {
272 foreach ($links as $link) {
273 if ($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) {
274 $follow_link = $link['@attributes']['template'];
282 * Check an URI for LRDD data
284 * this is a replacement for the "lrdd" function.
285 * It isn't used in this class and has some redundancies in the code.
286 * When time comes we can check the existing calls for "lrdd" if we can rework them.
288 * @param string $uri Address that should be probed
290 * @return array uri data
291 * @throws HTTPException\InternalServerErrorException
293 public static function lrdd($uri)
295 $lrdd = self::hostMeta($uri);
298 if (is_bool($lrdd)) {
303 $parts = @parse_url($uri);
304 if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
308 $host = $parts["host"];
309 if (!empty($parts["port"])) {
310 $host .= ':'.$parts["port"];
313 $path_parts = explode("/", trim($parts["path"], "/"));
315 $nick = array_pop($path_parts);
318 $lrdd = self::hostMeta($host);
319 $host .= "/".array_shift($path_parts);
320 } while (!$lrdd && (sizeof($path_parts) > 0));
324 Logger::log("No lrdd data found for ".$uri, Logger::DEBUG);
328 foreach ($lrdd as $type => $template) {
333 $path = str_replace('{uri}', urlencode($uri), $template);
334 $webfinger = self::webfinger($path, $type);
336 if (!$webfinger && (strstr($uri, "@"))) {
337 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
338 $webfinger = self::webfinger($path, $type);
341 // Special treatment for Mastodon
342 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
343 // But the webfinger for this format fails.
344 if (!$webfinger && !empty($nick)) {
345 // Mastodon uses a "@" as prefix for usernames in their url format
346 $nick = ltrim($nick, '@');
348 $addr = $nick."@".$host;
350 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
351 $webfinger = self::webfinger($path, $type);
355 if (!is_array($webfinger["links"])) {
356 Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
362 foreach ($webfinger["links"] as $link) {
363 $data[] = ["@attributes" => $link];
366 if (is_array($webfinger["aliases"])) {
367 foreach ($webfinger["aliases"] as $alias) {
368 $data[] = ["@attributes" =>
378 * Fetch information (protocol endpoints and user information) about a given uri
380 * @param string $uri Address that should be probed
381 * @param string $network Test for this specific network
382 * @param integer $uid User ID for the probe (only used for mails)
383 * @param boolean $cache Use cached values?
385 * @return array uri data
386 * @throws HTTPException\InternalServerErrorException
387 * @throws \ImagickException
389 public static function uri($uri, $network = '', $uid = -1, $cache = true)
392 $result = DI::cache()->get('Probe::uri:' . $network . ':' . $uri);
393 if (!is_null($result)) {
402 self::$istimeout = false;
404 if ($network != Protocol::ACTIVITYPUB) {
405 $data = self::detect($uri, $network, $uid);
410 // When the previous detection process had got a time out
411 // we could falsely detect a Friendica profile as AP profile.
412 if (!self::$istimeout) {
413 $ap_profile = ActivityPub::probeProfile($uri);
415 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
417 } elseif (!empty($ap_profile)) {
418 $ap_profile['batch'] = '';
419 $data = array_merge($ap_profile, $data);
422 Logger::notice('Time out detected. AP will not be probed.', ['uri' => $uri]);
425 if (!isset($data['url'])) {
429 if (!empty($data['photo']) && !empty($data['baseurl'])) {
430 $data['baseurl'] = Network::getUrlMatch(Strings::normaliseLink($data['baseurl']), Strings::normaliseLink($data['photo']));
431 } elseif (empty($data['photo'])) {
432 $data['photo'] = DI::baseUrl() . '/images/person-300.jpg';
435 if (empty($data['name'])) {
436 if (!empty($data['nick'])) {
437 $data['name'] = $data['nick'];
440 if (empty($data['name'])) {
441 $data['name'] = $data['url'];
445 if (empty($data['nick'])) {
446 $data['nick'] = strtolower($data['name']);
448 if (strpos($data['nick'], ' ')) {
449 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
453 if (!empty(self::$baseurl)) {
454 $data['baseurl'] = self::$baseurl;
457 if (empty($data['network'])) {
458 $data['network'] = Protocol::PHANTOM;
461 // Ensure that local connections always are DFRN
462 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
463 $data['network'] = Protocol::DFRN;
466 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
467 $data['hide'] = self::getHideStatus($data['url']);
470 $data = self::rearrangeData($data);
472 // Only store into the cache if the value seems to be valid
473 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
474 DI::cache()->set('Probe::uri:' . $network . ':' . $uri, $data, Duration::DAY);
482 * Fetches the "hide" status from the profile
484 * @param string $url URL of the profile
486 * @return boolean "hide" status
488 private static function getHideStatus($url)
490 $curlResult = Network::curl($url);
491 if (!$curlResult->isSuccess()) {
495 // If the file is too large then exit
496 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
500 // If it isn't a HTML file then exit
501 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
505 $body = $curlResult->getBody();
507 $doc = new DOMDocument();
508 @$doc->loadHTML($body);
510 $xpath = new DOMXPath($doc);
512 $list = $xpath->query('//meta[@name]');
513 foreach ($list as $node) {
515 if ($node->attributes->length) {
516 foreach ($node->attributes as $attribute) {
517 $meta_tag[$attribute->name] = $attribute->value;
521 if (empty($meta_tag['content'])) {
525 $content = strtolower(trim($meta_tag['content']));
527 switch (strtolower(trim($meta_tag['name']))) {
528 case 'dfrn-global-visibility':
529 if ($content == 'false') {
534 if (strpos($content, 'noindex') !== false) {
545 * Checks if a profile url should be OStatus but only provides partial information
547 * @param array $webfinger Webfinger data
548 * @param string $lrdd Path template for webfinger request
549 * @param string $type type
551 * @return array fixed webfinger data
552 * @throws HTTPException\InternalServerErrorException
554 private static function fixOStatus($webfinger, $lrdd, $type)
556 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
563 foreach ($webfinger['links'] as $link) {
564 if ($link['rel'] == ActivityNamespace::OSTATUSSUB) {
567 if ($link['rel'] == 'magic-public-key') {
572 if (!$is_ostatus || $has_key) {
576 $url = Network::switchScheme($webfinger['subject']);
577 $path = str_replace('{uri}', urlencode($url), $lrdd);
578 $webfinger2 = self::webfinger($path, $type);
580 // Is the new webfinger detectable as OStatus?
581 if (self::ostatus($webfinger2, true)) {
582 $webfinger = $webfinger2;
589 * Fetch information (protocol endpoints and user information) about a given uri
591 * This function is only called by the "uri" function that adds caching and rearranging of data.
593 * @param string $uri Address that should be probed
594 * @param string $network Test for this specific network
595 * @param integer $uid User ID for the probe (only used for mails)
597 * @return array uri data
598 * @throws HTTPException\InternalServerErrorException
600 private static function detect($uri, $network, $uid)
602 $parts = parse_url($uri);
604 if (!empty($parts["scheme"]) && !empty($parts["host"])) {
605 $host = $parts["host"];
606 if (!empty($parts["port"])) {
607 $host .= ':'.$parts["port"];
610 if ($host == 'twitter.com') {
611 return self::twitter($uri);
613 $lrdd = self::hostMeta($host);
615 if (is_bool($lrdd)) {
619 $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
621 while (!$lrdd && (sizeof($path_parts) > 1)) {
622 $host .= "/".array_shift($path_parts);
623 $lrdd = self::hostMeta($host);
626 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
627 return self::feed($uri);
629 $nick = array_pop($path_parts);
631 // Mastodon uses a "@" as prefix for usernames in their url format
632 $nick = ltrim($nick, '@');
634 $addr = $nick."@".$host;
635 } elseif (strstr($uri, '@')) {
636 // If the URI starts with "mailto:" then jump directly to the mail detection
637 if (strpos($uri, 'mailto:') !== false) {
638 $uri = str_replace('mailto:', '', $uri);
639 return self::mail($uri, $uid);
642 if ($network == Protocol::MAIL) {
643 return self::mail($uri, $uid);
645 // Remove "acct:" from the URI
646 $uri = str_replace('acct:', '', $uri);
648 $host = substr($uri, strpos($uri, '@') + 1);
649 $nick = substr($uri, 0, strpos($uri, '@'));
651 if (strpos($uri, '@twitter.com')) {
652 return self::twitter($uri);
654 $lrdd = self::hostMeta($host);
656 if (is_bool($lrdd)) {
661 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
662 return self::mail($uri, $uid);
666 Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
672 /// @todo Do we need the prefix "acct:" or "acct://"?
674 foreach ($lrdd as $type => $template) {
679 // At first try it with the given uri
680 $path = str_replace('{uri}', urlencode($uri), $template);
681 $webfinger = self::webfinger($path, $type);
683 // Fix possible problems with GNU Social probing to wrong scheme
684 $webfinger = self::fixOStatus($webfinger, $template, $type);
686 // We cannot be sure that the detected address was correct, so we don't use the values
687 if ($webfinger && ($uri != $addr)) {
692 // Try webfinger with the address (user@domain.tld)
694 $path = str_replace('{uri}', urlencode($addr), $template);
695 $webfinger = self::webfinger($path, $type);
698 // Mastodon needs to have it with "acct:"
700 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
701 $webfinger = self::webfinger($path, $type);
706 return self::feed($uri);
711 Logger::log("Probing ".$uri, Logger::DEBUG);
713 if (in_array($network, ["", Protocol::DFRN])) {
714 $result = self::dfrn($webfinger);
716 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
717 $result = self::diaspora($webfinger);
719 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
720 $result = self::ostatus($webfinger);
722 if (in_array($network, ['', Protocol::ZOT])) {
723 $result = self::zot($webfinger, $result);
725 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
726 $result = self::pumpio($webfinger, $addr);
728 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
729 $result = self::feed($uri);
731 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
732 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
733 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
734 $result["nick"] = $nick;
737 if (empty($result["addr"]) && ($addr != "")) {
738 $result["addr"] = $addr;
742 if (empty($result["network"])) {
743 $result["network"] = Protocol::PHANTOM;
746 if (empty($result["url"])) {
747 $result["url"] = $uri;
750 Logger::log($uri." is ".$result["network"], Logger::DEBUG);
752 if (empty($result["baseurl"]) && ($result["network"] != Protocol::PHANTOM)) {
753 $pos = strpos($result["url"], $host);
755 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
762 * Check for Zot contact
764 * @param array $webfinger Webfinger data
765 * @param array $data previously probed data
767 * @return array Zot data
768 * @throws HTTPException\InternalServerErrorException
770 private static function zot($webfinger, $data)
772 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
773 foreach ($webfinger["aliases"] as $alias) {
774 if (substr($alias, 0, 5) == 'acct:') {
775 $data["addr"] = substr($alias, 5);
780 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
781 $data["addr"] = substr($webfinger["subject"], 5);
785 foreach ($webfinger['links'] as $link) {
786 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
787 $zot_url = $link['href'];
791 if (empty($zot_url) && !empty($data['addr']) && !empty(self::$baseurl)) {
792 $condition = ['nurl' => Strings::normaliseLink(self::$baseurl), 'platform' => ['hubzilla']];
793 if (!DBA::exists('gserver', $condition)) {
796 $zot_url = self::$baseurl . '/.well-known/zot-info?address=' . $data['addr'];
799 if (empty($zot_url)) {
803 $data = self::pollZot($zot_url, $data);
805 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
806 foreach ($webfinger['aliases'] as $alias) {
807 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
808 $data['alias'] = $alias;
816 public static function pollZot($url, $data)
818 $curlResult = Network::curl($url);
819 if ($curlResult->isTimeout()) {
822 $content = $curlResult->getBody();
827 $json = json_decode($content, true);
828 if (!is_array($json)) {
832 if (empty($data['network'])) {
833 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
834 $data['network'] = Protocol::ZOT;
835 } elseif (!isset($json['protocols'])) {
836 $data['network'] = Protocol::ZOT;
840 if (!empty($json['guid']) && empty($data['guid'])) {
841 $data['guid'] = $json['guid'];
843 if (!empty($json['key']) && empty($data['pubkey'])) {
844 $data['pubkey'] = $json['key'];
846 if (!empty($json['name'])) {
847 $data['name'] = $json['name'];
849 if (!empty($json['photo'])) {
850 $data['photo'] = $json['photo'];
851 if (!empty($json['photo_updated'])) {
852 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
855 if (!empty($json['address'])) {
856 $data['addr'] = $json['address'];
858 if (!empty($json['url'])) {
859 $data['url'] = $json['url'];
861 if (!empty($json['connections_url'])) {
862 $data['poco'] = $json['connections_url'];
864 if (isset($json['searchable'])) {
865 $data['hide'] = !$json['searchable'];
867 if (!empty($json['public_forum'])) {
868 $data['community'] = $json['public_forum'];
869 $data['account-type'] = Contact::PAGE_COMMUNITY;
872 if (!empty($json['profile'])) {
873 $profile = $json['profile'];
874 if (!empty($profile['description'])) {
875 $data['about'] = $profile['description'];
877 if (!empty($profile['keywords'])) {
878 $keywords = implode(', ', $profile['keywords']);
879 if (!empty($keywords)) {
880 $data['keywords'] = $keywords;
885 if (!empty($profile['region'])) {
886 $loc['region'] = $profile['region'];
888 if (!empty($profile['country'])) {
889 $loc['country-name'] = $profile['country'];
891 $location = Profile::formatLocation($loc);
892 if (!empty($location)) {
893 $data['location'] = $location;
901 * Perform a webfinger request.
903 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
905 * @param string $url Address that should be probed
906 * @param string $type type
908 * @return array webfinger data
909 * @throws HTTPException\InternalServerErrorException
911 private static function webfinger($url, $type)
913 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
915 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
916 if ($curlResult->isTimeout()) {
917 self::$istimeout = true;
920 $data = $curlResult->getBody();
922 $webfinger = json_decode($data, true);
923 if (is_array($webfinger)) {
924 if (!isset($webfinger["links"])) {
925 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
931 // If it is not JSON, maybe it is XML
932 $xrd = XML::parseString($data, false);
933 if (!is_object($xrd)) {
934 Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
938 $xrd_arr = XML::elementToArray($xrd);
939 if (!isset($xrd_arr["xrd"]["link"])) {
940 Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
946 if (!empty($xrd_arr["xrd"]["subject"])) {
947 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
950 if (!empty($xrd_arr["xrd"]["alias"])) {
951 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
954 $webfinger["links"] = [];
956 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
957 if (!empty($data["@attributes"])) {
958 $attributes = $data["@attributes"];
959 } elseif ($value == "@attributes") {
965 $webfinger["links"][] = $attributes;
971 * Poll the Friendica specific noscrape page.
973 * "noscrape" is a faster alternative to fetch the data from the hcard.
974 * This functionality was originally created for the directory.
976 * @param string $noscrape_url Link to the noscrape page
977 * @param array $data The already fetched data
979 * @return array noscrape data
980 * @throws HTTPException\InternalServerErrorException
982 private static function pollNoscrape($noscrape_url, $data)
984 $curlResult = Network::curl($noscrape_url);
985 if ($curlResult->isTimeout()) {
986 self::$istimeout = true;
989 $content = $curlResult->getBody();
991 Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
995 $json = json_decode($content, true);
996 if (!is_array($json)) {
997 Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
1001 if (!empty($json["fn"])) {
1002 $data["name"] = $json["fn"];
1005 if (!empty($json["addr"])) {
1006 $data["addr"] = $json["addr"];
1009 if (!empty($json["nick"])) {
1010 $data["nick"] = $json["nick"];
1013 if (!empty($json["guid"])) {
1014 $data["guid"] = $json["guid"];
1017 if (!empty($json["comm"])) {
1018 $data["community"] = $json["comm"];
1021 if (!empty($json["tags"])) {
1022 $keywords = implode(", ", $json["tags"]);
1023 if ($keywords != "") {
1024 $data["keywords"] = $keywords;
1028 $location = Profile::formatLocation($json);
1030 $data["location"] = $location;
1033 if (!empty($json["about"])) {
1034 $data["about"] = $json["about"];
1037 if (!empty($json["key"])) {
1038 $data["pubkey"] = $json["key"];
1041 if (!empty($json["photo"])) {
1042 $data["photo"] = $json["photo"];
1045 if (!empty($json["dfrn-request"])) {
1046 $data["request"] = $json["dfrn-request"];
1049 if (!empty($json["dfrn-confirm"])) {
1050 $data["confirm"] = $json["dfrn-confirm"];
1053 if (!empty($json["dfrn-notify"])) {
1054 $data["notify"] = $json["dfrn-notify"];
1057 if (!empty($json["dfrn-poll"])) {
1058 $data["poll"] = $json["dfrn-poll"];
1061 if (isset($json["hide"])) {
1062 $data["hide"] = (bool)$json["hide"];
1064 $data["hide"] = false;
1071 * Check for valid DFRN data
1073 * @param array $data DFRN data
1075 * @return int Number of errors
1077 public static function validDfrn($data)
1080 if (!isset($data['key'])) {
1083 if (!isset($data['dfrn-request'])) {
1086 if (!isset($data['dfrn-confirm'])) {
1089 if (!isset($data['dfrn-notify'])) {
1092 if (!isset($data['dfrn-poll'])) {
1099 * Fetch data from a DFRN profile page and via "noscrape"
1101 * @param string $profile_link Link to the profile page
1103 * @return array profile data
1104 * @throws HTTPException\InternalServerErrorException
1105 * @throws \ImagickException
1107 public static function profile($profile_link)
1111 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
1113 // Fetch data via noscrape - this is faster
1114 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1115 $data = self::pollNoscrape($noscrape_url, $data);
1117 if (!isset($data["notify"])
1118 || !isset($data["confirm"])
1119 || !isset($data["request"])
1120 || !isset($data["poll"])
1121 || !isset($data["name"])
1122 || !isset($data["photo"])
1124 $data = self::pollHcard($profile_link, $data, true);
1129 if (empty($data["addr"]) || empty($data["nick"])) {
1130 $probe_data = self::uri($profile_link);
1131 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1132 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1135 $prof_data["addr"] = $data["addr"];
1136 $prof_data["nick"] = $data["nick"];
1137 $prof_data["dfrn-request"] = $data['request'] ?? null;
1138 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1139 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1140 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1141 $prof_data["photo"] = $data['photo'] ?? null;
1142 $prof_data["fn"] = $data['name'] ?? null;
1143 $prof_data["key"] = $data['pubkey'] ?? null;
1145 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
1151 * Check for DFRN contact
1153 * @param array $webfinger Webfinger data
1155 * @return array DFRN data
1156 * @throws HTTPException\InternalServerErrorException
1158 private static function dfrn($webfinger)
1162 // The array is reversed to take into account the order of preference for same-rel links
1163 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1164 foreach (array_reverse($webfinger["links"]) as $link) {
1165 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1166 $data["network"] = Protocol::DFRN;
1167 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1168 $data["poll"] = $link["href"];
1169 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1170 $data["url"] = $link["href"];
1171 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1172 $hcard_url = $link["href"];
1173 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1174 $data["poco"] = $link["href"];
1175 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1176 $data["photo"] = $link["href"];
1177 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1178 $data["baseurl"] = trim($link["href"], '/');
1179 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1180 $data["guid"] = $link["href"];
1181 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1182 $data["pubkey"] = base64_decode($link["href"]);
1184 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1185 if (strstr($data["pubkey"], 'RSA ')) {
1186 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1191 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1192 foreach ($webfinger["aliases"] as $alias) {
1193 if (empty($data["url"]) && !strstr($alias, "@")) {
1194 $data["url"] = $alias;
1195 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1196 $data["alias"] = $alias;
1197 } elseif (substr($alias, 0, 5) == 'acct:') {
1198 $data["addr"] = substr($alias, 5);
1203 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1204 $data["addr"] = substr($webfinger["subject"], 5);
1207 if (!isset($data["network"]) || ($hcard_url == "")) {
1211 // Fetch data via noscrape - this is faster
1212 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1213 $data = self::pollNoscrape($noscrape_url, $data);
1215 if (isset($data["notify"])
1216 && isset($data["confirm"])
1217 && isset($data["request"])
1218 && isset($data["poll"])
1219 && isset($data["name"])
1220 && isset($data["photo"])
1225 $data = self::pollHcard($hcard_url, $data, true);
1231 * Poll the hcard page (Diaspora and Friendica specific)
1233 * @param string $hcard_url Link to the hcard page
1234 * @param array $data The already fetched data
1235 * @param boolean $dfrn Poll DFRN specific data
1237 * @return array hcard data
1238 * @throws HTTPException\InternalServerErrorException
1240 private static function pollHcard($hcard_url, $data, $dfrn = false)
1242 $curlResult = Network::curl($hcard_url);
1243 if ($curlResult->isTimeout()) {
1244 self::$istimeout = true;
1247 $content = $curlResult->getBody();
1252 $doc = new DOMDocument();
1253 if (!@$doc->loadHTML($content)) {
1257 $xpath = new DomXPath($doc);
1259 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1260 if (!is_object($vcards)) {
1264 if (!isset($data["baseurl"])) {
1265 $data["baseurl"] = "";
1268 if ($vcards->length > 0) {
1269 $vcard = $vcards->item(0);
1271 // We have to discard the guid from the hcard in favour of the guid from lrdd
1272 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1273 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1274 if (($search->length > 0) && empty($data["guid"])) {
1275 $data["guid"] = $search->item(0)->nodeValue;
1278 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1279 if ($search->length > 0) {
1280 $data["nick"] = $search->item(0)->nodeValue;
1283 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1284 if ($search->length > 0) {
1285 $data["name"] = $search->item(0)->nodeValue;
1288 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1289 if ($search->length > 0) {
1290 $data["searchable"] = $search->item(0)->nodeValue;
1293 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1294 if ($search->length > 0) {
1295 $data["pubkey"] = $search->item(0)->nodeValue;
1296 if (strstr($data["pubkey"], 'RSA ')) {
1297 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1301 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1302 if ($search->length > 0) {
1303 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1308 if (!empty($vcard)) {
1309 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1310 foreach ($photos as $photo) {
1312 foreach ($photo->attributes as $attribute) {
1313 $attr[$attribute->name] = trim($attribute->value);
1316 if (isset($attr["src"]) && isset($attr["width"])) {
1317 $avatar[$attr["width"]] = $attr["src"];
1320 // We don't have a width. So we just take everything that we got.
1321 // This is a Hubzilla workaround which doesn't send a width.
1322 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1323 $avatar[] = $attr["src"];
1328 if (sizeof($avatar)) {
1330 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1334 // Poll DFRN specific data
1335 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1336 if ($search->length > 0) {
1337 foreach ($search as $link) {
1338 //$data["request"] = $search->item(0)->nodeValue;
1340 foreach ($link->attributes as $attribute) {
1341 $attr[$attribute->name] = trim($attribute->value);
1344 $data[substr($attr["rel"], 5)] = $attr["href"];
1348 // Older Friendica versions had used the "uid" field differently than newer versions
1349 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1350 unset($data["guid"]);
1359 * Check for Diaspora contact
1361 * @param array $webfinger Webfinger data
1363 * @return array Diaspora data
1364 * @throws HTTPException\InternalServerErrorException
1366 private static function diaspora($webfinger)
1371 // The array is reversed to take into account the order of preference for same-rel links
1372 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1373 foreach (array_reverse($webfinger["links"]) as $link) {
1374 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1375 $hcard_url = $link["href"];
1376 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1377 $data["baseurl"] = trim($link["href"], '/');
1378 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1379 $data["guid"] = $link["href"];
1380 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1381 $data["url"] = $link["href"];
1382 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1383 $data["poll"] = $link["href"];
1384 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1385 $data["poco"] = $link["href"];
1386 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1387 $data["notify"] = $link["href"];
1388 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1389 $data["pubkey"] = base64_decode($link["href"]);
1391 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1392 if (strstr($data["pubkey"], 'RSA ')) {
1393 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1398 if (empty($data["url"]) || empty($hcard_url)) {
1402 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1403 foreach ($webfinger["aliases"] as $alias) {
1404 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1405 $data["alias"] = $alias;
1406 } elseif (substr($alias, 0, 5) == 'acct:') {
1407 $data["addr"] = substr($alias, 5);
1412 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1413 $data["addr"] = substr($webfinger["subject"], 5);
1416 // Fetch further information from the hcard
1417 $data = self::pollHcard($hcard_url, $data);
1423 if (!empty($data["url"])
1424 && !empty($data["guid"])
1425 && !empty($data["baseurl"])
1426 && !empty($data["pubkey"])
1427 && !empty($hcard_url)
1429 $data["network"] = Protocol::DIASPORA;
1431 // The Diaspora handle must always be lowercase
1432 if (!empty($data["addr"])) {
1433 $data["addr"] = strtolower($data["addr"]);
1436 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1437 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1438 $data["batch"] = $data["baseurl"] . "/receive/public";
1447 * Check for OStatus contact
1449 * @param array $webfinger Webfinger data
1450 * @param bool $short Short detection mode
1452 * @return array|bool OStatus data or "false" on error or "true" on short mode
1453 * @throws HTTPException\InternalServerErrorException
1455 private static function ostatus($webfinger, $short = false)
1459 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1460 foreach ($webfinger["aliases"] as $alias) {
1461 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1462 $data["addr"] = str_replace('acct:', '', $alias);
1467 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1468 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1470 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1473 if (is_array($webfinger["links"])) {
1474 // The array is reversed to take into account the order of preference for same-rel links
1475 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1476 foreach (array_reverse($webfinger["links"]) as $link) {
1477 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1478 && (($link["type"] ?? "") == "text/html")
1479 && ($link["href"] != "")
1481 $data["url"] = $link["href"];
1482 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1483 $data["notify"] = $link["href"];
1484 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1485 $data["poll"] = $link["href"];
1486 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1487 $pubkey = $link["href"];
1489 if (substr($pubkey, 0, 5) === 'data:') {
1490 if (strstr($pubkey, ',')) {
1491 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1493 $pubkey = substr($pubkey, 5);
1495 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1496 $curlResult = Network::curl($pubkey);
1497 if ($curlResult->isTimeout()) {
1498 self::$istimeout = true;
1501 $pubkey = $curlResult->getBody();
1504 $key = explode(".", $pubkey);
1506 if (sizeof($key) >= 3) {
1507 $m = Strings::base64UrlDecode($key[1]);
1508 $e = Strings::base64UrlDecode($key[2]);
1509 $data["pubkey"] = Crypto::meToPem($m, $e);
1515 if (isset($data["notify"]) && isset($data["pubkey"])
1516 && isset($data["poll"])
1517 && isset($data["url"])
1519 $data["network"] = Protocol::OSTATUS;
1528 // Fetch all additional data from the feed
1529 $curlResult = Network::curl($data["poll"]);
1530 if ($curlResult->isTimeout()) {
1531 self::$istimeout = true;
1534 $feed = $curlResult->getBody();
1535 $feed_data = Feed::import($feed);
1540 if (!empty($feed_data["header"]["author-name"])) {
1541 $data["name"] = $feed_data["header"]["author-name"];
1543 if (!empty($feed_data["header"]["author-nick"])) {
1544 $data["nick"] = $feed_data["header"]["author-nick"];
1546 if (!empty($feed_data["header"]["author-avatar"])) {
1547 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1549 if (!empty($feed_data["header"]["author-id"])) {
1550 $data["alias"] = $feed_data["header"]["author-id"];
1552 if (!empty($feed_data["header"]["author-location"])) {
1553 $data["location"] = $feed_data["header"]["author-location"];
1555 if (!empty($feed_data["header"]["author-about"])) {
1556 $data["about"] = $feed_data["header"]["author-about"];
1558 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1559 // So we take the value that we just fetched, although the other one worked as well
1560 if (!empty($feed_data["header"]["author-link"])) {
1561 $data["url"] = $feed_data["header"]["author-link"];
1564 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1565 $data['url'] = $data["alias"];
1566 $data["alias"] = '';
1569 /// @todo Fetch location and "about" from the feed as well
1574 * Fetch data from a pump.io profile page
1576 * @param string $profile_link Link to the profile page
1578 * @return array profile data
1580 private static function pumpioProfileData($profile_link)
1582 $curlResult = Network::curl($profile_link);
1583 if (!$curlResult->isSuccess()) {
1587 $doc = new DOMDocument();
1588 if (!@$doc->loadHTML($curlResult->getBody())) {
1592 $xpath = new DomXPath($doc);
1596 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1598 if ($data["name"] == '') {
1599 // This is ugly - but pump.io doesn't seem to know a better way for it
1600 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1601 $pos = strpos($data["name"], chr(10));
1603 $data["name"] = trim(substr($data["name"], 0, $pos));
1607 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1609 if ($data["location"] == '') {
1610 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1613 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1615 if ($data["about"] == '') {
1616 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1619 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1621 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1624 foreach ($avatar->attributes as $attribute) {
1625 if ($attribute->name == "src") {
1626 $data["photo"] = trim($attribute->value);
1635 * Check for pump.io contact
1637 * @param array $webfinger Webfinger data
1638 * @param string $addr
1639 * @return array pump.io data
1641 private static function pumpio($webfinger, $addr)
1644 // The array is reversed to take into account the order of preference for same-rel links
1645 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1646 foreach (array_reverse($webfinger["links"]) as $link) {
1647 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1648 && (($link["type"] ?? "") == "text/html")
1649 && ($link["href"] != "")
1651 $data["url"] = $link["href"];
1652 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1653 $data["notify"] = $link["href"];
1654 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1655 $data["poll"] = $link["href"];
1656 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1657 $data["dialback"] = $link["href"];
1660 if (isset($data["poll"]) && isset($data["notify"])
1661 && isset($data["dialback"])
1662 && isset($data["url"])
1664 // by now we use these fields only for the network type detection
1665 // So we unset all data that isn't used at the moment
1666 unset($data["dialback"]);
1668 $data["network"] = Protocol::PUMPIO;
1673 $profile_data = self::pumpioProfileData($data["url"]);
1675 if (!$profile_data) {
1679 $data = array_merge($data, $profile_data);
1681 if (($addr != '') && ($data['name'] != '')) {
1682 $name = trim(str_replace($addr, '', $data['name']));
1684 $data['name'] = $name;
1692 * Check for twitter contact
1694 * @param string $uri
1696 * @return array twitter data
1698 private static function twitter($uri)
1700 if (preg_match('=(.*)@twitter.com=i', $uri, $matches)) {
1701 $nick = $matches[1];
1702 } elseif (preg_match('=https?://twitter.com/(.*)=i', $uri, $matches)) {
1703 $nick = $matches[1];
1709 $data['url'] = 'https://twitter.com/' . $nick;
1710 $data['addr'] = $nick . '@twitter.com';
1711 $data['nick'] = $data['name'] = $nick;
1712 $data['network'] = Protocol::TWITTER;
1713 $data['baseurl'] = 'https://twitter.com';
1715 $curlResult = Network::curl($data['url'], false);
1716 if (!$curlResult->isSuccess()) {
1720 $body = $curlResult->getBody();
1721 $doc = new DOMDocument();
1722 @$doc->loadHTML($body);
1723 $xpath = new DOMXPath($doc);
1725 $list = $xpath->query('//img[@class]');
1726 foreach ($list as $node) {
1728 if ($node->attributes->length) {
1729 foreach ($node->attributes as $attribute) {
1730 $img_attr[$attribute->name] = $attribute->value;
1734 if (empty($img_attr['class'])) {
1738 if (strpos($img_attr['class'], 'ProfileAvatar-image') !== false) {
1739 if (!empty($img_attr['src'])) {
1740 $data['photo'] = $img_attr['src'];
1742 if (!empty($img_attr['alt'])) {
1743 $data['name'] = $img_attr['alt'];
1752 * Check page for feed link
1754 * @param string $url Page link
1756 * @return string feed link
1758 private static function getFeedLink($url)
1760 $curlResult = Network::curl($url);
1761 if (!$curlResult->isSuccess()) {
1765 $doc = new DOMDocument();
1766 if (!@$doc->loadHTML($curlResult->getBody())) {
1770 $xpath = new DomXPath($doc);
1772 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1773 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1774 if (!is_object($feeds)) {
1778 if ($feeds->length == 0) {
1784 foreach ($feeds as $feed) {
1786 foreach ($feed->attributes as $attribute) {
1787 $attr[$attribute->name] = trim($attribute->value);
1790 if (empty($feed_url) && !empty($attr['href'])) {
1791 $feed_url = $attr["href"];
1799 * Check for feed contact
1801 * @param string $url Profile link
1802 * @param boolean $probe Do a probe if the page contains a feed link
1804 * @return array feed data
1805 * @throws HTTPException\InternalServerErrorException
1807 private static function feed($url, $probe = true)
1809 $curlResult = Network::curl($url);
1810 if ($curlResult->isTimeout()) {
1811 self::$istimeout = true;
1814 $feed = $curlResult->getBody();
1815 $feed_data = Feed::import($feed);
1822 $feed_url = self::getFeedLink($url);
1828 return self::feed($feed_url, false);
1831 if (!empty($feed_data["header"]["author-name"])) {
1832 $data["name"] = $feed_data["header"]["author-name"];
1835 if (!empty($feed_data["header"]["author-nick"])) {
1836 $data["nick"] = $feed_data["header"]["author-nick"];
1839 if (!empty($feed_data["header"]["author-avatar"])) {
1840 $data["photo"] = $feed_data["header"]["author-avatar"];
1843 if (!empty($feed_data["header"]["author-id"])) {
1844 $data["alias"] = $feed_data["header"]["author-id"];
1847 $data["url"] = $url;
1848 $data["poll"] = $url;
1850 if (!empty($feed_data["header"]["author-link"])) {
1851 $data["baseurl"] = $feed_data["header"]["author-link"];
1853 $data["baseurl"] = $data["url"];
1856 $data["network"] = Protocol::FEED;
1862 * Check for mail contact
1864 * @param string $uri Profile link
1865 * @param integer $uid User ID
1867 * @return array mail data
1868 * @throws \Exception
1870 private static function mail($uri, $uid)
1872 if (!Network::isEmailDomainValid($uri)) {
1880 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1882 $condition = ["`uid` = ? AND `server` != ''", $uid];
1883 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1884 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1886 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1890 $mailbox = Email::constructMailboxName($mailacct);
1892 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1893 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1898 $msgs = Email::poll($mbox, $uri);
1899 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1901 if (!count($msgs)) {
1905 $phost = substr($uri, strpos($uri, '@') + 1);
1908 $data["addr"] = $uri;
1909 $data["network"] = Protocol::MAIL;
1910 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1911 $data["nick"] = $data["name"];
1912 $data["photo"] = Network::lookupAvatarByEmail($uri);
1913 $data["url"] = 'mailto:'.$uri;
1914 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1915 $data["poll"] = 'email ' . Strings::getRandomHex();
1917 $x = Email::messageMeta($mbox, $msgs[0]);
1918 if (stristr($x[0]->from, $uri)) {
1919 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1920 } elseif (stristr($x[0]->to, $uri)) {
1921 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1924 foreach ($adr as $feadr) {
1925 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1926 &&(strcasecmp($feadr->host, $phost) == 0)
1927 && (strlen($feadr->personal))
1929 $personal = imap_mime_header_decode($feadr->personal);
1931 foreach ($personal as $perspart) {
1932 if ($perspart->charset != "default") {
1933 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1935 $data["name"] .= $perspart->text;
1939 $data["name"] = Strings::escapeTags($data["name"]);
1943 if (!empty($mbox)) {
1950 * Mix two paths together to possibly fix missing parts
1952 * @param string $avatar Path to the avatar
1953 * @param string $base Another path that is hopefully complete
1955 * @return string fixed avatar path
1956 * @throws \Exception
1958 public static function fixAvatar($avatar, $base)
1960 $base_parts = parse_url($base);
1962 // Remove all parts that could create a problem
1963 unset($base_parts['path']);
1964 unset($base_parts['query']);
1965 unset($base_parts['fragment']);
1967 $avatar_parts = parse_url($avatar);
1970 $parts = array_merge($base_parts, $avatar_parts);
1972 // And put them together again
1973 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1974 $host = isset($parts['host']) ? $parts['host'] : '';
1975 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1976 $path = isset($parts['path']) ? $parts['path'] : '';
1977 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1978 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1980 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1982 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);