3 * @file src/Network/Probe.php
5 namespace Friendica\Network;
8 * @file src/Network/Probe.php
9 * @brief Functions for probing URL
13 use Friendica\Core\Cache;
14 use Friendica\Core\Config;
15 use Friendica\Core\Logger;
16 use Friendica\Core\Protocol;
17 use Friendica\Core\System;
18 use Friendica\Database\DBA;
19 use Friendica\Model\Contact;
20 use Friendica\Model\Profile;
21 use Friendica\Protocol\Email;
22 use Friendica\Protocol\Feed;
23 use Friendica\Protocol\ActivityPub;
24 use Friendica\Util\Crypto;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\Network;
27 use Friendica\Util\Strings;
28 use Friendica\Util\XML;
32 * @brief This class contain functions for probing URL
37 private static $baseurl;
38 private static $istimeout;
41 * @brief Rearrange the array so that it always has the same order
43 * @param array $data Unordered data
45 * @return array Ordered data
47 private static function rearrangeData($data)
49 $fields = ["name", "nick", "guid", "url", "addr", "alias",
50 "photo", "community", "keywords", "location", "about",
51 "batch", "notify", "poll", "request", "confirm", "poco",
52 "priority", "network", "pubkey", "baseurl"];
55 foreach ($fields as $field) {
56 if (isset($data[$field])) {
57 $newdata[$field] = $data[$field];
59 $newdata[$field] = "";
63 // We don't use the "priority" field anymore and replace it with a dummy.
64 $newdata["priority"] = 0;
70 * @brief Check if the hostname belongs to the own server
72 * @param string $host The hostname that is to be checked
74 * @return bool Does the testes hostname belongs to the own server?
76 private static function ownHost($host)
78 $own_host = \get_app()->getHostName();
80 $parts = parse_url($host);
82 if (!isset($parts['scheme'])) {
83 $parts = parse_url('http://'.$host);
86 if (!isset($parts['host'])) {
89 return $parts['host'] == $own_host;
93 * @brief Probes for webfinger path via "host-meta"
95 * We have to check if the servers in the future still will offer this.
96 * It seems as if it was dropped from the standard.
98 * @param string $host The host part of an url
100 * @return array with template and type of the webfinger template for JSON or XML
101 * @throws HTTPException\InternalServerErrorException
103 private static function hostMeta($host)
105 // Reset the static variable
108 $ssl_url = "https://".$host."/.well-known/host-meta";
109 $url = "http://".$host."/.well-known/host-meta";
111 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
114 Logger::log("Probing for ".$host, Logger::DEBUG);
117 $curlResult = Network::curl($ssl_url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
118 if ($curlResult->isSuccess()) {
119 $xml = $curlResult->getBody();
120 $xrd = XML::parseString($xml, false);
121 $host_url = 'https://'.$host;
124 if (!is_object($xrd)) {
125 $curlResult = Network::curl($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
126 if ($curlResult->isTimeout()) {
127 Logger::log("Probing timeout for " . $url, Logger::DEBUG);
128 self::$istimeout = true;
131 $xml = $curlResult->getBody();
132 $xrd = XML::parseString($xml, false);
133 $host_url = 'http://'.$host;
135 if (!is_object($xrd)) {
136 Logger::log("No xrd object found for ".$host, Logger::DEBUG);
140 $links = XML::elementToArray($xrd);
141 if (!isset($links["xrd"]["link"])) {
142 Logger::log("No xrd data found for ".$host, Logger::DEBUG);
147 // The following webfinger path is defined in RFC 7033 https://tools.ietf.org/html/rfc7033
148 // Problem is that Hubzilla currently doesn't provide all data in the JSON webfinger
149 // compared to the XML webfinger. So this is commented out by now.
150 // $lrdd = array("application/jrd+json" => $host_url.'/.well-known/webfinger?resource={uri}');
152 foreach ($links["xrd"]["link"] as $value => $link) {
153 if (!empty($link["@attributes"])) {
154 $attributes = $link["@attributes"];
155 } elseif ($value == "@attributes") {
161 if (!empty($attributes["rel"]) && $attributes["rel"] == "lrdd" && !empty($attributes["template"])) {
162 $type = (empty($attributes["type"]) ? '' : $attributes["type"]);
164 $lrdd[$type] = $attributes["template"];
168 self::$baseurl = $host_url;
170 Logger::log("Probing successful for ".$host, Logger::DEBUG);
176 * @brief Perform Webfinger lookup and return DFRN data
178 * Given an email style address, perform webfinger lookup and
179 * return the resulting DFRN profile URL, or if no DFRN profile URL
180 * is located, returns an OStatus subscription template (prefixed
181 * with the string 'stat:' to identify it as on OStatus template).
182 * If this isn't an email style address just return $webbie.
183 * Return an empty string if email-style addresses but webfinger fails,
184 * or if the resultant personal XRD doesn't contain a supported
185 * subscription/friend-request attribute.
187 * amended 7/9/2011 to return an hcard which could save potentially loading
188 * a lengthy content page to scrape dfrn attributes
190 * @param string $webbie Address that should be probed
191 * @param string $hcard_url Link to the hcard - is returned by reference
193 * @return string profile link
194 * @throws HTTPException\InternalServerErrorException
196 public static function webfingerDfrn($webbie, &$hcard_url)
200 $links = self::lrdd($webbie);
201 Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA);
203 foreach ($links as $link) {
204 if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
205 $profile_link = $link['@attributes']['href'];
207 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) && ($profile_link == "")) {
208 $profile_link = 'stat:'.$link['@attributes']['template'];
210 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
211 $hcard_url = $link['@attributes']['href'];
215 return $profile_link;
219 * @brief Check an URI for LRDD data
221 * this is a replacement for the "lrdd" function.
222 * It isn't used in this class and has some redundancies in the code.
223 * When time comes we can check the existing calls for "lrdd" if we can rework them.
225 * @param string $uri Address that should be probed
227 * @return array uri data
228 * @throws HTTPException\InternalServerErrorException
230 public static function lrdd($uri)
232 $lrdd = self::hostMeta($uri);
235 if (is_bool($lrdd)) {
240 $parts = @parse_url($uri);
241 if (!$parts || empty($parts["host"]) || empty($parts["path"])) {
245 $host = $parts["host"];
246 if (!empty($parts["port"])) {
247 $host .= ':'.$parts["port"];
250 $path_parts = explode("/", trim($parts["path"], "/"));
252 $nick = array_pop($path_parts);
255 $lrdd = self::hostMeta($host);
256 $host .= "/".array_shift($path_parts);
257 } while (!$lrdd && (sizeof($path_parts) > 0));
261 Logger::log("No lrdd data found for ".$uri, Logger::DEBUG);
265 foreach ($lrdd as $type => $template) {
270 $path = str_replace('{uri}', urlencode($uri), $template);
271 $webfinger = self::webfinger($path, $type);
273 if (!$webfinger && (strstr($uri, "@"))) {
274 $path = str_replace('{uri}', urlencode("acct:".$uri), $template);
275 $webfinger = self::webfinger($path, $type);
278 // Special treatment for Mastodon
279 // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
280 // But the webfinger for this format fails.
281 if (!$webfinger && !empty($nick)) {
282 // Mastodon uses a "@" as prefix for usernames in their url format
283 $nick = ltrim($nick, '@');
285 $addr = $nick."@".$host;
287 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
288 $webfinger = self::webfinger($path, $type);
292 if (!is_array($webfinger["links"])) {
293 Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
299 foreach ($webfinger["links"] as $link) {
300 $data[] = ["@attributes" => $link];
303 if (is_array($webfinger["aliases"])) {
304 foreach ($webfinger["aliases"] as $alias) {
305 $data[] = ["@attributes" =>
315 * @brief Fetch information (protocol endpoints and user information) about a given uri
317 * @param string $uri Address that should be probed
318 * @param string $network Test for this specific network
319 * @param integer $uid User ID for the probe (only used for mails)
320 * @param boolean $cache Use cached values?
322 * @return array uri data
323 * @throws HTTPException\InternalServerErrorException
324 * @throws \ImagickException
326 public static function uri($uri, $network = '', $uid = -1, $cache = true)
329 $result = Cache::get('Probe::uri:' . $network . ':' . $uri);
330 if (!is_null($result)) {
339 self::$istimeout = false;
341 if ($network != Protocol::ACTIVITYPUB) {
342 $data = self::detect($uri, $network, $uid);
347 // When the previous detection process had got a time out
348 // we could falsely detect a Friendica profile as AP profile.
349 if (!self::$istimeout) {
350 $ap_profile = ActivityPub::probeProfile($uri);
352 if (!empty($ap_profile) && empty($network) && (defaults($data, 'network', '') != Protocol::DFRN)) {
357 if (!isset($data['url'])) {
361 if (!empty($data['photo'])) {
362 $data['baseurl'] = Network::getUrlMatch(Strings::normaliseLink(defaults($data, 'baseurl', '')), Strings::normaliseLink($data['photo']));
364 $data['photo'] = System::baseUrl() . '/images/person-300.jpg';
367 if (empty($data['name'])) {
368 if (!empty($data['nick'])) {
369 $data['name'] = $data['nick'];
372 if (empty($data['name'])) {
373 $data['name'] = $data['url'];
377 if (empty($data['nick'])) {
378 $data['nick'] = strtolower($data['name']);
380 if (strpos($data['nick'], ' ')) {
381 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
385 if (!empty(self::$baseurl)) {
386 $data['baseurl'] = self::$baseurl;
389 if (empty($data['network'])) {
390 $data['network'] = Protocol::PHANTOM;
393 $data = self::rearrangeData($data);
395 // Only store into the cache if the value seems to be valid
396 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
397 Cache::set('Probe::uri:' . $network . ':' . $uri, $data, Cache::DAY);
399 /// @todo temporary fix - we need a real contact update function that updates only changing fields
400 /// The biggest problem is the avatar picture that could have a reduced image size.
401 /// It should only be updated if the existing picture isn't existing anymore.
402 /// We only update the contact when it is no probing for a specific network.
403 if (($data['network'] != Protocol::FEED)
412 'name' => $data['name'],
413 'nick' => $data['nick'],
414 'url' => $data['url'],
415 'addr' => $data['addr'],
416 'photo' => $data['photo'],
417 'keywords' => $data['keywords'],
418 'location' => $data['location'],
419 'about' => $data['about'],
420 'notify' => $data['notify'],
421 'network' => $data['network'],
422 'server_url' => $data['baseurl']
425 // This doesn't cover the case when a community isn't a community anymore
426 if (!empty($data['community']) && $data['community']) {
427 $fields['community'] = $data['community'];
428 $fields['contact-type'] = Contact::TYPE_COMMUNITY;
433 foreach ($fields as $key => $val) {
435 unset($fields[$key]);
437 $fieldnames[] = $key;
441 $fields['updated'] = DateTimeFormat::utcNow();
443 $condition = ['nurl' => Strings::normaliseLink($data['url'])];
445 $old_fields = DBA::selectFirst('gcontact', $fieldnames, $condition);
447 // When the gcontact doesn't exist, the value "true" will trigger an insert.
448 // In difference to the public contacts we want to have every contact
449 // in the world in our global contacts.
453 // These values have to be set only on insert
454 $fields['photo'] = $data['photo'];
455 $fields['created'] = DateTimeFormat::utcNow();
458 DBA::update('gcontact', $fields, $condition, $old_fields);
461 'name' => $data['name'],
462 'nick' => $data['nick'],
463 'url' => $data['url'],
464 'addr' => $data['addr'],
465 'alias' => $data['alias'],
466 'keywords' => $data['keywords'],
467 'location' => $data['location'],
468 'about' => $data['about'],
469 'batch' => $data['batch'],
470 'notify' => $data['notify'],
471 'poll' => $data['poll'],
472 'request' => $data['request'],
473 'confirm' => $data['confirm'],
474 'poco' => $data['poco'],
475 'network' => $data['network'],
476 'pubkey' => $data['pubkey'],
477 'priority' => $data['priority'],
479 'rel' => Contact::SHARING
484 foreach ($fields as $key => $val) {
486 unset($fields[$key]);
488 $fieldnames[] = $key;
492 $condition = ['nurl' => Strings::normaliseLink($data['url']), 'self' => false, 'uid' => 0];
494 // "$old_fields" will return a "false" when the contact doesn't exist.
495 // This won't trigger an insert. This is intended, since we only need
496 // public contacts for everyone we store items from.
497 // We don't need to store every contact on the planet.
498 $old_fields = DBA::selectFirst('contact', $fieldnames, $condition);
500 $fields['name-date'] = DateTimeFormat::utcNow();
501 $fields['uri-date'] = DateTimeFormat::utcNow();
502 $fields['success_update'] = DateTimeFormat::utcNow();
504 DBA::update('contact', $fields, $condition, $old_fields);
512 * @brief Switch the scheme of an url between http and https
514 * @param string $url URL
516 * @return string switched URL
518 private static function switchScheme($url)
520 $parts = parse_url($url);
522 if (!isset($parts['scheme'])) {
526 if ($parts['scheme'] == 'http') {
527 $url = str_replace('http://', 'https://', $url);
528 } elseif ($parts['scheme'] == 'https') {
529 $url = str_replace('https://', 'http://', $url);
536 * @brief Checks if a profile url should be OStatus but only provides partial information
538 * @param array $webfinger Webfinger data
539 * @param string $lrdd Path template for webfinger request
540 * @param string $type type
542 * @return array fixed webfinger data
543 * @throws HTTPException\InternalServerErrorException
545 private static function fixOStatus($webfinger, $lrdd, $type)
547 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
554 foreach ($webfinger['links'] as $link) {
555 if ($link['rel'] == NAMESPACE_OSTATUSSUB) {
558 if ($link['rel'] == 'magic-public-key') {
563 if (!$is_ostatus || $has_key) {
567 $url = self::switchScheme($webfinger['subject']);
568 $path = str_replace('{uri}', urlencode($url), $lrdd);
569 $webfinger2 = self::webfinger($path, $type);
571 // Is the new webfinger detectable as OStatus?
572 if (self::ostatus($webfinger2, true)) {
573 $webfinger = $webfinger2;
580 * @brief Fetch information (protocol endpoints and user information) about a given uri
582 * This function is only called by the "uri" function that adds caching and rearranging of data.
584 * @param string $uri Address that should be probed
585 * @param string $network Test for this specific network
586 * @param integer $uid User ID for the probe (only used for mails)
588 * @return array uri data
589 * @throws HTTPException\InternalServerErrorException
591 private static function detect($uri, $network, $uid)
593 $parts = parse_url($uri);
595 if (!empty($parts["scheme"]) && !empty($parts["host"])) {
596 $host = $parts["host"];
597 if (!empty($parts["port"])) {
598 $host .= ':'.$parts["port"];
601 if ($host == 'twitter.com') {
602 return ["network" => Protocol::TWITTER];
604 $lrdd = self::hostMeta($host);
606 if (is_bool($lrdd)) {
610 $path_parts = explode("/", trim(defaults($parts, 'path', ''), "/"));
612 while (!$lrdd && (sizeof($path_parts) > 1)) {
613 $host .= "/".array_shift($path_parts);
614 $lrdd = self::hostMeta($host);
617 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
618 return self::feed($uri);
620 $nick = array_pop($path_parts);
622 // Mastodon uses a "@" as prefix for usernames in their url format
623 $nick = ltrim($nick, '@');
625 $addr = $nick."@".$host;
626 } elseif (strstr($uri, '@')) {
627 // If the URI starts with "mailto:" then jump directly to the mail detection
628 if (strpos($uri, 'mailto:') !== false) {
629 $uri = str_replace('mailto:', '', $uri);
630 return self::mail($uri, $uid);
633 if ($network == Protocol::MAIL) {
634 return self::mail($uri, $uid);
636 // Remove "acct:" from the URI
637 $uri = str_replace('acct:', '', $uri);
639 $host = substr($uri, strpos($uri, '@') + 1);
640 $nick = substr($uri, 0, strpos($uri, '@'));
642 if (strpos($uri, '@twitter.com')) {
643 return ["network" => Protocol::TWITTER];
645 $lrdd = self::hostMeta($host);
647 if (is_bool($lrdd)) {
652 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
653 return self::mail($uri, $uid);
657 Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
663 /// @todo Do we need the prefix "acct:" or "acct://"?
665 foreach ($lrdd as $type => $template) {
670 // At first try it with the given uri
671 $path = str_replace('{uri}', urlencode($uri), $template);
672 $webfinger = self::webfinger($path, $type);
674 // Fix possible problems with GNU Social probing to wrong scheme
675 $webfinger = self::fixOStatus($webfinger, $template, $type);
677 // We cannot be sure that the detected address was correct, so we don't use the values
678 if ($webfinger && ($uri != $addr)) {
683 // Try webfinger with the address (user@domain.tld)
685 $path = str_replace('{uri}', urlencode($addr), $template);
686 $webfinger = self::webfinger($path, $type);
689 // Mastodon needs to have it with "acct:"
691 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
692 $webfinger = self::webfinger($path, $type);
697 return self::feed($uri);
702 Logger::log("Probing ".$uri, Logger::DEBUG);
704 if (in_array($network, ["", Protocol::DFRN])) {
705 $result = self::dfrn($webfinger);
707 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
708 $result = self::diaspora($webfinger);
710 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
711 $result = self::ostatus($webfinger);
713 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
714 $result = self::pumpio($webfinger, $addr);
716 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
717 $result = self::feed($uri);
719 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
720 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
721 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
722 $result["nick"] = $nick;
725 if (empty($result["addr"]) && ($addr != "")) {
726 $result["addr"] = $addr;
730 if (empty($result["network"])) {
731 $result["network"] = Protocol::PHANTOM;
734 if (empty($result["url"])) {
735 $result["url"] = $uri;
738 Logger::log($uri." is ".$result["network"], Logger::DEBUG);
740 if (empty($result["baseurl"])) {
741 $pos = strpos($result["url"], $host);
743 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
750 * @brief Perform a webfinger request.
752 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
754 * @param string $url Address that should be probed
755 * @param string $type type
757 * @return array webfinger data
758 * @throws HTTPException\InternalServerErrorException
760 private static function webfinger($url, $type)
762 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
765 $curlResult = Network::curl($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
766 if ($curlResult->isTimeout()) {
767 self::$istimeout = true;
770 $data = $curlResult->getBody();
772 $webfinger = json_decode($data, true);
773 if (is_array($webfinger)) {
774 if (!isset($webfinger["links"])) {
775 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
781 // If it is not JSON, maybe it is XML
782 $xrd = XML::parseString($data, false);
783 if (!is_object($xrd)) {
784 Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
788 $xrd_arr = XML::elementToArray($xrd);
789 if (!isset($xrd_arr["xrd"]["link"])) {
790 Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
796 if (!empty($xrd_arr["xrd"]["subject"])) {
797 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
800 if (!empty($xrd_arr["xrd"]["alias"])) {
801 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
804 $webfinger["links"] = [];
806 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
807 if (!empty($data["@attributes"])) {
808 $attributes = $data["@attributes"];
809 } elseif ($value == "@attributes") {
815 $webfinger["links"][] = $attributes;
821 * @brief Poll the Friendica specific noscrape page.
823 * "noscrape" is a faster alternative to fetch the data from the hcard.
824 * This functionality was originally created for the directory.
826 * @param string $noscrape_url Link to the noscrape page
827 * @param array $data The already fetched data
829 * @return array noscrape data
830 * @throws HTTPException\InternalServerErrorException
832 private static function pollNoscrape($noscrape_url, $data)
834 $curlResult = Network::curl($noscrape_url);
835 if ($curlResult->isTimeout()) {
836 self::$istimeout = true;
839 $content = $curlResult->getBody();
841 Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
845 $json = json_decode($content, true);
846 if (!is_array($json)) {
847 Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
851 if (!empty($json["fn"])) {
852 $data["name"] = $json["fn"];
855 if (!empty($json["addr"])) {
856 $data["addr"] = $json["addr"];
859 if (!empty($json["nick"])) {
860 $data["nick"] = $json["nick"];
863 if (!empty($json["guid"])) {
864 $data["guid"] = $json["guid"];
867 if (!empty($json["comm"])) {
868 $data["community"] = $json["comm"];
871 if (!empty($json["tags"])) {
872 $keywords = implode(" ", $json["tags"]);
873 if ($keywords != "") {
874 $data["keywords"] = $keywords;
878 $location = Profile::formatLocation($json);
880 $data["location"] = $location;
883 if (!empty($json["about"])) {
884 $data["about"] = $json["about"];
887 if (!empty($json["key"])) {
888 $data["pubkey"] = $json["key"];
891 if (!empty($json["photo"])) {
892 $data["photo"] = $json["photo"];
895 if (!empty($json["dfrn-request"])) {
896 $data["request"] = $json["dfrn-request"];
899 if (!empty($json["dfrn-confirm"])) {
900 $data["confirm"] = $json["dfrn-confirm"];
903 if (!empty($json["dfrn-notify"])) {
904 $data["notify"] = $json["dfrn-notify"];
907 if (!empty($json["dfrn-poll"])) {
908 $data["poll"] = $json["dfrn-poll"];
915 * @brief Check for valid DFRN data
917 * @param array $data DFRN data
919 * @return int Number of errors
921 public static function validDfrn($data)
924 if (!isset($data['key'])) {
927 if (!isset($data['dfrn-request'])) {
930 if (!isset($data['dfrn-confirm'])) {
933 if (!isset($data['dfrn-notify'])) {
936 if (!isset($data['dfrn-poll'])) {
943 * @brief Fetch data from a DFRN profile page and via "noscrape"
945 * @param string $profile_link Link to the profile page
947 * @return array profile data
948 * @throws HTTPException\InternalServerErrorException
949 * @throws \ImagickException
951 public static function profile($profile_link)
955 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
957 // Fetch data via noscrape - this is faster
958 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
959 $data = self::pollNoscrape($noscrape_url, $data);
961 if (!isset($data["notify"])
962 || !isset($data["confirm"])
963 || !isset($data["request"])
964 || !isset($data["poll"])
965 || !isset($data["name"])
966 || !isset($data["photo"])
968 $data = self::pollHcard($profile_link, $data, true);
973 if (empty($data["addr"]) || empty($data["nick"])) {
974 $probe_data = self::uri($profile_link);
975 $data["addr"] = defaults($data, "addr", $probe_data["addr"]);
976 $data["nick"] = defaults($data, "nick", $probe_data["nick"]);
979 $prof_data["addr"] = $data["addr"];
980 $prof_data["nick"] = $data["nick"];
981 $prof_data["dfrn-request"] = defaults($data, 'request', null);
982 $prof_data["dfrn-confirm"] = defaults($data, 'confirm', null);
983 $prof_data["dfrn-notify"] = defaults($data, 'notify' , null);
984 $prof_data["dfrn-poll"] = defaults($data, 'poll' , null);
985 $prof_data["photo"] = defaults($data, 'photo' , null);
986 $prof_data["fn"] = defaults($data, 'name' , null);
987 $prof_data["key"] = defaults($data, 'pubkey' , null);
989 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
995 * @brief Check for DFRN contact
997 * @param array $webfinger Webfinger data
999 * @return array DFRN data
1000 * @throws HTTPException\InternalServerErrorException
1002 private static function dfrn($webfinger)
1006 // The array is reversed to take into account the order of preference for same-rel links
1007 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1008 foreach (array_reverse($webfinger["links"]) as $link) {
1009 if (($link["rel"] == NAMESPACE_DFRN) && !empty($link["href"])) {
1010 $data["network"] = Protocol::DFRN;
1011 } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
1012 $data["poll"] = $link["href"];
1013 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (defaults($link, "type", "") == "text/html") && !empty($link["href"])) {
1014 $data["url"] = $link["href"];
1015 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1016 $hcard_url = $link["href"];
1017 } elseif (($link["rel"] == NAMESPACE_POCO) && !empty($link["href"])) {
1018 $data["poco"] = $link["href"];
1019 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1020 $data["photo"] = $link["href"];
1021 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1022 $data["baseurl"] = trim($link["href"], '/');
1023 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1024 $data["guid"] = $link["href"];
1025 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1026 $data["pubkey"] = base64_decode($link["href"]);
1028 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1029 if (strstr($data["pubkey"], 'RSA ')) {
1030 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1035 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1036 foreach ($webfinger["aliases"] as $alias) {
1037 if (empty($data["url"]) && !strstr($alias, "@")) {
1038 $data["url"] = $alias;
1039 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1040 $data["alias"] = $alias;
1041 } elseif (substr($alias, 0, 5) == 'acct:') {
1042 $data["addr"] = substr($alias, 5);
1047 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1048 $data["addr"] = substr($webfinger["subject"], 5);
1051 if (!isset($data["network"]) || ($hcard_url == "")) {
1055 // Fetch data via noscrape - this is faster
1056 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1057 $data = self::pollNoscrape($noscrape_url, $data);
1059 if (isset($data["notify"])
1060 && isset($data["confirm"])
1061 && isset($data["request"])
1062 && isset($data["poll"])
1063 && isset($data["name"])
1064 && isset($data["photo"])
1069 $data = self::pollHcard($hcard_url, $data, true);
1075 * @brief Poll the hcard page (Diaspora and Friendica specific)
1077 * @param string $hcard_url Link to the hcard page
1078 * @param array $data The already fetched data
1079 * @param boolean $dfrn Poll DFRN specific data
1081 * @return array hcard data
1082 * @throws HTTPException\InternalServerErrorException
1084 private static function pollHcard($hcard_url, $data, $dfrn = false)
1086 $curlResult = Network::curl($hcard_url);
1087 if ($curlResult->isTimeout()) {
1088 self::$istimeout = true;
1091 $content = $curlResult->getBody();
1096 $doc = new DOMDocument();
1097 if (!@$doc->loadHTML($content)) {
1101 $xpath = new DomXPath($doc);
1103 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1104 if (!is_object($vcards)) {
1108 if (!isset($data["baseurl"])) {
1109 $data["baseurl"] = "";
1112 if ($vcards->length > 0) {
1113 $vcard = $vcards->item(0);
1115 // We have to discard the guid from the hcard in favour of the guid from lrdd
1116 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1117 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1118 if (($search->length > 0) && empty($data["guid"])) {
1119 $data["guid"] = $search->item(0)->nodeValue;
1122 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1123 if ($search->length > 0) {
1124 $data["nick"] = $search->item(0)->nodeValue;
1127 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1128 if ($search->length > 0) {
1129 $data["name"] = $search->item(0)->nodeValue;
1132 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1133 if ($search->length > 0) {
1134 $data["searchable"] = $search->item(0)->nodeValue;
1137 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1138 if ($search->length > 0) {
1139 $data["pubkey"] = $search->item(0)->nodeValue;
1140 if (strstr($data["pubkey"], 'RSA ')) {
1141 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1145 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1146 if ($search->length > 0) {
1147 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1152 if (!empty($vcard)) {
1153 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1154 foreach ($photos as $photo) {
1156 foreach ($photo->attributes as $attribute) {
1157 $attr[$attribute->name] = trim($attribute->value);
1160 if (isset($attr["src"]) && isset($attr["width"])) {
1161 $avatar[$attr["width"]] = $attr["src"];
1164 // We don't have a width. So we just take everything that we got.
1165 // This is a Hubzilla workaround which doesn't send a width.
1166 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1167 $avatar[] = $attr["src"];
1172 if (sizeof($avatar)) {
1174 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1178 // Poll DFRN specific data
1179 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1180 if ($search->length > 0) {
1181 foreach ($search as $link) {
1182 //$data["request"] = $search->item(0)->nodeValue;
1184 foreach ($link->attributes as $attribute) {
1185 $attr[$attribute->name] = trim($attribute->value);
1188 $data[substr($attr["rel"], 5)] = $attr["href"];
1192 // Older Friendica versions had used the "uid" field differently than newer versions
1193 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1194 unset($data["guid"]);
1203 * @brief Check for Diaspora contact
1205 * @param array $webfinger Webfinger data
1207 * @return array Diaspora data
1208 * @throws HTTPException\InternalServerErrorException
1210 private static function diaspora($webfinger)
1214 // The array is reversed to take into account the order of preference for same-rel links
1215 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1216 foreach (array_reverse($webfinger["links"]) as $link) {
1217 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1218 $hcard_url = $link["href"];
1219 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1220 $data["baseurl"] = trim($link["href"], '/');
1221 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1222 $data["guid"] = $link["href"];
1223 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (defaults($link, "type", "") == "text/html") && !empty($link["href"])) {
1224 $data["url"] = $link["href"];
1225 } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
1226 $data["poll"] = $link["href"];
1227 } elseif (($link["rel"] == NAMESPACE_POCO) && !empty($link["href"])) {
1228 $data["poco"] = $link["href"];
1229 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1230 $data["notify"] = $link["href"];
1231 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1232 $data["pubkey"] = base64_decode($link["href"]);
1234 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1235 if (strstr($data["pubkey"], 'RSA ')) {
1236 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1241 if (!isset($data["url"]) || ($hcard_url == "")) {
1245 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1246 foreach ($webfinger["aliases"] as $alias) {
1247 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1248 $data["alias"] = $alias;
1249 } elseif (substr($alias, 0, 5) == 'acct:') {
1250 $data["addr"] = substr($alias, 5);
1255 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1256 $data["addr"] = substr($webfinger["subject"], 5);
1259 // Fetch further information from the hcard
1260 $data = self::pollHcard($hcard_url, $data);
1266 if (isset($data["url"])
1267 && isset($data["guid"])
1268 && isset($data["baseurl"])
1269 && isset($data["pubkey"])
1270 && ($hcard_url != "")
1272 $data["network"] = Protocol::DIASPORA;
1274 // The Diaspora handle must always be lowercase
1275 if (!empty($data["addr"])) {
1276 $data["addr"] = strtolower($data["addr"]);
1279 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1280 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1281 $data["batch"] = $data["baseurl"] . "/receive/public";
1290 * @brief Check for OStatus contact
1292 * @param array $webfinger Webfinger data
1293 * @param bool $short Short detection mode
1295 * @return array|bool OStatus data or "false" on error or "true" on short mode
1296 * @throws HTTPException\InternalServerErrorException
1298 private static function ostatus($webfinger, $short = false)
1302 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1303 foreach ($webfinger["aliases"] as $alias) {
1304 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1305 $data["addr"] = str_replace('acct:', '', $alias);
1310 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1311 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1313 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1316 if (is_array($webfinger["links"])) {
1317 // The array is reversed to take into account the order of preference for same-rel links
1318 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1319 foreach (array_reverse($webfinger["links"]) as $link) {
1320 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1321 && (defaults($link, "type", "") == "text/html")
1322 && ($link["href"] != "")
1324 $data["url"] = $link["href"];
1325 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1326 $data["notify"] = $link["href"];
1327 } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
1328 $data["poll"] = $link["href"];
1329 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1330 $pubkey = $link["href"];
1332 if (substr($pubkey, 0, 5) === 'data:') {
1333 if (strstr($pubkey, ',')) {
1334 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1336 $pubkey = substr($pubkey, 5);
1338 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1339 $curlResult = Network::curl($pubkey);
1340 if ($curlResult->isTimeout()) {
1341 self::$istimeout = true;
1344 $pubkey = $curlResult->getBody();
1347 $key = explode(".", $pubkey);
1349 if (sizeof($key) >= 3) {
1350 $m = Strings::base64UrlDecode($key[1]);
1351 $e = Strings::base64UrlDecode($key[2]);
1352 $data["pubkey"] = Crypto::meToPem($m, $e);
1358 if (isset($data["notify"]) && isset($data["pubkey"])
1359 && isset($data["poll"])
1360 && isset($data["url"])
1362 $data["network"] = Protocol::OSTATUS;
1371 // Fetch all additional data from the feed
1372 $curlResult = Network::curl($data["poll"]);
1373 if ($curlResult->isTimeout()) {
1374 self::$istimeout = true;
1377 $feed = $curlResult->getBody();
1381 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1386 if (!empty($feed_data["header"]["author-name"])) {
1387 $data["name"] = $feed_data["header"]["author-name"];
1389 if (!empty($feed_data["header"]["author-nick"])) {
1390 $data["nick"] = $feed_data["header"]["author-nick"];
1392 if (!empty($feed_data["header"]["author-avatar"])) {
1393 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1395 if (!empty($feed_data["header"]["author-id"])) {
1396 $data["alias"] = $feed_data["header"]["author-id"];
1398 if (!empty($feed_data["header"]["author-location"])) {
1399 $data["location"] = $feed_data["header"]["author-location"];
1401 if (!empty($feed_data["header"]["author-about"])) {
1402 $data["about"] = $feed_data["header"]["author-about"];
1404 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1405 // So we take the value that we just fetched, although the other one worked as well
1406 if (!empty($feed_data["header"]["author-link"])) {
1407 $data["url"] = $feed_data["header"]["author-link"];
1410 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1411 $data['url'] = $data["alias"];
1412 $data["alias"] = '';
1415 /// @todo Fetch location and "about" from the feed as well
1420 * @brief Fetch data from a pump.io profile page
1422 * @param string $profile_link Link to the profile page
1424 * @return array profile data
1426 private static function pumpioProfileData($profile_link)
1428 $doc = new DOMDocument();
1429 if (!@$doc->loadHTMLFile($profile_link)) {
1433 $xpath = new DomXPath($doc);
1437 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1439 if ($data["name"] == '') {
1440 // This is ugly - but pump.io doesn't seem to know a better way for it
1441 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1442 $pos = strpos($data["name"], chr(10));
1444 $data["name"] = trim(substr($data["name"], 0, $pos));
1448 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1450 if ($data["location"] == '') {
1451 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1454 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1456 if ($data["about"] == '') {
1457 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1460 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1462 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1465 foreach ($avatar->attributes as $attribute) {
1466 if ($attribute->name == "src") {
1467 $data["photo"] = trim($attribute->value);
1476 * @brief Check for pump.io contact
1478 * @param array $webfinger Webfinger data
1481 * @return array pump.io data
1483 private static function pumpio($webfinger, $addr)
1486 // The array is reversed to take into account the order of preference for same-rel links
1487 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1488 foreach (array_reverse($webfinger["links"]) as $link) {
1489 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1490 && (defaults($link, "type", "") == "text/html")
1491 && ($link["href"] != "")
1493 $data["url"] = $link["href"];
1494 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1495 $data["notify"] = $link["href"];
1496 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1497 $data["poll"] = $link["href"];
1498 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1499 $data["dialback"] = $link["href"];
1502 if (isset($data["poll"]) && isset($data["notify"])
1503 && isset($data["dialback"])
1504 && isset($data["url"])
1506 // by now we use these fields only for the network type detection
1507 // So we unset all data that isn't used at the moment
1508 unset($data["dialback"]);
1510 $data["network"] = Protocol::PUMPIO;
1515 $profile_data = self::pumpioProfileData($data["url"]);
1517 if (!$profile_data) {
1521 $data = array_merge($data, $profile_data);
1523 if (($addr != '') && ($data['name'] != '')) {
1524 $name = trim(str_replace($addr, '', $data['name']));
1526 $data['name'] = $name;
1534 * @brief Check page for feed link
1536 * @param string $url Page link
1538 * @return string feed link
1540 private static function getFeedLink($url)
1542 $doc = new DOMDocument();
1544 if (!@$doc->loadHTMLFile($url)) {
1548 $xpath = new DomXPath($doc);
1550 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1551 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1552 if (!is_object($feeds)) {
1556 if ($feeds->length == 0) {
1562 foreach ($feeds as $feed) {
1564 foreach ($feed->attributes as $attribute) {
1565 $attr[$attribute->name] = trim($attribute->value);
1568 if ($feed_url == "") {
1569 $feed_url = $attr["href"];
1577 * @brief Check for feed contact
1579 * @param string $url Profile link
1580 * @param boolean $probe Do a probe if the page contains a feed link
1582 * @return array feed data
1583 * @throws HTTPException\InternalServerErrorException
1585 private static function feed($url, $probe = true)
1587 $curlResult = Network::curl($url);
1588 if ($curlResult->isTimeout()) {
1589 self::$istimeout = true;
1592 $feed = $curlResult->getBody();
1593 $dummy1 = $dummy2 = $dummy3 = null;
1594 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1601 $feed_url = self::getFeedLink($url);
1607 return self::feed($feed_url, false);
1610 if (!empty($feed_data["header"]["author-name"])) {
1611 $data["name"] = $feed_data["header"]["author-name"];
1614 if (!empty($feed_data["header"]["author-nick"])) {
1615 $data["nick"] = $feed_data["header"]["author-nick"];
1618 if (!empty($feed_data["header"]["author-avatar"])) {
1619 $data["photo"] = $feed_data["header"]["author-avatar"];
1622 if (!empty($feed_data["header"]["author-id"])) {
1623 $data["alias"] = $feed_data["header"]["author-id"];
1626 $data["url"] = $url;
1627 $data["poll"] = $url;
1629 if (!empty($feed_data["header"]["author-link"])) {
1630 $data["baseurl"] = $feed_data["header"]["author-link"];
1632 $data["baseurl"] = $data["url"];
1635 $data["network"] = Protocol::FEED;
1641 * @brief Check for mail contact
1643 * @param string $uri Profile link
1644 * @param integer $uid User ID
1646 * @return array mail data
1647 * @throws \Exception
1649 private static function mail($uri, $uid)
1651 if (!Network::isEmailDomainValid($uri)) {
1659 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1661 $condition = ["`uid` = ? AND `server` != ''", $uid];
1662 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1663 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1665 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1669 $mailbox = Email::constructMailboxName($mailacct);
1671 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1672 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1677 $msgs = Email::poll($mbox, $uri);
1678 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1680 if (!count($msgs)) {
1684 $phost = substr($uri, strpos($uri, '@') + 1);
1687 $data["addr"] = $uri;
1688 $data["network"] = Protocol::MAIL;
1689 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1690 $data["nick"] = $data["name"];
1691 $data["photo"] = Network::lookupAvatarByEmail($uri);
1692 $data["url"] = 'mailto:'.$uri;
1693 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1694 $data["poll"] = 'email ' . Strings::getRandomHex();
1696 $x = Email::messageMeta($mbox, $msgs[0]);
1697 if (stristr($x[0]->from, $uri)) {
1698 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1699 } elseif (stristr($x[0]->to, $uri)) {
1700 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1703 foreach ($adr as $feadr) {
1704 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1705 &&(strcasecmp($feadr->host, $phost) == 0)
1706 && (strlen($feadr->personal))
1708 $personal = imap_mime_header_decode($feadr->personal);
1710 foreach ($personal as $perspart) {
1711 if ($perspart->charset != "default") {
1712 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1714 $data["name"] .= $perspart->text;
1718 $data["name"] = Strings::escapeTags($data["name"]);
1722 if (!empty($mbox)) {
1729 * @brief Mix two paths together to possibly fix missing parts
1731 * @param string $avatar Path to the avatar
1732 * @param string $base Another path that is hopefully complete
1734 * @return string fixed avatar path
1735 * @throws \Exception
1737 public static function fixAvatar($avatar, $base)
1739 $base_parts = parse_url($base);
1741 // Remove all parts that could create a problem
1742 unset($base_parts['path']);
1743 unset($base_parts['query']);
1744 unset($base_parts['fragment']);
1746 $avatar_parts = parse_url($avatar);
1749 $parts = array_merge($base_parts, $avatar_parts);
1751 // And put them together again
1752 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1753 $host = isset($parts['host']) ? $parts['host'] : '';
1754 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1755 $path = isset($parts['path']) ? $parts['path'] : '';
1756 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1757 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1759 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1761 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);