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)) {
356 Logger::notice('Time out detected. AP will not be probed.', ['url' => $url]);
359 if (!isset($data['url'])) {
363 if (!empty($data['photo'])) {
364 $data['baseurl'] = Network::getUrlMatch(Strings::normaliseLink(defaults($data, 'baseurl', '')), Strings::normaliseLink($data['photo']));
366 $data['photo'] = System::baseUrl() . '/images/person-300.jpg';
369 if (empty($data['name'])) {
370 if (!empty($data['nick'])) {
371 $data['name'] = $data['nick'];
374 if (empty($data['name'])) {
375 $data['name'] = $data['url'];
379 if (empty($data['nick'])) {
380 $data['nick'] = strtolower($data['name']);
382 if (strpos($data['nick'], ' ')) {
383 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
387 if (!empty(self::$baseurl)) {
388 $data['baseurl'] = self::$baseurl;
391 if (empty($data['network'])) {
392 $data['network'] = Protocol::PHANTOM;
395 $data = self::rearrangeData($data);
397 // Only store into the cache if the value seems to be valid
398 if (!in_array($data['network'], [Protocol::PHANTOM, Protocol::MAIL])) {
399 Cache::set('Probe::uri:' . $network . ':' . $uri, $data, Cache::DAY);
401 /// @todo temporary fix - we need a real contact update function that updates only changing fields
402 /// The biggest problem is the avatar picture that could have a reduced image size.
403 /// It should only be updated if the existing picture isn't existing anymore.
404 /// We only update the contact when it is no probing for a specific network.
405 if (($data['network'] != Protocol::FEED)
414 'name' => $data['name'],
415 'nick' => $data['nick'],
416 'url' => $data['url'],
417 'addr' => $data['addr'],
418 'photo' => $data['photo'],
419 'keywords' => $data['keywords'],
420 'location' => $data['location'],
421 'about' => $data['about'],
422 'notify' => $data['notify'],
423 'network' => $data['network'],
424 'server_url' => $data['baseurl']
427 // This doesn't cover the case when a community isn't a community anymore
428 if (!empty($data['community']) && $data['community']) {
429 $fields['community'] = $data['community'];
430 $fields['contact-type'] = Contact::TYPE_COMMUNITY;
435 foreach ($fields as $key => $val) {
437 unset($fields[$key]);
439 $fieldnames[] = $key;
443 $fields['updated'] = DateTimeFormat::utcNow();
445 $condition = ['nurl' => Strings::normaliseLink($data['url'])];
447 $old_fields = DBA::selectFirst('gcontact', $fieldnames, $condition);
449 // When the gcontact doesn't exist, the value "true" will trigger an insert.
450 // In difference to the public contacts we want to have every contact
451 // in the world in our global contacts.
455 // These values have to be set only on insert
456 $fields['photo'] = $data['photo'];
457 $fields['created'] = DateTimeFormat::utcNow();
460 DBA::update('gcontact', $fields, $condition, $old_fields);
463 'name' => $data['name'],
464 'nick' => $data['nick'],
465 'url' => $data['url'],
466 'addr' => $data['addr'],
467 'alias' => $data['alias'],
468 'keywords' => $data['keywords'],
469 'location' => $data['location'],
470 'about' => $data['about'],
471 'batch' => $data['batch'],
472 'notify' => $data['notify'],
473 'poll' => $data['poll'],
474 'request' => $data['request'],
475 'confirm' => $data['confirm'],
476 'poco' => $data['poco'],
477 'network' => $data['network'],
478 'pubkey' => $data['pubkey'],
479 'priority' => $data['priority'],
481 'rel' => Contact::SHARING
486 foreach ($fields as $key => $val) {
488 unset($fields[$key]);
490 $fieldnames[] = $key;
494 $condition = ['nurl' => Strings::normaliseLink($data['url']), 'self' => false, 'uid' => 0];
496 // "$old_fields" will return a "false" when the contact doesn't exist.
497 // This won't trigger an insert. This is intended, since we only need
498 // public contacts for everyone we store items from.
499 // We don't need to store every contact on the planet.
500 $old_fields = DBA::selectFirst('contact', $fieldnames, $condition);
502 $fields['name-date'] = DateTimeFormat::utcNow();
503 $fields['uri-date'] = DateTimeFormat::utcNow();
504 $fields['success_update'] = DateTimeFormat::utcNow();
506 DBA::update('contact', $fields, $condition, $old_fields);
514 * @brief Switch the scheme of an url between http and https
516 * @param string $url URL
518 * @return string switched URL
520 private static function switchScheme($url)
522 $parts = parse_url($url);
524 if (!isset($parts['scheme'])) {
528 if ($parts['scheme'] == 'http') {
529 $url = str_replace('http://', 'https://', $url);
530 } elseif ($parts['scheme'] == 'https') {
531 $url = str_replace('https://', 'http://', $url);
538 * @brief Checks if a profile url should be OStatus but only provides partial information
540 * @param array $webfinger Webfinger data
541 * @param string $lrdd Path template for webfinger request
542 * @param string $type type
544 * @return array fixed webfinger data
545 * @throws HTTPException\InternalServerErrorException
547 private static function fixOStatus($webfinger, $lrdd, $type)
549 if (empty($webfinger['links']) || empty($webfinger['subject'])) {
556 foreach ($webfinger['links'] as $link) {
557 if ($link['rel'] == NAMESPACE_OSTATUSSUB) {
560 if ($link['rel'] == 'magic-public-key') {
565 if (!$is_ostatus || $has_key) {
569 $url = self::switchScheme($webfinger['subject']);
570 $path = str_replace('{uri}', urlencode($url), $lrdd);
571 $webfinger2 = self::webfinger($path, $type);
573 // Is the new webfinger detectable as OStatus?
574 if (self::ostatus($webfinger2, true)) {
575 $webfinger = $webfinger2;
582 * @brief Fetch information (protocol endpoints and user information) about a given uri
584 * This function is only called by the "uri" function that adds caching and rearranging of data.
586 * @param string $uri Address that should be probed
587 * @param string $network Test for this specific network
588 * @param integer $uid User ID for the probe (only used for mails)
590 * @return array uri data
591 * @throws HTTPException\InternalServerErrorException
593 private static function detect($uri, $network, $uid)
595 $parts = parse_url($uri);
597 if (!empty($parts["scheme"]) && !empty($parts["host"])) {
598 $host = $parts["host"];
599 if (!empty($parts["port"])) {
600 $host .= ':'.$parts["port"];
603 if ($host == 'twitter.com') {
604 return ["network" => Protocol::TWITTER];
606 $lrdd = self::hostMeta($host);
608 if (is_bool($lrdd)) {
612 $path_parts = explode("/", trim(defaults($parts, 'path', ''), "/"));
614 while (!$lrdd && (sizeof($path_parts) > 1)) {
615 $host .= "/".array_shift($path_parts);
616 $lrdd = self::hostMeta($host);
619 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
620 return self::feed($uri);
622 $nick = array_pop($path_parts);
624 // Mastodon uses a "@" as prefix for usernames in their url format
625 $nick = ltrim($nick, '@');
627 $addr = $nick."@".$host;
628 } elseif (strstr($uri, '@')) {
629 // If the URI starts with "mailto:" then jump directly to the mail detection
630 if (strpos($uri, 'mailto:') !== false) {
631 $uri = str_replace('mailto:', '', $uri);
632 return self::mail($uri, $uid);
635 if ($network == Protocol::MAIL) {
636 return self::mail($uri, $uid);
638 // Remove "acct:" from the URI
639 $uri = str_replace('acct:', '', $uri);
641 $host = substr($uri, strpos($uri, '@') + 1);
642 $nick = substr($uri, 0, strpos($uri, '@'));
644 if (strpos($uri, '@twitter.com')) {
645 return ["network" => Protocol::TWITTER];
647 $lrdd = self::hostMeta($host);
649 if (is_bool($lrdd)) {
654 Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
655 return self::mail($uri, $uid);
659 Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
665 /// @todo Do we need the prefix "acct:" or "acct://"?
667 foreach ($lrdd as $type => $template) {
672 // At first try it with the given uri
673 $path = str_replace('{uri}', urlencode($uri), $template);
674 $webfinger = self::webfinger($path, $type);
676 // Fix possible problems with GNU Social probing to wrong scheme
677 $webfinger = self::fixOStatus($webfinger, $template, $type);
679 // We cannot be sure that the detected address was correct, so we don't use the values
680 if ($webfinger && ($uri != $addr)) {
685 // Try webfinger with the address (user@domain.tld)
687 $path = str_replace('{uri}', urlencode($addr), $template);
688 $webfinger = self::webfinger($path, $type);
691 // Mastodon needs to have it with "acct:"
693 $path = str_replace('{uri}', urlencode("acct:".$addr), $template);
694 $webfinger = self::webfinger($path, $type);
699 return self::feed($uri);
704 Logger::log("Probing ".$uri, Logger::DEBUG);
706 if (in_array($network, ["", Protocol::DFRN])) {
707 $result = self::dfrn($webfinger);
709 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
710 $result = self::diaspora($webfinger);
712 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
713 $result = self::ostatus($webfinger);
715 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
716 $result = self::pumpio($webfinger, $addr);
718 if ((!$result && ($network == "")) || ($network == Protocol::FEED)) {
719 $result = self::feed($uri);
721 // We overwrite the detected nick with our try if the previois routines hadn't detected it.
722 // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
723 if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
724 $result["nick"] = $nick;
727 if (empty($result["addr"]) && ($addr != "")) {
728 $result["addr"] = $addr;
732 if (empty($result["network"])) {
733 $result["network"] = Protocol::PHANTOM;
736 if (empty($result["url"])) {
737 $result["url"] = $uri;
740 Logger::log($uri." is ".$result["network"], Logger::DEBUG);
742 if (empty($result["baseurl"])) {
743 $pos = strpos($result["url"], $host);
745 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
752 * @brief Perform a webfinger request.
754 * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
756 * @param string $url Address that should be probed
757 * @param string $type type
759 * @return array webfinger data
760 * @throws HTTPException\InternalServerErrorException
762 private static function webfinger($url, $type)
764 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
767 $curlResult = Network::curl($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
768 if ($curlResult->isTimeout()) {
769 self::$istimeout = true;
772 $data = $curlResult->getBody();
774 $webfinger = json_decode($data, true);
775 if (is_array($webfinger)) {
776 if (!isset($webfinger["links"])) {
777 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
783 // If it is not JSON, maybe it is XML
784 $xrd = XML::parseString($data, false);
785 if (!is_object($xrd)) {
786 Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
790 $xrd_arr = XML::elementToArray($xrd);
791 if (!isset($xrd_arr["xrd"]["link"])) {
792 Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
798 if (!empty($xrd_arr["xrd"]["subject"])) {
799 $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
802 if (!empty($xrd_arr["xrd"]["alias"])) {
803 $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
806 $webfinger["links"] = [];
808 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
809 if (!empty($data["@attributes"])) {
810 $attributes = $data["@attributes"];
811 } elseif ($value == "@attributes") {
817 $webfinger["links"][] = $attributes;
823 * @brief Poll the Friendica specific noscrape page.
825 * "noscrape" is a faster alternative to fetch the data from the hcard.
826 * This functionality was originally created for the directory.
828 * @param string $noscrape_url Link to the noscrape page
829 * @param array $data The already fetched data
831 * @return array noscrape data
832 * @throws HTTPException\InternalServerErrorException
834 private static function pollNoscrape($noscrape_url, $data)
836 $curlResult = Network::curl($noscrape_url);
837 if ($curlResult->isTimeout()) {
838 self::$istimeout = true;
841 $content = $curlResult->getBody();
843 Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
847 $json = json_decode($content, true);
848 if (!is_array($json)) {
849 Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
853 if (!empty($json["fn"])) {
854 $data["name"] = $json["fn"];
857 if (!empty($json["addr"])) {
858 $data["addr"] = $json["addr"];
861 if (!empty($json["nick"])) {
862 $data["nick"] = $json["nick"];
865 if (!empty($json["guid"])) {
866 $data["guid"] = $json["guid"];
869 if (!empty($json["comm"])) {
870 $data["community"] = $json["comm"];
873 if (!empty($json["tags"])) {
874 $keywords = implode(" ", $json["tags"]);
875 if ($keywords != "") {
876 $data["keywords"] = $keywords;
880 $location = Profile::formatLocation($json);
882 $data["location"] = $location;
885 if (!empty($json["about"])) {
886 $data["about"] = $json["about"];
889 if (!empty($json["key"])) {
890 $data["pubkey"] = $json["key"];
893 if (!empty($json["photo"])) {
894 $data["photo"] = $json["photo"];
897 if (!empty($json["dfrn-request"])) {
898 $data["request"] = $json["dfrn-request"];
901 if (!empty($json["dfrn-confirm"])) {
902 $data["confirm"] = $json["dfrn-confirm"];
905 if (!empty($json["dfrn-notify"])) {
906 $data["notify"] = $json["dfrn-notify"];
909 if (!empty($json["dfrn-poll"])) {
910 $data["poll"] = $json["dfrn-poll"];
917 * @brief Check for valid DFRN data
919 * @param array $data DFRN data
921 * @return int Number of errors
923 public static function validDfrn($data)
926 if (!isset($data['key'])) {
929 if (!isset($data['dfrn-request'])) {
932 if (!isset($data['dfrn-confirm'])) {
935 if (!isset($data['dfrn-notify'])) {
938 if (!isset($data['dfrn-poll'])) {
945 * @brief Fetch data from a DFRN profile page and via "noscrape"
947 * @param string $profile_link Link to the profile page
949 * @return array profile data
950 * @throws HTTPException\InternalServerErrorException
951 * @throws \ImagickException
953 public static function profile($profile_link)
957 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
959 // Fetch data via noscrape - this is faster
960 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
961 $data = self::pollNoscrape($noscrape_url, $data);
963 if (!isset($data["notify"])
964 || !isset($data["confirm"])
965 || !isset($data["request"])
966 || !isset($data["poll"])
967 || !isset($data["name"])
968 || !isset($data["photo"])
970 $data = self::pollHcard($profile_link, $data, true);
975 if (empty($data["addr"]) || empty($data["nick"])) {
976 $probe_data = self::uri($profile_link);
977 $data["addr"] = defaults($data, "addr", $probe_data["addr"]);
978 $data["nick"] = defaults($data, "nick", $probe_data["nick"]);
981 $prof_data["addr"] = $data["addr"];
982 $prof_data["nick"] = $data["nick"];
983 $prof_data["dfrn-request"] = defaults($data, 'request', null);
984 $prof_data["dfrn-confirm"] = defaults($data, 'confirm', null);
985 $prof_data["dfrn-notify"] = defaults($data, 'notify' , null);
986 $prof_data["dfrn-poll"] = defaults($data, 'poll' , null);
987 $prof_data["photo"] = defaults($data, 'photo' , null);
988 $prof_data["fn"] = defaults($data, 'name' , null);
989 $prof_data["key"] = defaults($data, 'pubkey' , null);
991 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
997 * @brief Check for DFRN contact
999 * @param array $webfinger Webfinger data
1001 * @return array DFRN data
1002 * @throws HTTPException\InternalServerErrorException
1004 private static function dfrn($webfinger)
1008 // The array is reversed to take into account the order of preference for same-rel links
1009 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1010 foreach (array_reverse($webfinger["links"]) as $link) {
1011 if (($link["rel"] == NAMESPACE_DFRN) && !empty($link["href"])) {
1012 $data["network"] = Protocol::DFRN;
1013 } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
1014 $data["poll"] = $link["href"];
1015 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (defaults($link, "type", "") == "text/html") && !empty($link["href"])) {
1016 $data["url"] = $link["href"];
1017 } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1018 $hcard_url = $link["href"];
1019 } elseif (($link["rel"] == NAMESPACE_POCO) && !empty($link["href"])) {
1020 $data["poco"] = $link["href"];
1021 } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1022 $data["photo"] = $link["href"];
1023 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1024 $data["baseurl"] = trim($link["href"], '/');
1025 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1026 $data["guid"] = $link["href"];
1027 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1028 $data["pubkey"] = base64_decode($link["href"]);
1030 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1031 if (strstr($data["pubkey"], 'RSA ')) {
1032 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1037 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1038 foreach ($webfinger["aliases"] as $alias) {
1039 if (empty($data["url"]) && !strstr($alias, "@")) {
1040 $data["url"] = $alias;
1041 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1042 $data["alias"] = $alias;
1043 } elseif (substr($alias, 0, 5) == 'acct:') {
1044 $data["addr"] = substr($alias, 5);
1049 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1050 $data["addr"] = substr($webfinger["subject"], 5);
1053 if (!isset($data["network"]) || ($hcard_url == "")) {
1057 // Fetch data via noscrape - this is faster
1058 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1059 $data = self::pollNoscrape($noscrape_url, $data);
1061 if (isset($data["notify"])
1062 && isset($data["confirm"])
1063 && isset($data["request"])
1064 && isset($data["poll"])
1065 && isset($data["name"])
1066 && isset($data["photo"])
1071 $data = self::pollHcard($hcard_url, $data, true);
1077 * @brief Poll the hcard page (Diaspora and Friendica specific)
1079 * @param string $hcard_url Link to the hcard page
1080 * @param array $data The already fetched data
1081 * @param boolean $dfrn Poll DFRN specific data
1083 * @return array hcard data
1084 * @throws HTTPException\InternalServerErrorException
1086 private static function pollHcard($hcard_url, $data, $dfrn = false)
1088 $curlResult = Network::curl($hcard_url);
1089 if ($curlResult->isTimeout()) {
1090 self::$istimeout = true;
1093 $content = $curlResult->getBody();
1098 $doc = new DOMDocument();
1099 if (!@$doc->loadHTML($content)) {
1103 $xpath = new DomXPath($doc);
1105 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1106 if (!is_object($vcards)) {
1110 if (!isset($data["baseurl"])) {
1111 $data["baseurl"] = "";
1114 if ($vcards->length > 0) {
1115 $vcard = $vcards->item(0);
1117 // We have to discard the guid from the hcard in favour of the guid from lrdd
1118 // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1119 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1120 if (($search->length > 0) && empty($data["guid"])) {
1121 $data["guid"] = $search->item(0)->nodeValue;
1124 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1125 if ($search->length > 0) {
1126 $data["nick"] = $search->item(0)->nodeValue;
1129 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1130 if ($search->length > 0) {
1131 $data["name"] = $search->item(0)->nodeValue;
1134 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1135 if ($search->length > 0) {
1136 $data["searchable"] = $search->item(0)->nodeValue;
1139 $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1140 if ($search->length > 0) {
1141 $data["pubkey"] = $search->item(0)->nodeValue;
1142 if (strstr($data["pubkey"], 'RSA ')) {
1143 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1147 $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1148 if ($search->length > 0) {
1149 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1154 if (!empty($vcard)) {
1155 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1156 foreach ($photos as $photo) {
1158 foreach ($photo->attributes as $attribute) {
1159 $attr[$attribute->name] = trim($attribute->value);
1162 if (isset($attr["src"]) && isset($attr["width"])) {
1163 $avatar[$attr["width"]] = $attr["src"];
1166 // We don't have a width. So we just take everything that we got.
1167 // This is a Hubzilla workaround which doesn't send a width.
1168 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1169 $avatar[] = $attr["src"];
1174 if (sizeof($avatar)) {
1176 $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1180 // Poll DFRN specific data
1181 $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1182 if ($search->length > 0) {
1183 foreach ($search as $link) {
1184 //$data["request"] = $search->item(0)->nodeValue;
1186 foreach ($link->attributes as $attribute) {
1187 $attr[$attribute->name] = trim($attribute->value);
1190 $data[substr($attr["rel"], 5)] = $attr["href"];
1194 // Older Friendica versions had used the "uid" field differently than newer versions
1195 if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1196 unset($data["guid"]);
1205 * @brief Check for Diaspora contact
1207 * @param array $webfinger Webfinger data
1209 * @return array Diaspora data
1210 * @throws HTTPException\InternalServerErrorException
1212 private static function diaspora($webfinger)
1216 // The array is reversed to take into account the order of preference for same-rel links
1217 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1218 foreach (array_reverse($webfinger["links"]) as $link) {
1219 if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1220 $hcard_url = $link["href"];
1221 } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1222 $data["baseurl"] = trim($link["href"], '/');
1223 } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1224 $data["guid"] = $link["href"];
1225 } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (defaults($link, "type", "") == "text/html") && !empty($link["href"])) {
1226 $data["url"] = $link["href"];
1227 } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
1228 $data["poll"] = $link["href"];
1229 } elseif (($link["rel"] == NAMESPACE_POCO) && !empty($link["href"])) {
1230 $data["poco"] = $link["href"];
1231 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1232 $data["notify"] = $link["href"];
1233 } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1234 $data["pubkey"] = base64_decode($link["href"]);
1236 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1237 if (strstr($data["pubkey"], 'RSA ')) {
1238 $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1243 if (!isset($data["url"]) || ($hcard_url == "")) {
1247 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1248 foreach ($webfinger["aliases"] as $alias) {
1249 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1250 $data["alias"] = $alias;
1251 } elseif (substr($alias, 0, 5) == 'acct:') {
1252 $data["addr"] = substr($alias, 5);
1257 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1258 $data["addr"] = substr($webfinger["subject"], 5);
1261 // Fetch further information from the hcard
1262 $data = self::pollHcard($hcard_url, $data);
1268 if (isset($data["url"])
1269 && isset($data["guid"])
1270 && isset($data["baseurl"])
1271 && isset($data["pubkey"])
1272 && ($hcard_url != "")
1274 $data["network"] = Protocol::DIASPORA;
1276 // The Diaspora handle must always be lowercase
1277 if (!empty($data["addr"])) {
1278 $data["addr"] = strtolower($data["addr"]);
1281 // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1282 $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1283 $data["batch"] = $data["baseurl"] . "/receive/public";
1292 * @brief Check for OStatus contact
1294 * @param array $webfinger Webfinger data
1295 * @param bool $short Short detection mode
1297 * @return array|bool OStatus data or "false" on error or "true" on short mode
1298 * @throws HTTPException\InternalServerErrorException
1300 private static function ostatus($webfinger, $short = false)
1304 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1305 foreach ($webfinger["aliases"] as $alias) {
1306 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1307 $data["addr"] = str_replace('acct:', '', $alias);
1312 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1313 && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1315 $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1318 if (is_array($webfinger["links"])) {
1319 // The array is reversed to take into account the order of preference for same-rel links
1320 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1321 foreach (array_reverse($webfinger["links"]) as $link) {
1322 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1323 && (defaults($link, "type", "") == "text/html")
1324 && ($link["href"] != "")
1326 $data["url"] = $link["href"];
1327 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1328 $data["notify"] = $link["href"];
1329 } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) {
1330 $data["poll"] = $link["href"];
1331 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1332 $pubkey = $link["href"];
1334 if (substr($pubkey, 0, 5) === 'data:') {
1335 if (strstr($pubkey, ',')) {
1336 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1338 $pubkey = substr($pubkey, 5);
1340 } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1341 $curlResult = Network::curl($pubkey);
1342 if ($curlResult->isTimeout()) {
1343 self::$istimeout = true;
1346 $pubkey = $curlResult->getBody();
1349 $key = explode(".", $pubkey);
1351 if (sizeof($key) >= 3) {
1352 $m = Strings::base64UrlDecode($key[1]);
1353 $e = Strings::base64UrlDecode($key[2]);
1354 $data["pubkey"] = Crypto::meToPem($m, $e);
1360 if (isset($data["notify"]) && isset($data["pubkey"])
1361 && isset($data["poll"])
1362 && isset($data["url"])
1364 $data["network"] = Protocol::OSTATUS;
1373 // Fetch all additional data from the feed
1374 $curlResult = Network::curl($data["poll"]);
1375 if ($curlResult->isTimeout()) {
1376 self::$istimeout = true;
1379 $feed = $curlResult->getBody();
1383 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1388 if (!empty($feed_data["header"]["author-name"])) {
1389 $data["name"] = $feed_data["header"]["author-name"];
1391 if (!empty($feed_data["header"]["author-nick"])) {
1392 $data["nick"] = $feed_data["header"]["author-nick"];
1394 if (!empty($feed_data["header"]["author-avatar"])) {
1395 $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1397 if (!empty($feed_data["header"]["author-id"])) {
1398 $data["alias"] = $feed_data["header"]["author-id"];
1400 if (!empty($feed_data["header"]["author-location"])) {
1401 $data["location"] = $feed_data["header"]["author-location"];
1403 if (!empty($feed_data["header"]["author-about"])) {
1404 $data["about"] = $feed_data["header"]["author-about"];
1406 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1407 // So we take the value that we just fetched, although the other one worked as well
1408 if (!empty($feed_data["header"]["author-link"])) {
1409 $data["url"] = $feed_data["header"]["author-link"];
1412 if (($data['poll'] == $data['url']) && ($data["alias"] != '')) {
1413 $data['url'] = $data["alias"];
1414 $data["alias"] = '';
1417 /// @todo Fetch location and "about" from the feed as well
1422 * @brief Fetch data from a pump.io profile page
1424 * @param string $profile_link Link to the profile page
1426 * @return array profile data
1428 private static function pumpioProfileData($profile_link)
1430 $doc = new DOMDocument();
1431 if (!@$doc->loadHTMLFile($profile_link)) {
1435 $xpath = new DomXPath($doc);
1439 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1441 if ($data["name"] == '') {
1442 // This is ugly - but pump.io doesn't seem to know a better way for it
1443 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1444 $pos = strpos($data["name"], chr(10));
1446 $data["name"] = trim(substr($data["name"], 0, $pos));
1450 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1452 if ($data["location"] == '') {
1453 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1456 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1458 if ($data["about"] == '') {
1459 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1462 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1464 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1467 foreach ($avatar->attributes as $attribute) {
1468 if ($attribute->name == "src") {
1469 $data["photo"] = trim($attribute->value);
1478 * @brief Check for pump.io contact
1480 * @param array $webfinger Webfinger data
1483 * @return array pump.io data
1485 private static function pumpio($webfinger, $addr)
1488 // The array is reversed to take into account the order of preference for same-rel links
1489 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1490 foreach (array_reverse($webfinger["links"]) as $link) {
1491 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1492 && (defaults($link, "type", "") == "text/html")
1493 && ($link["href"] != "")
1495 $data["url"] = $link["href"];
1496 } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1497 $data["notify"] = $link["href"];
1498 } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1499 $data["poll"] = $link["href"];
1500 } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1501 $data["dialback"] = $link["href"];
1504 if (isset($data["poll"]) && isset($data["notify"])
1505 && isset($data["dialback"])
1506 && isset($data["url"])
1508 // by now we use these fields only for the network type detection
1509 // So we unset all data that isn't used at the moment
1510 unset($data["dialback"]);
1512 $data["network"] = Protocol::PUMPIO;
1517 $profile_data = self::pumpioProfileData($data["url"]);
1519 if (!$profile_data) {
1523 $data = array_merge($data, $profile_data);
1525 if (($addr != '') && ($data['name'] != '')) {
1526 $name = trim(str_replace($addr, '', $data['name']));
1528 $data['name'] = $name;
1536 * @brief Check page for feed link
1538 * @param string $url Page link
1540 * @return string feed link
1542 private static function getFeedLink($url)
1544 $doc = new DOMDocument();
1546 if (!@$doc->loadHTMLFile($url)) {
1550 $xpath = new DomXPath($doc);
1552 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1553 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1554 if (!is_object($feeds)) {
1558 if ($feeds->length == 0) {
1564 foreach ($feeds as $feed) {
1566 foreach ($feed->attributes as $attribute) {
1567 $attr[$attribute->name] = trim($attribute->value);
1570 if ($feed_url == "") {
1571 $feed_url = $attr["href"];
1579 * @brief Check for feed contact
1581 * @param string $url Profile link
1582 * @param boolean $probe Do a probe if the page contains a feed link
1584 * @return array feed data
1585 * @throws HTTPException\InternalServerErrorException
1587 private static function feed($url, $probe = true)
1589 $curlResult = Network::curl($url);
1590 if ($curlResult->isTimeout()) {
1591 self::$istimeout = true;
1594 $feed = $curlResult->getBody();
1595 $dummy1 = $dummy2 = $dummy3 = null;
1596 $feed_data = Feed::import($feed, $dummy1, $dummy2, $dummy3, true);
1603 $feed_url = self::getFeedLink($url);
1609 return self::feed($feed_url, false);
1612 if (!empty($feed_data["header"]["author-name"])) {
1613 $data["name"] = $feed_data["header"]["author-name"];
1616 if (!empty($feed_data["header"]["author-nick"])) {
1617 $data["nick"] = $feed_data["header"]["author-nick"];
1620 if (!empty($feed_data["header"]["author-avatar"])) {
1621 $data["photo"] = $feed_data["header"]["author-avatar"];
1624 if (!empty($feed_data["header"]["author-id"])) {
1625 $data["alias"] = $feed_data["header"]["author-id"];
1628 $data["url"] = $url;
1629 $data["poll"] = $url;
1631 if (!empty($feed_data["header"]["author-link"])) {
1632 $data["baseurl"] = $feed_data["header"]["author-link"];
1634 $data["baseurl"] = $data["url"];
1637 $data["network"] = Protocol::FEED;
1643 * @brief Check for mail contact
1645 * @param string $uri Profile link
1646 * @param integer $uid User ID
1648 * @return array mail data
1649 * @throws \Exception
1651 private static function mail($uri, $uid)
1653 if (!Network::isEmailDomainValid($uri)) {
1661 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1663 $condition = ["`uid` = ? AND `server` != ''", $uid];
1664 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1665 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1667 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1671 $mailbox = Email::constructMailboxName($mailacct);
1673 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1674 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1679 $msgs = Email::poll($mbox, $uri);
1680 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1682 if (!count($msgs)) {
1686 $phost = substr($uri, strpos($uri, '@') + 1);
1689 $data["addr"] = $uri;
1690 $data["network"] = Protocol::MAIL;
1691 $data["name"] = substr($uri, 0, strpos($uri, '@'));
1692 $data["nick"] = $data["name"];
1693 $data["photo"] = Network::lookupAvatarByEmail($uri);
1694 $data["url"] = 'mailto:'.$uri;
1695 $data["notify"] = 'smtp ' . Strings::getRandomHex();
1696 $data["poll"] = 'email ' . Strings::getRandomHex();
1698 $x = Email::messageMeta($mbox, $msgs[0]);
1699 if (stristr($x[0]->from, $uri)) {
1700 $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1701 } elseif (stristr($x[0]->to, $uri)) {
1702 $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1705 foreach ($adr as $feadr) {
1706 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1707 &&(strcasecmp($feadr->host, $phost) == 0)
1708 && (strlen($feadr->personal))
1710 $personal = imap_mime_header_decode($feadr->personal);
1712 foreach ($personal as $perspart) {
1713 if ($perspart->charset != "default") {
1714 $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1716 $data["name"] .= $perspart->text;
1720 $data["name"] = Strings::escapeTags($data["name"]);
1724 if (!empty($mbox)) {
1731 * @brief Mix two paths together to possibly fix missing parts
1733 * @param string $avatar Path to the avatar
1734 * @param string $base Another path that is hopefully complete
1736 * @return string fixed avatar path
1737 * @throws \Exception
1739 public static function fixAvatar($avatar, $base)
1741 $base_parts = parse_url($base);
1743 // Remove all parts that could create a problem
1744 unset($base_parts['path']);
1745 unset($base_parts['query']);
1746 unset($base_parts['fragment']);
1748 $avatar_parts = parse_url($avatar);
1751 $parts = array_merge($base_parts, $avatar_parts);
1753 // And put them together again
1754 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
1755 $host = isset($parts['host']) ? $parts['host'] : '';
1756 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
1757 $path = isset($parts['path']) ? $parts['path'] : '';
1758 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
1759 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1761 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1763 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);