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, true);
165 $host_url = 'https://' . $host;
169 } elseif ($curlResult->isTimeout()) {
170 Logger::info('Probing timeout', ['url' => $ssl_url], Logger::DEBUG);
171 self::$istimeout = true;
175 if (!is_object($xrd) && !empty($url)) {
176 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
177 $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
178 if ($curlResult->isTimeout()) {
179 Logger::info('Probing timeout', ['url' => $url], Logger::DEBUG);
180 self::$istimeout = true;
182 } elseif ($connection_error && $ssl_connection_error) {
183 self::$istimeout = true;
187 $xml = $curlResult->getBody();
188 $xrd = XML::parseString($xml, true);
189 $host_url = 'http://'.$host;
191 if (!is_object($xrd)) {
192 Logger::log("No xrd object found for ".$host, Logger::DEBUG);
196 $links = XML::elementToArray($xrd);
197 if (!isset($links["xrd"]["link"])) {
198 Logger::log("No xrd data found for ".$host, Logger::DEBUG);
202 $lrdd = ['application/jrd+json' => $host_url . '/.well-known/webfinger?resource={uri}'];
204 foreach ($links["xrd"]["link"] as $value => $link) {
205 if (!empty($link["@attributes"])) {
206 $attributes = $link["@attributes"];
207 } elseif ($value == "@attributes") {
213 if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
214 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
216 $lrdd[$type] = $attributes["template"];
220 self::$baseurl = $host_url;
222 Logger::log("Probing successful for ".$host, Logger::DEBUG);
228 * Perform Webfinger lookup and return DFRN data
230 * Given an email style address, perform webfinger lookup and
231 * return the resulting DFRN profile URL, or if no DFRN profile URL
232 * is located, returns an OStatus subscription template (prefixed
233 * with the string 'stat:' to identify it as on OStatus template).
234 * If this isn't an email style address just return $webbie.
235 * Return an empty string if email-style addresses but webfinger fails,
236 * or if the resultant personal XRD doesn't contain a supported
237 * subscription/friend-request attribute.
239 * amended 7/9/2011 to return an hcard which could save potentially loading
240 * a lengthy content page to scrape dfrn attributes
242 * @param string $webbie Address that should be probed
243 * @param string $hcard_url Link to the hcard - is returned by reference
245 * @return string profile link
246 * @throws HTTPException\InternalServerErrorException
248 public static function webfingerDfrn($webbie, &$hcard_url)
252 $links = self::lrdd($webbie);
253 Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA);
254 if (!empty($links) && is_array($links)) {
255 foreach ($links as $link) {
256 if ($link['@attributes']['rel'] === ActivityNamespace::DFRN) {
257 $profile_link = $link['@attributes']['href'];
259 if (($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) && ($profile_link == "")) {
260 $profile_link = 'stat:'.$link['@attributes']['template'];
262 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
263 $hcard_url = $link['@attributes']['href'];
267 return $profile_link;
271 * Get the link for the remote follow page for a given profile link
273 * @param sting $profile
274 * @return string Remote follow page link
276 public static function getRemoteFollowLink(string $profile)
280 $links = self::lrdd($profile);
282 if (!empty($links) && is_array($links)) {
283 foreach ($links as $link) {
284 if ($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) {
285 $follow_link = $link['@attributes']['template'];
293 * Check an URI for LRDD data
295 * @param string $uri Address that should be probed
297 * @return array uri data
298 * @throws HTTPException\InternalServerErrorException
300 public static function lrdd($uri)
302 $lrdd = self::hostMeta($uri);
305 if (is_bool($lrdd)) {
310 $parts = @parse_url($uri);
311 if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
315 $host = $parts['scheme'] . '://' . $parts["host"];
316 if (!empty($parts["port"])) {
317 $host .= ':'.$parts["port"];
320 $path_parts = explode("/", trim($parts["path"], "/"));
322 $nick = array_pop($path_parts);
325 $lrdd = self::hostMeta($host);
326 $host .= "/".array_shift($path_parts);
327 } while (!$lrdd && (sizeof($path_parts) > 0));
331 Logger::log("No lrdd data found for ".$uri, Logger::DEBUG);
335 foreach ($lrdd as $type => $template) {
340 $path = str_replace('{uri}', urlencode($uri), $template);
341 $webfinger = self::webfinger($path, $type);
343 if (!$webfinger && (strstr($uri, "@"))) {
344 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
345 $webfinger = self::webfinger($path, $type);
348 // Special treatment for Mastodon
349 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
350 // But the webfinger for this format fails.
351 if (!$webfinger && !empty($nick)) {
352 // Mastodon uses a "@" as prefix for usernames in their url format
353 $nick = ltrim($nick, '@');
355 $addr = $nick."@".$host;
357 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
358 $webfinger = self::webfinger($path, $type);
362 if (!is_array($webfinger["links"])) {
363 Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
369 foreach ($webfinger["links"] as $link) {
370 $data[] = ["@attributes" => $link];
373 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
374 foreach ($webfinger["aliases"] as $alias) {
375 $data[] = ["@attributes" =>
385 * Fetch information (protocol endpoints and user information) about a given uri
387 * @param string $uri Address that should be probed
388 * @param string $network Test for this specific network
389 * @param integer $uid User ID for the probe (only used for mails)
390 * @param boolean $cache Use cached values?
392 * @return array uri data
393 * @throws HTTPException\InternalServerErrorException
394 * @throws \ImagickException
396 public static function uri($uri, $network = '', $uid = -1, $cache = true)
399 $result = DI::cache()->get('Probe::uri:' . $network . ':' . $uri);
400 if (!is_null($result)) {
409 self::$istimeout = false;
411 if ($network != Protocol::ACTIVITYPUB) {
412 $data = self::detect($uri, $network, $uid);
417 // When the previous detection process had got a time out
418 // we could falsely detect a Friendica profile as AP profile.
419 if (!self::$istimeout) {
420 $ap_profile = ActivityPub::probeProfile($uri);
422 if (empty($data) || (!empty($ap_profile) && empty($network) && (($data['network'] ?? '') != Protocol::DFRN))) {
424 } elseif (!empty($ap_profile)) {
425 $ap_profile['batch'] = '';
426 $data = array_merge($ap_profile, $data);
429 Logger::notice('Time out detected. AP will not be probed.', ['uri' => $uri]);
432 if (!isset($data['url'])) {
436 if (!empty($data['photo']) && !empty($data['baseurl'])) {
437 $data['baseurl'] = Network::getUrlMatch(Strings::normaliseLink($data['baseurl']), Strings::normaliseLink($data['photo']));
438 } elseif (empty($data['photo'])) {
439 $data['photo'] = DI::baseUrl() . '/images/person-300.jpg';
442 if (empty($data['name'])) {
443 if (!empty($data['nick'])) {
444 $data['name'] = $data['nick'];
447 if (empty($data['name'])) {
448 $data['name'] = $data['url'];
452 if (empty($data['nick'])) {
453 $data['nick'] = strtolower($data['name']);
455 if (strpos($data['nick'], ' ')) {
456 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
460 if (!empty(self::$baseurl)) {
461 $data['baseurl'] = self::$baseurl;
464 if (empty($data['network'])) {
465 $data['network'] = Protocol::PHANTOM;
468 // Ensure that local connections always are DFRN
469 if (($network == '') && ($data['network'] != Protocol::PHANTOM) && (self::ownHost($data['baseurl'] ?? '') || self::ownHost($data['url']))) {
470 $data['network'] = Protocol::DFRN;
473 if (!isset($data['hide']) && in_array($data['network'], Protocol::FEDERATED)) {
474 $data['hide'] = self::getHideStatus($data['url']);
477 $data = self::rearrangeData($data);
479 // Only store into the cache if the value seems to be valid
480 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
481 DI::cache()->set('Probe::uri:' . $network . ':' . $uri, $data, Duration::DAY);
489 * Fetches the "hide" status from the profile
491 * @param string $url URL of the profile
493 * @return boolean "hide" status
495 private static function getHideStatus($url)
497 $curlResult = Network::curl($url);
498 if (!$curlResult->isSuccess()) {
502 // If the file is too large then exit
503 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
507 // If it isn't a HTML file then exit
508 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
512 $body = $curlResult->getBody();
514 $doc = new DOMDocument();
515 @$doc->loadHTML($body);
517 $xpath = new DOMXPath($doc);
519 $list = $xpath->query('//meta[@name]');
520 foreach ($list as $node) {
522 if ($node->attributes->length) {
523 foreach ($node->attributes as $attribute) {
524 $meta_tag[$attribute->name] = $attribute->value;
528 if (empty($meta_tag['content'])) {
532 $content = strtolower(trim($meta_tag['content']));
534 switch (strtolower(trim($meta_tag['name']))) {
535 case 'dfrn-global-visibility':
536 if ($content == 'false') {
541 if (strpos($content, 'noindex') !== false) {
552 * Checks if a profile url should be OStatus but only provides partial information
554 * @param array $webfinger Webfinger data
555 * @param string $lrdd Path template for webfinger request
556 * @param string $type type
558 * @return array fixed webfinger data
559 * @throws HTTPException\InternalServerErrorException
561 private static function fixOStatus($webfinger, $lrdd, $type)
563 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
570 foreach ($webfinger['links'] as $link) {
571 if ($link['rel'] == ActivityNamespace::OSTATUSSUB) {
574 if ($link['rel'] == 'magic-public-key') {
579 if (!$is_ostatus || $has_key) {
583 $url = Network::switchScheme($webfinger['subject']);
584 $path = str_replace('{uri}', urlencode($url), $lrdd);
585 $webfinger2 = self::webfinger($path, $type);
587 // Is the new webfinger detectable as OStatus?
588 if (self::ostatus($webfinger2, true)) {
589 $webfinger = $webfinger2;
596 * Fetch information (protocol endpoints and user information) about a given uri
598 * This function is only called by the "uri" function that adds caching and rearranging of data.
600 * @param string $uri Address that should be probed
601 * @param string $network Test for this specific network
602 * @param integer $uid User ID for the probe (only used for mails)
604 * @return array uri data
605 * @throws HTTPException\InternalServerErrorException
607 private static function detect($uri, $network, $uid)
609 $parts = parse_url($uri);
611 if (!empty($parts["scheme"]) && !empty($parts["host"])) {
612 $host = $parts["host"];
613 if (!empty($parts["port"])) {
614 $host .= ':'.$parts["port"];
617 if ($host == 'twitter.com') {
618 return self::twitter($uri);
620 $lrdd = self::hostMeta($host);
622 if (is_bool($lrdd)) {
626 $path_parts = explode("/", trim($parts['path'] ?? '', "/"));
628 while (!$lrdd && (sizeof($path_parts) > 1)) {
629 $host .= "/".array_shift($path_parts);
630 $lrdd = self::hostMeta($host);
633 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
634 return self::feed($uri);
636 $nick = array_pop($path_parts);
638 // Mastodon uses a "@" as prefix for usernames in their url format
639 $nick = ltrim($nick, '@');
641 $addr = $nick."@".$host;
642 } elseif (strstr($uri, '@')) {
643 // If the URI starts with "mailto:" then jump directly to the mail detection
644 if (strpos($uri, 'mailto:') !== false) {
645 $uri = str_replace('mailto:', '', $uri);
646 return self::mail($uri, $uid);
649 if ($network == Protocol::MAIL) {
650 return self::mail($uri, $uid);
652 // Remove "acct:" from the URI
653 $uri = str_replace('acct:', '', $uri);
655 $host = substr($uri, strpos($uri, '@') + 1);
656 $nick = substr($uri, 0, strpos($uri, '@'));
658 if (strpos($uri, '@twitter.com')) {
659 return self::twitter($uri);
661 $lrdd = self::hostMeta($host);
663 if (is_bool($lrdd)) {
668 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
669 return self::mail($uri, $uid);
673 Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
679 /// @todo Do we need the prefix "acct:" or "acct://"?
681 foreach ($lrdd as $type => $template) {
686 // At first try it with the given uri
687 $path = str_replace('{uri}', urlencode($uri), $template);
688 $webfinger = self::webfinger($path, $type);
690 // Fix possible problems with GNU Social probing to wrong scheme
691 $webfinger = self::fixOStatus($webfinger, $template, $type);
693 // We cannot be sure that the detected address was correct, so we don't use the values
694 if ($webfinger && ($uri != $addr)) {
699 // Try webfinger with the address (user@domain.tld)
701 $path = str_replace('{uri}', urlencode($addr), $template);
702 $webfinger = self::webfinger($path, $type);
705 // Mastodon needs to have it with "acct:"
707 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
708 $webfinger = self::webfinger($path, $type);
713 return self::feed($uri);
718 Logger::log("Probing ".$uri, Logger::DEBUG);
720 if (in_array($network, ["", Protocol::DFRN])) {
721 $result = self::dfrn($webfinger);
723 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
724 $result = self::diaspora($webfinger);
726 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
727 $result = self::ostatus($webfinger);
729 if (in_array($network, ['', Protocol::ZOT])) {
730 $result = self::zot($webfinger, $result);
732 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
733 $result = self::pumpio($webfinger, $addr);
735 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
736 $result = self::feed($uri);
738 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
739 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
740 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
741 $result["nick"] = $nick;
744 if (empty($result["addr"]) && ($addr != "")) {
745 $result["addr"] = $addr;
749 if (empty($result["network"])) {
750 $result["network"] = Protocol::PHANTOM;
753 if (empty($result["url"])) {
754 $result["url"] = $uri;
757 Logger::log($uri." is ".$result["network"], Logger::DEBUG);
759 if (empty($result["baseurl"]) && ($result["network"] != Protocol::PHANTOM)) {
760 $pos = strpos($result["url"], $host);
762 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
769 * Check for Zot contact
771 * @param array $webfinger Webfinger data
772 * @param array $data previously probed data
774 * @return array Zot data
775 * @throws HTTPException\InternalServerErrorException
777 private static function zot($webfinger, $data)
779 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
780 foreach ($webfinger["aliases"] as $alias) {
781 if (substr($alias, 0, 5) == 'acct:') {
782 $data["addr"] = substr($alias, 5);
787 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
788 $data["addr"] = substr($webfinger["subject"], 5);
792 foreach ($webfinger['links'] as $link) {
793 if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
794 $zot_url = $link['href'];
798 if (empty($zot_url) && !empty($data['addr']) && !empty(self::$baseurl)) {
799 $condition = ['nurl' => Strings::normaliseLink(self::$baseurl), 'platform' => ['hubzilla']];
800 if (!DBA::exists('gserver', $condition)) {
803 $zot_url = self::$baseurl . '/.well-known/zot-info?address=' . $data['addr'];
806 if (empty($zot_url)) {
810 $data = self::pollZot($zot_url, $data);
812 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
813 foreach ($webfinger['aliases'] as $alias) {
814 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
815 $data['alias'] = $alias;
823 public static function pollZot($url, $data)
825 $curlResult = Network::curl($url);
826 if ($curlResult->isTimeout()) {
829 $content = $curlResult->getBody();
834 $json = json_decode($content, true);
835 if (!is_array($json)) {
839 if (empty($data['network'])) {
840 if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
841 $data['network'] = Protocol::ZOT;
842 } elseif (!isset($json['protocols'])) {
843 $data['network'] = Protocol::ZOT;
847 if (!empty($json['guid']) && empty($data['guid'])) {
848 $data['guid'] = $json['guid'];
850 if (!empty($json['key']) && empty($data['pubkey'])) {
851 $data['pubkey'] = $json['key'];
853 if (!empty($json['name'])) {
854 $data['name'] = $json['name'];
856 if (!empty($json['photo'])) {
857 $data['photo'] = $json['photo'];
858 if (!empty($json['photo_updated'])) {
859 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
862 if (!empty($json['address'])) {
863 $data['addr'] = $json['address'];
865 if (!empty($json['url'])) {
866 $data['url'] = $json['url'];
868 if (!empty($json['connections_url'])) {
869 $data['poco'] = $json['connections_url'];
871 if (isset($json['searchable'])) {
872 $data['hide'] = !$json['searchable'];
874 if (!empty($json['public_forum'])) {
875 $data['community'] = $json['public_forum'];
876 $data['account-type'] = Contact::PAGE_COMMUNITY;
879 if (!empty($json['profile'])) {
880 $profile = $json['profile'];
881 if (!empty($profile['description'])) {
882 $data['about'] = $profile['description'];
884 if (!empty($profile['keywords'])) {
885 $keywords = implode(', ', $profile['keywords']);
886 if (!empty($keywords)) {
887 $data['keywords'] = $keywords;
892 if (!empty($profile['region'])) {
893 $loc['region'] = $profile['region'];
895 if (!empty($profile['country'])) {
896 $loc['country-name'] = $profile['country'];
898 $location = Profile::formatLocation($loc);
899 if (!empty($location)) {
900 $data['location'] = $location;
908 * Perform a webfinger request.
910 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
912 * @param string $url Address that should be probed
913 * @param string $type type
915 * @return array webfinger data
916 * @throws HTTPException\InternalServerErrorException
918 private static function webfinger($url, $type)
920 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
922 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
923 if ($curlResult->isTimeout()) {
924 self::$istimeout = true;
927 $data = $curlResult->getBody();
929 $webfinger = json_decode($data, true);
930 if (is_array($webfinger)) {
931 if (!isset($webfinger["links"])) {
932 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
938 // If it is not JSON, maybe it is XML
939 $xrd = XML::parseString($data, true);
940 if (!is_object($xrd)) {
941 Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
945 $xrd_arr = XML::elementToArray($xrd);
946 if (!isset($xrd_arr["xrd"]["link"])) {
947 Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
953 if (!empty($xrd_arr["xrd"]["subject"])) {
954 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
957 if (!empty($xrd_arr["xrd"]["alias"])) {
958 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
961 $webfinger["links"] = [];
963 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
964 if (!empty($data["@attributes"])) {
965 $attributes = $data["@attributes"];
966 } elseif ($value == "@attributes") {
972 $webfinger["links"][] = $attributes;
978 * Poll the Friendica specific noscrape page.
980 * "noscrape" is a faster alternative to fetch the data from the hcard.
981 * This functionality was originally created for the directory.
983 * @param string $noscrape_url Link to the noscrape page
984 * @param array $data The already fetched data
986 * @return array noscrape data
987 * @throws HTTPException\InternalServerErrorException
989 private static function pollNoscrape($noscrape_url, $data)
991 $curlResult = Network::curl($noscrape_url);
992 if ($curlResult->isTimeout()) {
993 self::$istimeout = true;
996 $content = $curlResult->getBody();
998 Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
1002 $json = json_decode($content, true);
1003 if (!is_array($json)) {
1004 Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
1008 if (!empty($json["fn"])) {
1009 $data["name"] = $json["fn"];
1012 if (!empty($json["addr"])) {
1013 $data["addr"] = $json["addr"];
1016 if (!empty($json["nick"])) {
1017 $data["nick"] = $json["nick"];
1020 if (!empty($json["guid"])) {
1021 $data["guid"] = $json["guid"];
1024 if (!empty($json["comm"])) {
1025 $data["community"] = $json["comm"];
1028 if (!empty($json["tags"])) {
1029 $keywords = implode(", ", $json["tags"]);
1030 if ($keywords != "") {
1031 $data["keywords"] = $keywords;
1035 $location = Profile::formatLocation($json);
1037 $data["location"] = $location;
1040 if (!empty($json["about"])) {
1041 $data["about"] = $json["about"];
1044 if (!empty($json["key"])) {
1045 $data["pubkey"] = $json["key"];
1048 if (!empty($json["photo"])) {
1049 $data["photo"] = $json["photo"];
1052 if (!empty($json["dfrn-request"])) {
1053 $data["request"] = $json["dfrn-request"];
1056 if (!empty($json["dfrn-confirm"])) {
1057 $data["confirm"] = $json["dfrn-confirm"];
1060 if (!empty($json["dfrn-notify"])) {
1061 $data["notify"] = $json["dfrn-notify"];
1064 if (!empty($json["dfrn-poll"])) {
1065 $data["poll"] = $json["dfrn-poll"];
1068 if (isset($json["hide"])) {
1069 $data["hide"] = (bool)$json["hide"];
1071 $data["hide"] = false;
1078 * Check for valid DFRN data
1080 * @param array $data DFRN data
1082 * @return int Number of errors
1084 public static function validDfrn($data)
1087 if (!isset($data['key'])) {
1090 if (!isset($data['dfrn-request'])) {
1093 if (!isset($data['dfrn-confirm'])) {
1096 if (!isset($data['dfrn-notify'])) {
1099 if (!isset($data['dfrn-poll'])) {
1106 * Fetch data from a DFRN profile page and via "noscrape"
1108 * @param string $profile_link Link to the profile page
1110 * @return array profile data
1111 * @throws HTTPException\InternalServerErrorException
1112 * @throws \ImagickException
1114 public static function profile($profile_link)
1118 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
1120 // Fetch data via noscrape - this is faster
1121 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1122 $data = self::pollNoscrape($noscrape_url, $data);
1124 if (!isset($data["notify"])
1125 || !isset($data["confirm"])
1126 || !isset($data["request"])
1127 || !isset($data["poll"])
1128 || !isset($data["name"])
1129 || !isset($data["photo"])
1131 $data = self::pollHcard($profile_link, $data, true);
1136 if (empty($data["addr"]) || empty($data["nick"])) {
1137 $probe_data = self::uri($profile_link);
1138 $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1139 $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1142 $prof_data["addr"] = $data["addr"];
1143 $prof_data["nick"] = $data["nick"];
1144 $prof_data["dfrn-request"] = $data['request'] ?? null;
1145 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1146 $prof_data["dfrn-notify"] = $data['notify'] ?? null;
1147 $prof_data["dfrn-poll"] = $data['poll'] ?? null;
1148 $prof_data["photo"] = $data['photo'] ?? null;
1149 $prof_data["fn"] = $data['name'] ?? null;
1150 $prof_data["key"] = $data['pubkey'] ?? null;
1152 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
1158 * Check for DFRN contact
1160 * @param array $webfinger Webfinger data
1162 * @return array DFRN data
1163 * @throws HTTPException\InternalServerErrorException
1165 private static function dfrn($webfinger)
1169 // The array is reversed to take into account the order of preference for same-rel links
1170 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1171 foreach (array_reverse($webfinger["links"]) as $link) {
1172 if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1173 $data["network"] = Protocol::DFRN;
1174 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1175 $data["poll"] = $link["href"];
1176 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1177 $data["url"] = $link["href"];
1178 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1179 $hcard_url = $link["href"];
1180 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1181 $data["poco"] = $link["href"];
1182 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1183 $data["photo"] = $link["href"];
1184 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1185 $data["baseurl"] = trim($link["href"], '/');
1186 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1187 $data["guid"] = $link["href"];
1188 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1189 $data["pubkey"] = base64_decode($link["href"]);
1191 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1192 if (strstr($data["pubkey"], 'RSA ')) {
1193 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1198 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1199 foreach ($webfinger["aliases"] as $alias) {
1200 if (empty($data["url"]) && !strstr($alias, "@")) {
1201 $data["url"] = $alias;
1202 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1203 $data["alias"] = $alias;
1204 } elseif (substr($alias, 0, 5) == 'acct:') {
1205 $data["addr"] = substr($alias, 5);
1210 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1211 $data["addr"] = substr($webfinger["subject"], 5);
1214 if (!isset($data["network"]) || ($hcard_url == "")) {
1218 // Fetch data via noscrape - this is faster
1219 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1220 $data = self::pollNoscrape($noscrape_url, $data);
1222 if (isset($data["notify"])
1223 && isset($data["confirm"])
1224 && isset($data["request"])
1225 && isset($data["poll"])
1226 && isset($data["name"])
1227 && isset($data["photo"])
1232 $data = self::pollHcard($hcard_url, $data, true);
1238 * Poll the hcard page (Diaspora and Friendica specific)
1240 * @param string $hcard_url Link to the hcard page
1241 * @param array $data The already fetched data
1242 * @param boolean $dfrn Poll DFRN specific data
1244 * @return array hcard data
1245 * @throws HTTPException\InternalServerErrorException
1247 private static function pollHcard($hcard_url, $data, $dfrn = false)
1249 $curlResult = Network::curl($hcard_url);
1250 if ($curlResult->isTimeout()) {
1251 self::$istimeout = true;
1254 $content = $curlResult->getBody();
1259 $doc = new DOMDocument();
1260 if (!@$doc->loadHTML($content)) {
1264 $xpath = new DomXPath($doc);
1266 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1267 if (!is_object($vcards)) {
1271 if (!isset($data["baseurl"])) {
1272 $data["baseurl"] = "";
1275 if ($vcards->length > 0) {
1276 $vcard = $vcards->item(0);
1278 // We have to discard the guid from the hcard in favour of the guid from lrdd
1279 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1280 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1281 if (($search->length > 0) && empty($data["guid"])) {
1282 $data["guid"] = $search->item(0)->nodeValue;
1285 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1286 if ($search->length > 0) {
1287 $data["nick"] = $search->item(0)->nodeValue;
1290 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1291 if ($search->length > 0) {
1292 $data["name"] = $search->item(0)->nodeValue;
1295 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1296 if ($search->length > 0) {
1297 $data["searchable"] = $search->item(0)->nodeValue;
1300 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1301 if ($search->length > 0) {
1302 $data["pubkey"] = $search->item(0)->nodeValue;
1303 if (strstr($data["pubkey"], 'RSA ')) {
1304 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1308 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1309 if ($search->length > 0) {
1310 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1315 if (!empty($vcard)) {
1316 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1317 foreach ($photos as $photo) {
1319 foreach ($photo->attributes as $attribute) {
1320 $attr[$attribute->name] = trim($attribute->value);
1323 if (isset($attr["src"]) && isset($attr["width"])) {
1324 $avatar[$attr["width"]] = $attr["src"];
1327 // We don't have a width. So we just take everything that we got.
1328 // This is a Hubzilla workaround which doesn't send a width.
1329 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1330 $avatar[] = $attr["src"];
1335 if (sizeof($avatar)) {
1337 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1341 // Poll DFRN specific data
1342 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1343 if ($search->length > 0) {
1344 foreach ($search as $link) {
1345 //$data["request"] = $search->item(0)->nodeValue;
1347 foreach ($link->attributes as $attribute) {
1348 $attr[$attribute->name] = trim($attribute->value);
1351 $data[substr($attr["rel"], 5)] = $attr["href"];
1355 // Older Friendica versions had used the "uid" field differently than newer versions
1356 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1357 unset($data["guid"]);
1366 * Check for Diaspora contact
1368 * @param array $webfinger Webfinger data
1370 * @return array Diaspora data
1371 * @throws HTTPException\InternalServerErrorException
1373 private static function diaspora($webfinger)
1378 // The array is reversed to take into account the order of preference for same-rel links
1379 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1380 foreach (array_reverse($webfinger["links"]) as $link) {
1381 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1382 $hcard_url = $link["href"];
1383 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1384 $data["baseurl"] = trim($link["href"], '/');
1385 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1386 $data["guid"] = $link["href"];
1387 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1388 $data["url"] = $link["href"];
1389 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1390 $data["poll"] = $link["href"];
1391 } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1392 $data["poco"] = $link["href"];
1393 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1394 $data["notify"] = $link["href"];
1395 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1396 $data["pubkey"] = base64_decode($link["href"]);
1398 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1399 if (strstr($data["pubkey"], 'RSA ')) {
1400 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1405 if (empty($data["url"]) || empty($hcard_url)) {
1409 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1410 foreach ($webfinger["aliases"] as $alias) {
1411 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1412 $data["alias"] = $alias;
1413 } elseif (substr($alias, 0, 5) == 'acct:') {
1414 $data["addr"] = substr($alias, 5);
1419 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1420 $data["addr"] = substr($webfinger["subject"], 5);
1423 // Fetch further information from the hcard
1424 $data = self::pollHcard($hcard_url, $data);
1430 if (!empty($data["url"])
1431 && !empty($data["guid"])
1432 && !empty($data["baseurl"])
1433 && !empty($data["pubkey"])
1434 && !empty($hcard_url)
1436 $data["network"] = Protocol::DIASPORA;
1438 // The Diaspora handle must always be lowercase
1439 if (!empty($data["addr"])) {
1440 $data["addr"] = strtolower($data["addr"]);
1443 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1444 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1445 $data["batch"] = $data["baseurl"] . "/receive/public";
1454 * Check for OStatus contact
1456 * @param array $webfinger Webfinger data
1457 * @param bool $short Short detection mode
1459 * @return array|bool OStatus data or "false" on error or "true" on short mode
1460 * @throws HTTPException\InternalServerErrorException
1462 private static function ostatus($webfinger, $short = false)
1466 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1467 foreach ($webfinger["aliases"] as $alias) {
1468 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1469 $data["addr"] = str_replace('acct:', '', $alias);
1474 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1475 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1477 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1480 if (is_array($webfinger["links"])) {
1481 // The array is reversed to take into account the order of preference for same-rel links
1482 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1483 foreach (array_reverse($webfinger["links"]) as $link) {
1484 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1485 && (($link["type"] ?? "") == "text/html")
1486 && ($link["href"] != "")
1488 $data["url"] = $link["href"];
1489 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1490 $data["notify"] = $link["href"];
1491 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1492 $data["poll"] = $link["href"];
1493 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1494 $pubkey = $link["href"];
1496 if (substr($pubkey, 0, 5) === 'data:') {
1497 if (strstr($pubkey, ',')) {
1498 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1500 $pubkey = substr($pubkey, 5);
1502 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1503 $curlResult = Network::curl($pubkey);
1504 if ($curlResult->isTimeout()) {
1505 self::$istimeout = true;
1508 $pubkey = $curlResult->getBody();
1511 $key = explode(".", $pubkey);
1513 if (sizeof($key) >= 3) {
1514 $m = Strings::base64UrlDecode($key[1]);
1515 $e = Strings::base64UrlDecode($key[2]);
1516 $data["pubkey"] = Crypto::meToPem($m, $e);
1522 if (isset($data["notify"]) && isset($data["pubkey"])
1523 && isset($data["poll"])
1524 && isset($data["url"])
1526 $data["network"] = Protocol::OSTATUS;
1535 // Fetch all additional data from the feed
1536 $curlResult = Network::curl($data["poll"]);
1537 if ($curlResult->isTimeout()) {
1538 self::$istimeout = true;
1541 $feed = $curlResult->getBody();
1542 $feed_data = Feed::import($feed);
1547 if (!empty($feed_data["header"]["author-name"])) {
1548 $data["name"] = $feed_data["header"]["author-name"];
1550 if (!empty($feed_data["header"]["author-nick"])) {
1551 $data["nick"] = $feed_data["header"]["author-nick"];
1553 if (!empty($feed_data["header"]["author-avatar"])) {
1554 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1556 if (!empty($feed_data["header"]["author-id"])) {
1557 $data["alias"] = $feed_data["header"]["author-id"];
1559 if (!empty($feed_data["header"]["author-location"])) {
1560 $data["location"] = $feed_data["header"]["author-location"];
1562 if (!empty($feed_data["header"]["author-about"])) {
1563 $data["about"] = $feed_data["header"]["author-about"];
1565 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1566 // So we take the value that we just fetched, although the other one worked as well
1567 if (!empty($feed_data["header"]["author-link"])) {
1568 $data["url"] = $feed_data["header"]["author-link"];
1571 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1572 $data['url'] = $data["alias"];
1573 $data["alias"] = '';
1576 /// @todo Fetch location and "about" from the feed as well
1581 * Fetch data from a pump.io profile page
1583 * @param string $profile_link Link to the profile page
1585 * @return array profile data
1587 private static function pumpioProfileData($profile_link)
1589 $curlResult = Network::curl($profile_link);
1590 if (!$curlResult->isSuccess()) {
1594 $doc = new DOMDocument();
1595 if (!@$doc->loadHTML($curlResult->getBody())) {
1599 $xpath = new DomXPath($doc);
1603 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1605 if ($data["name"] == '') {
1606 // This is ugly - but pump.io doesn't seem to know a better way for it
1607 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1608 $pos = strpos($data["name"], chr(10));
1610 $data["name"] = trim(substr($data["name"], 0, $pos));
1614 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1616 if ($data["location"] == '') {
1617 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1620 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1622 if ($data["about"] == '') {
1623 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1626 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1628 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1631 foreach ($avatar->attributes as $attribute) {
1632 if ($attribute->name == "src") {
1633 $data["photo"] = trim($attribute->value);
1642 * Check for pump.io contact
1644 * @param array $webfinger Webfinger data
1645 * @param string $addr
1646 * @return array pump.io data
1648 private static function pumpio($webfinger, $addr)
1651 // The array is reversed to take into account the order of preference for same-rel links
1652 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1653 foreach (array_reverse($webfinger["links"]) as $link) {
1654 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1655 && (($link["type"] ?? "") == "text/html")
1656 && ($link["href"] != "")
1658 $data["url"] = $link["href"];
1659 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1660 $data["notify"] = $link["href"];
1661 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1662 $data["poll"] = $link["href"];
1663 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1664 $data["dialback"] = $link["href"];
1667 if (isset($data["poll"]) && isset($data["notify"])
1668 && isset($data["dialback"])
1669 && isset($data["url"])
1671 // by now we use these fields only for the network type detection
1672 // So we unset all data that isn't used at the moment
1673 unset($data["dialback"]);
1675 $data["network"] = Protocol::PUMPIO;
1680 $profile_data = self::pumpioProfileData($data["url"]);
1682 if (!$profile_data) {
1686 $data = array_merge($data, $profile_data);
1688 if (($addr != '') && ($data['name'] != '')) {
1689 $name = trim(str_replace($addr, '', $data['name']));
1691 $data['name'] = $name;
1699 * Check for twitter contact
1701 * @param string $uri
1703 * @return array twitter data
1705 private static function twitter($uri)
1707 if (preg_match('=(.*)@twitter.com=i', $uri, $matches)) {
1708 $nick = $matches[1];
1709 } elseif (preg_match('=https?://twitter.com/(.*)=i', $uri, $matches)) {
1710 $nick = $matches[1];
1716 $data['url'] = 'https://twitter.com/' . $nick;
1717 $data['addr'] = $nick . '@twitter.com';
1718 $data['nick'] = $data['name'] = $nick;
1719 $data['network'] = Protocol::TWITTER;
1720 $data['baseurl'] = 'https://twitter.com';
1722 $curlResult = Network::curl($data['url'], false);
1723 if (!$curlResult->isSuccess()) {
1727 $body = $curlResult->getBody();
1728 $doc = new DOMDocument();
1729 @$doc->loadHTML($body);
1730 $xpath = new DOMXPath($doc);
1732 $list = $xpath->query('//img[@class]');
1733 foreach ($list as $node) {
1735 if ($node->attributes->length) {
1736 foreach ($node->attributes as $attribute) {
1737 $img_attr[$attribute->name] = $attribute->value;
1741 if (empty($img_attr['class'])) {
1745 if (strpos($img_attr['class'], 'ProfileAvatar-image') !== false) {
1746 if (!empty($img_attr['src'])) {
1747 $data['photo'] = $img_attr['src'];
1749 if (!empty($img_attr['alt'])) {
1750 $data['name'] = $img_attr['alt'];
1759 * Check page for feed link
1761 * @param string $url Page link
1763 * @return string feed link
1765 private static function getFeedLink($url)
1767 $curlResult = Network::curl($url);
1768 if (!$curlResult->isSuccess()) {
1772 $doc = new DOMDocument();
1773 if (!@$doc->loadHTML($curlResult->getBody())) {
1777 $xpath = new DomXPath($doc);
1779 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1780 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1781 if (!is_object($feeds)) {
1785 if ($feeds->length == 0) {
1791 foreach ($feeds as $feed) {
1793 foreach ($feed->attributes as $attribute) {
1794 $attr[$attribute->name] = trim($attribute->value);
1797 if (empty($feed_url) && !empty($attr['href'])) {
1798 $feed_url = $attr["href"];
1806 * Check for feed contact
1808 * @param string $url Profile link
1809 * @param boolean $probe Do a probe if the page contains a feed link
1811 * @return array feed data
1812 * @throws HTTPException\InternalServerErrorException
1814 private static function feed($url, $probe = true)
1816 $curlResult = Network::curl($url);
1817 if ($curlResult->isTimeout()) {
1818 self::$istimeout = true;
1821 $feed = $curlResult->getBody();
1822 $feed_data = Feed::import($feed);
1829 $feed_url = self::getFeedLink($url);
1835 return self::feed($feed_url, false);
1838 if (!empty($feed_data["header"]["author-name"])) {
1839 $data["name"] = $feed_data["header"]["author-name"];
1842 if (!empty($feed_data["header"]["author-nick"])) {
1843 $data["nick"] = $feed_data["header"]["author-nick"];
1846 if (!empty($feed_data["header"]["author-avatar"])) {
1847 $data["photo"] = $feed_data["header"]["author-avatar"];
1850 if (!empty($feed_data["header"]["author-id"])) {
1851 $data["alias"] = $feed_data["header"]["author-id"];
1854 $data["url"] = $url;
1855 $data["poll"] = $url;
1857 if (!empty($feed_data["header"]["author-link"])) {
1858 $data["baseurl"] = $feed_data["header"]["author-link"];
1860 $data["baseurl"] = $data["url"];
1863 $data["network"] = Protocol::FEED;
1869 * Check for mail contact
1871 * @param string $uri Profile link
1872 * @param integer $uid User ID
1874 * @return array mail data
1875 * @throws \Exception
1877 private static function mail($uri, $uid)
1879 if (!Network::isEmailDomainValid($uri)) {
1887 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1889 $condition = ["`uid` = ? AND `server` != ''", $uid];
1890 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1891 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1893 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1897 $mailbox = Email::constructMailboxName($mailacct);
1899 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1900 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1905 $msgs = Email::poll($mbox, $uri);
1906 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1908 if (!count($msgs)) {
1912 $phost = substr($uri, strpos($uri, '@') + 1);
1915 $data["addr"] = $uri;
1916 $data["network"] = Protocol::MAIL;
1917 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1918 $data["nick"] = $data["name"];
1919 $data["photo"] = Network::lookupAvatarByEmail($uri);
1920 $data["url"] = 'mailto:'.$uri;
1921 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1922 $data["poll"] = 'email ' . Strings::getRandomHex();
1924 $x = Email::messageMeta($mbox, $msgs[0]);
1925 if (stristr($x[0]->from, $uri)) {
1926 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1927 } elseif (stristr($x[0]->to, $uri)) {
1928 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1931 foreach ($adr as $feadr) {
1932 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1933 &&(strcasecmp($feadr->host, $phost) == 0)
1934 && (strlen($feadr->personal))
1936 $personal = imap_mime_header_decode($feadr->personal);
1938 foreach ($personal as $perspart) {
1939 if ($perspart->charset != "default") {
1940 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1942 $data["name"] .= $perspart->text;
1946 $data["name"] = Strings::escapeTags($data["name"]);
1950 if (!empty($mbox)) {
1957 * Mix two paths together to possibly fix missing parts
1959 * @param string $avatar Path to the avatar
1960 * @param string $base Another path that is hopefully complete
1962 * @return string fixed avatar path
1963 * @throws \Exception
1965 public static function fixAvatar($avatar, $base)
1967 $base_parts = parse_url($base);
1969 // Remove all parts that could create a problem
1970 unset($base_parts['path']);
1971 unset($base_parts['query']);
1972 unset($base_parts['fragment']);
1974 $avatar_parts = parse_url($avatar);
1977 $parts = array_merge($base_parts, $avatar_parts);
1979 // And put them together again
1980 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1981 $host = isset($parts['host']) ? $parts['host'] : '';
1982 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1983 $path = isset($parts['path']) ? $parts['path'] : '';
1984 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1985 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1987 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1989 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);