]> git.mxchange.org Git - friendica.git/blob - src/Network/Probe.php
Merge pull request #3457 from annando/1705-probe
[friendica.git] / src / Network / Probe.php
1 <?php
2
3 namespace Friendica\Network;
4
5 /**
6  * @file src/Network/Probe.php
7  * @brief Functions for probing URL
8  *
9  */
10
11 use Friendica\App;
12 use Friendica\Core\Config;
13
14 require_once 'include/feed.php';
15 require_once 'include/email.php';
16 require_once 'include/network.php';
17
18 /**
19  * @brief This class contain functions for probing URL
20  *
21  */
22 class Probe {
23
24         private static $baseurl;
25
26         /**
27          * @brief Rearrange the array so that it always has the same order
28          *
29          * @param array $data Unordered data
30          *
31          * @return array Ordered data
32          */
33         private function rearrangeData($data) {
34                 $fields = array("name", "nick", "guid", "url", "addr", "alias",
35                                 "photo", "community", "keywords", "location", "about",
36                                 "batch", "notify", "poll", "request", "confirm", "poco",
37                                 "priority", "network", "pubkey", "baseurl");
38
39                 $newdata = array();
40                 foreach ($fields as $field) {
41                         if (isset($data[$field])) {
42                                 $newdata[$field] = $data[$field];
43                         } else {
44                                 $newdata[$field] = "";
45                         }
46                 }
47
48                 // We don't use the "priority" field anymore and replace it with a dummy.
49                 $newdata["priority"] = 0;
50
51                 return $newdata;
52         }
53
54         /**
55          * @brief Probes for XRD data
56          *
57          * @param string $host The host part of an url
58          *
59          * @return array
60          *      'lrdd' => Link to LRDD endpoint
61          *      'lrdd-xml' => Link to LRDD endpoint in XML format
62          *      'lrdd-json' => Link to LRDD endpoint in JSON format
63          */
64         private function xrd($host) {
65
66                 // Reset the static variable
67                 self::$baseurl = '';
68
69                 $ssl_url = "https://".$host."/.well-known/host-meta";
70                 $url = "http://".$host."/.well-known/host-meta";
71
72                 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
73                 $redirects = 0;
74
75                 $ret = z_fetch_url($ssl_url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
76                 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
77                         return false;
78                 }
79                 $xml = $ret['body'];
80
81                 $xrd = parse_xml_string($xml, false);
82
83                 if (!is_object($xrd)) {
84                         $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
85                         if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
86                                 return false;
87                         }
88                         $xml = $ret['body'];
89                         $xrd = parse_xml_string($xml, false);
90                 }
91                 if (!is_object($xrd)) {
92                         return false;
93                 }
94
95                 $links = \xml::element_to_array($xrd);
96                 if (!isset($links["xrd"]["link"])) {
97                         return false;
98                 }
99
100                 $xrd_data = array();
101
102                 foreach ($links["xrd"]["link"] as $value => $link) {
103                         if (isset($link["@attributes"])) {
104                                 $attributes = $link["@attributes"];
105                         } elseif ($value == "@attributes") {
106                                 $attributes = $link;
107                         } else {
108                                 continue;
109                         }
110
111                         if (($attributes["rel"] == "lrdd")
112                                 AND ($attributes["type"] == "application/xrd+xml")
113                         ) {
114                                 $xrd_data["lrdd-xml"] = $attributes["template"];
115                         } elseif (($attributes["rel"] == "lrdd")
116                                 AND ($attributes["type"] == "application/json")
117                         ) {
118                                 $xrd_data["lrdd-json"] = $attributes["template"];
119                         } elseif ($attributes["rel"] == "lrdd") {
120                                 $xrd_data["lrdd"] = $attributes["template"];
121                         }
122                 }
123
124                 self::$baseurl = "http://".$host;
125
126                 return $xrd_data;
127         }
128
129         /**
130          * @brief Perform Webfinger lookup and return DFRN data
131          *
132          * Given an email style address, perform webfinger lookup and
133          * return the resulting DFRN profile URL, or if no DFRN profile URL
134          * is located, returns an OStatus subscription template (prefixed
135          * with the string 'stat:' to identify it as on OStatus template).
136          * If this isn't an email style address just return $webbie.
137          * Return an empty string if email-style addresses but webfinger fails,
138          * or if the resultant personal XRD doesn't contain a supported
139          * subscription/friend-request attribute.
140          *
141          * amended 7/9/2011 to return an hcard which could save potentially loading
142          * a lengthy content page to scrape dfrn attributes
143          *
144          * @param string $webbie Address that should be probed
145          * @param string $hcard_url Link to the hcard - is returned by reference
146          *
147          * @return string profile link
148          */
149
150         public static function webfingerDfrn($webbie, &$hcard_url) {
151
152                 $profile_link = '';
153
154                 $links = self::lrdd($webbie);
155                 logger('webfingerDfrn: '.$webbie.':'.print_r($links, true), LOGGER_DATA);
156                 if (count($links)) {
157                         foreach ($links as $link) {
158                                 if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
159                                         $profile_link = $link['@attributes']['href'];
160                                 }
161                                 if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) AND ($profile_link == "")) {
162                                         $profile_link = 'stat:'.$link['@attributes']['template'];
163                                 }
164                                 if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') {
165                                         $hcard_url = $link['@attributes']['href'];
166                                 }
167                         }
168                 }
169                 return $profile_link;
170         }
171
172         /**
173          * @brief Check an URI for LRDD data
174          *
175          * this is a replacement for the "lrdd" function in include/network.php.
176          * It isn't used in this class and has some redundancies in the code.
177          * When time comes we can check the existing calls for "lrdd" if we can rework them.
178          *
179          * @param string $uri Address that should be probed
180          *
181          * @return array uri data
182          */
183         public static function lrdd($uri) {
184
185                 $lrdd = self::xrd($uri);
186                 $webfinger = null;
187
188                 if (!$lrdd) {
189                         $parts = @parse_url($uri);
190                         if (!$parts) {
191                                 return array();
192                         }
193
194                         $host = $parts["host"];
195                         if (isset($parts["port"])) {
196                                 $host .= ':'.$parts["port"];
197                         }
198
199                         $path_parts = explode("/", trim($parts["path"], "/"));
200
201                         $nick = array_pop($path_parts);
202
203                         do {
204                                 $lrdd = self::xrd($host);
205                                 $host .= "/".array_shift($path_parts);
206                         } while (!$lrdd AND (sizeof($path_parts) > 0));
207                 }
208
209                 if (!$lrdd) {
210                         return array();
211                 }
212
213                 foreach ($lrdd as $key => $link) {
214                         if ($webfinger) {
215                                 continue;
216                         }
217
218                         if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
219                                 continue;
220                         }
221
222                         $path = str_replace('{uri}', urlencode($uri), $link);
223                         $webfinger = self::webfinger($path);
224
225                         if (!$webfinger AND (strstr($uri, "@"))) {
226                                 $path = str_replace('{uri}', urlencode("acct:".$uri), $link);
227                                 $webfinger = self::webfinger($path);
228                         }
229
230                         // Special treatment for Mastodon
231                         // Problem is that Mastodon uses an URL format like http://domain.tld/@nick
232                         // But the webfinger for this format fails.
233                         if (!$webfinger AND isset($nick)) {
234                                 // Mastodon uses a "@" as prefix for usernames in their url format
235                                 $nick = ltrim($nick, '@');
236
237                                 $addr = $nick."@".$host;
238
239                                 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
240                                 $webfinger = self::webfinger($path);
241                         }
242                 }
243
244                 if (!is_array($webfinger["links"])) {
245                         return false;
246                 }
247
248                 $data = array();
249
250                 foreach ($webfinger["links"] as $link) {
251                         $data[] = array("@attributes" => $link);
252                 }
253
254                 if (is_array($webfinger["aliases"])) {
255                         foreach ($webfinger["aliases"] as $alias) {
256                                 $data[] = array("@attributes" =>
257                                                         array("rel" => "alias",
258                                                                 "href" => $alias));
259                         }
260                 }
261
262                 return $data;
263         }
264
265         /**
266          * @brief Fetch information (protocol endpoints and user information) about a given uri
267          *
268          * @param string $uri Address that should be probed
269          * @param string $network Test for this specific network
270          * @param integer $uid User ID for the probe (only used for mails)
271          * @param boolean $cache Use cached values?
272          *
273          * @return array uri data
274          */
275         public static function uri($uri, $network = "", $uid = 0, $cache = true) {
276
277                 if ($cache) {
278                         $result = \Cache::get("probe_url:".$network.":".$uri);
279                         if (!is_null($result)) {
280                                 return $result;
281                         }
282                 }
283
284                 if ($uid == 0) {
285                         $uid = local_user();
286                 }
287
288                 $data = self::detect($uri, $network, $uid);
289
290                 if (!isset($data["url"])) {
291                         $data["url"] = $uri;
292                 }
293
294                 if ($data["photo"] != "") {
295                         $data["baseurl"] = matching_url(normalise_link($data["baseurl"]), normalise_link($data["photo"]));
296                 } else {
297                         $data["photo"] = App::get_baseurl().'/images/person-175.jpg';
298                 }
299
300                 if (!isset($data["name"]) OR ($data["name"] == "")) {
301                         if (isset($data["nick"])) {
302                                 $data["name"] = $data["nick"];
303                         }
304
305                         if ($data["name"] == "") {
306                                 $data["name"] = $data["url"];
307                         }
308                 }
309
310                 if (!isset($data["nick"]) OR ($data["nick"] == "")) {
311                         $data["nick"] = strtolower($data["name"]);
312
313                         if (strpos($data['nick'], ' ')) {
314                                 $data['nick'] = trim(substr($data['nick'], 0, strpos($data['nick'], ' ')));
315                         }
316                 }
317
318                 if (self::$baseurl != "") {
319                         $data["baseurl"] = self::$baseurl;
320                 }
321
322                 if (!isset($data["network"])) {
323                         $data["network"] = NETWORK_PHANTOM;
324                 }
325
326                 $data = self::rearrangeData($data);
327
328                 // Only store into the cache if the value seems to be valid
329                 if (!in_array($data['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) {
330                         \Cache::set("probe_url:".$network.":".$uri, $data, CACHE_DAY);
331
332                         /// @todo temporary fix - we need a real contact update function that updates only changing fields
333                         /// The biggest problem is the avatar picture that could have a reduced image size.
334                         /// It should only be updated if the existing picture isn't existing anymore.
335                         /// We only update the contact when it is no probing for a specific network.
336                         if (($data['network'] != NETWORK_FEED)
337                                 AND ($network == "")
338                                 AND $data["name"]
339                                 AND $data["nick"]
340                                 AND $data["url"]
341                                 AND $data["addr"]
342                                 AND $data["poll"]
343                         ) {
344                                 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `url` = '%s', `addr` = '%s',
345                                                 `notify` = '%s', `poll` = '%s', `alias` = '%s', `success_update` = '%s'
346                                         WHERE `nurl` = '%s' AND NOT `self` AND `uid` = 0",
347                                         dbesc($data["name"]),
348                                         dbesc($data["nick"]),
349                                         dbesc($data["url"]),
350                                         dbesc($data["addr"]),
351                                         dbesc($data["notify"]),
352                                         dbesc($data["poll"]),
353                                         dbesc($data["alias"]),
354                                         dbesc(datetime_convert()),
355                                         dbesc(normalise_link($data['url']))
356                                 );
357                         }
358                 }
359
360                 return $data;
361         }
362
363         /**
364          * @brief Fetch information (protocol endpoints and user information) about a given uri
365          *
366          * This function is only called by the "uri" function that adds caching and rearranging of data.
367          *
368          * @param string $uri Address that should be probed
369          * @param string $network Test for this specific network
370          * @param integer $uid User ID for the probe (only used for mails)
371          *
372          * @return array uri data
373          */
374         private function detect($uri, $network, $uid) {
375                 $parts = parse_url($uri);
376
377                 if (isset($parts["scheme"]) AND isset($parts["host"]) AND isset($parts["path"])) {
378                         $host = $parts["host"];
379                         if (isset($parts["port"])) {
380                                 $host .= ':'.$parts["port"];
381                         }
382
383                         if ($host == 'twitter.com') {
384                                 return array("network" => NETWORK_TWITTER);
385                         }
386                         $lrdd = self::xrd($host);
387
388                         $path_parts = explode("/", trim($parts["path"], "/"));
389
390                         while (!$lrdd AND (sizeof($path_parts) > 1)) {
391                                 $host .= "/".array_shift($path_parts);
392                                 $lrdd = self::xrd($host);
393                         }
394                         if (!$lrdd) {
395                                 return self::feed($uri);
396                         }
397                         $nick = array_pop($path_parts);
398
399                         // Mastodon uses a "@" as prefix for usernames in their url format
400                         $nick = ltrim($nick, '@');
401
402                         $addr = $nick."@".$host;
403
404                 } elseif (strstr($uri, '@')) {
405                         // If the URI starts with "mailto:" then jump directly to the mail detection
406                         if (strpos($uri, 'mailto:') !== false) {
407                                 $uri = str_replace('mailto:', '', $uri);
408                                 return self::mail($uri, $uid);
409                         }
410
411                         if ($network == NETWORK_MAIL) {
412                                 return self::mail($uri, $uid);
413                         }
414                         // Remove "acct:" from the URI
415                         $uri = str_replace('acct:', '', $uri);
416
417                         $host = substr($uri, strpos($uri, '@') + 1);
418                         $nick = substr($uri, 0, strpos($uri, '@'));
419
420                         if (strpos($uri, '@twitter.com')) {
421                                 return array("network" => NETWORK_TWITTER);
422                         }
423                         $lrdd = self::xrd($host);
424
425                         if (!$lrdd) {
426                                 return self::mail($uri, $uid);
427                         }
428                         $addr = $uri;
429
430                 } else {
431                         return false;
432                 }
433
434                 $webfinger = false;
435
436                 /// @todo Do we need the prefix "acct:" or "acct://"?
437
438                 foreach ($lrdd as $key => $link) {
439                         if ($webfinger) {
440                                 continue;
441                         }
442                         if (!in_array($key, array("lrdd", "lrdd-xml", "lrdd-json"))) {
443                                 continue;
444                         }
445                         // At first try it with the given uri
446                         $path = str_replace('{uri}', urlencode($uri), $link);
447                         $webfinger = self::webfinger($path);
448
449                         // We cannot be sure that the detected address was correct, so we don't use the values
450                         if ($webfinger AND ($uri != $addr)) {
451                                 $nick = "";
452                                 $addr = "";
453                         }
454
455                         // Try webfinger with the address (user@domain.tld)
456                         if (!$webfinger) {
457                                 $path = str_replace('{uri}', urlencode($addr), $link);
458                                 $webfinger = self::webfinger($path);
459                         }
460
461                         // Mastodon needs to have it with "acct:"
462                         if (!$webfinger) {
463                                 $path = str_replace('{uri}', urlencode("acct:".$addr), $link);
464                                 $webfinger = self::webfinger($path);
465                         }
466                 }
467                 if (!$webfinger) {
468                         return self::feed($uri);
469                 }
470
471                 $result = false;
472
473                 logger("Probing ".$uri, LOGGER_DEBUG);
474
475                 if (in_array($network, array("", NETWORK_DFRN))) {
476                         $result = self::dfrn($webfinger);
477                 }
478                 if ((!$result AND ($network == "")) OR ($network == NETWORK_DIASPORA)) {
479                         $result = self::diaspora($webfinger);
480                 }
481                 if ((!$result AND ($network == "")) OR ($network == NETWORK_OSTATUS)) {
482                         $result = self::ostatus($webfinger);
483                 }
484                 if ((!$result AND ($network == "")) OR ($network == NETWORK_PUMPIO)) {
485                         $result = self::pumpio($webfinger);
486                 }
487                 if ((!$result AND ($network == "")) OR ($network == NETWORK_FEED)) {
488                         $result = self::feed($uri);
489                 } else {
490                         // We overwrite the detected nick with our try if the previois routines hadn't detected it.
491                         // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
492                         if ((!isset($result["nick"]) OR ($result["nick"] == "") OR (strstr($result["nick"], " "))) AND ($nick != "")) {
493                                 $result["nick"] = $nick;
494                         }
495
496                         if ((!isset($result["addr"]) OR ($result["addr"] == "")) AND ($addr != "")) {
497                                 $result["addr"] = $addr;
498                         }
499                 }
500
501                 logger($uri." is ".$result["network"], LOGGER_DEBUG);
502
503                 if (!isset($result["baseurl"]) OR ($result["baseurl"] == "")) {
504                         $pos = strpos($result["url"], $host);
505                         if ($pos) {
506                                 $result["baseurl"] = substr($result["url"], 0, $pos).$host;
507                         }
508                 }
509
510                 return $result;
511         }
512
513         /**
514          * @brief Perform a webfinger request.
515          *
516          * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
517          *
518          * @param string $url Address that should be probed
519          *
520          * @return array webfinger data
521          */
522         private function webfinger($url) {
523
524                 $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
525                 $redirects = 0;
526
527                 $ret = z_fetch_url($url, false, $redirects, array('timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml'));
528                 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
529                         return false;
530                 }
531                 $data = $ret['body'];
532
533                 $xrd = parse_xml_string($data, false);
534
535                 if (!is_object($xrd)) {
536                         // If it is not XML, maybe it is JSON
537                         $webfinger = json_decode($data, true);
538
539                         if (!isset($webfinger["links"])) {
540                                 return false;
541                         }
542
543                         return $webfinger;
544                 }
545
546                 $xrd_arr = \xml::element_to_array($xrd);
547                 if (!isset($xrd_arr["xrd"]["link"])) {
548                         return false;
549                 }
550
551                 $webfinger = array();
552
553                 if (isset($xrd_arr["xrd"]["subject"])) {
554                         $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
555                 }
556
557                 if (isset($xrd_arr["xrd"]["alias"])) {
558                         $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
559                 }
560
561                 $webfinger["links"] = array();
562
563                 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
564                         if (isset($data["@attributes"])) {
565                                 $attributes = $data["@attributes"];
566                         } elseif ($value == "@attributes") {
567                                 $attributes = $data;
568                         } else {
569                                 continue;
570                         }
571
572                         $webfinger["links"][] = $attributes;
573                 }
574                 return $webfinger;
575         }
576
577         /**
578          * @brief Poll the Friendica specific noscrape page.
579          *
580          * "noscrape" is a faster alternative to fetch the data from the hcard.
581          * This functionality was originally created for the directory.
582          *
583          * @param string $noscrape_url Link to the noscrape page
584          * @param array $data The already fetched data
585          *
586          * @return array noscrape data
587          */
588         private function pollNoscrape($noscrape_url, $data) {
589                 $ret = z_fetch_url($noscrape_url);
590                 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
591                         return false;
592                 }
593                 $content = $ret['body'];
594                 if (!$content) {
595                         return false;
596                 }
597
598                 $json = json_decode($content, true);
599                 if (!is_array($json)) {
600                         return false;
601                 }
602
603                 if (isset($json["fn"])) {
604                         $data["name"] = $json["fn"];
605                 }
606
607                 if (isset($json["addr"])) {
608                         $data["addr"] = $json["addr"];
609                 }
610
611                 if (isset($json["nick"])) {
612                         $data["nick"] = $json["nick"];
613                 }
614
615                 if (isset($json["comm"])) {
616                         $data["community"] = $json["comm"];
617                 }
618
619                 if (isset($json["tags"])) {
620                         $keywords = implode(" ", $json["tags"]);
621                         if ($keywords != "") {
622                                 $data["keywords"] = $keywords;
623                         }
624                 }
625
626                 $location = formatted_location($json);
627                 if ($location) {
628                         $data["location"] = $location;
629                 }
630
631                 if (isset($json["about"])) {
632                         $data["about"] = $json["about"];
633                 }
634
635                 if (isset($json["key"])) {
636                         $data["pubkey"] = $json["key"];
637                 }
638
639                 if (isset($json["photo"])) {
640                         $data["photo"] = $json["photo"];
641                 }
642
643                 if (isset($json["dfrn-request"])) {
644                         $data["request"] = $json["dfrn-request"];
645                 }
646
647                 if (isset($json["dfrn-confirm"])) {
648                         $data["confirm"] = $json["dfrn-confirm"];
649                 }
650
651                 if (isset($json["dfrn-notify"])) {
652                         $data["notify"] = $json["dfrn-notify"];
653                 }
654
655                 if (isset($json["dfrn-poll"])) {
656                         $data["poll"] = $json["dfrn-poll"];
657                 }
658
659                 return $data;
660         }
661
662         /**
663          * @brief Check for valid DFRN data
664          *
665          * @param array $data DFRN data
666          *
667          * @return int Number of errors
668          */
669         public static function validDfrn($data) {
670                 $errors = 0;
671                 if (!isset($data['key'])) {
672                         $errors ++;
673                 }
674                 if (!isset($data['dfrn-request'])) {
675                         $errors ++;
676                 }
677                 if (!isset($data['dfrn-confirm'])) {
678                         $errors ++;
679                 }
680                 if (!isset($data['dfrn-notify'])) {
681                         $errors ++;
682                 }
683                 if (!isset($data['dfrn-poll'])) {
684                         $errors ++;
685                 }
686                 return $errors;
687         }
688
689         /**
690          * @brief Fetch data from a DFRN profile page and via "noscrape"
691          *
692          * @param string $profile_link Link to the profile page
693          *
694          * @return array profile data
695          */
696         public static function profile($profile_link) {
697
698                 $data = array();
699
700                 logger("Check profile ".$profile_link, LOGGER_DEBUG);
701
702                 // Fetch data via noscrape - this is faster
703                 $noscrape_url = str_replace(array("/hcard/", "/profile/"), "/noscrape/", $profile_link);
704                 $data = self::pollNoscrape($noscrape_url, $data);
705
706                 if (!isset($data["notify"])
707                         OR !isset($data["confirm"])
708                         OR !isset($data["request"])
709                         OR !isset($data["poll"])
710                         OR !isset($data["poco"])
711                         OR !isset($data["name"])
712                         OR !isset($data["photo"])
713                 ) {
714                         $data = self::pollHcard($profile_link, $data, true);
715                 }
716
717                 $prof_data = array();
718                 $prof_data["addr"]         = $data["addr"];
719                 $prof_data["nick"]         = $data["nick"];
720                 $prof_data["dfrn-request"] = $data["request"];
721                 $prof_data["dfrn-confirm"] = $data["confirm"];
722                 $prof_data["dfrn-notify"]  = $data["notify"];
723                 $prof_data["dfrn-poll"]    = $data["poll"];
724                 $prof_data["dfrn-poco"]    = $data["poco"];
725                 $prof_data["photo"]        = $data["photo"];
726                 $prof_data["fn"]           = $data["name"];
727                 $prof_data["key"]          = $data["pubkey"];
728
729                 logger("Result for profile ".$profile_link.": ".print_r($prof_data, true), LOGGER_DEBUG);
730
731                 return $prof_data;
732         }
733
734         /**
735          * @brief Check for DFRN contact
736          *
737          * @param array $webfinger Webfinger data
738          *
739          * @return array DFRN data
740          */
741         private function dfrn($webfinger) {
742
743                 $hcard_url = "";
744                 $data = array();
745                 foreach ($webfinger["links"] as $link) {
746                         if (($link["rel"] == NAMESPACE_DFRN) AND ($link["href"] != "")) {
747                                 $data["network"] = NETWORK_DFRN;
748                         } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
749                                 $data["poll"] = $link["href"];
750                         } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND ($link["type"] == "text/html") AND ($link["href"] != "")) {
751                                 $data["url"] = $link["href"];
752                         } elseif (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != "")) {
753                                 $hcard_url = $link["href"];
754                         } elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != "")) {
755                                 $data["poco"] = $link["href"];
756                         } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") AND ($link["href"] != "")) {
757                                 $data["photo"] = $link["href"];
758                         } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != "")) {
759                                 $data["baseurl"] = trim($link["href"], '/');
760                         } elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != "")) {
761                                 $data["guid"] = $link["href"];
762                         } elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
763                                 $data["pubkey"] = base64_decode($link["href"]);
764
765                                 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
766                                 if (strstr($data["pubkey"], 'RSA ')) {
767                                         $data["pubkey"] = rsatopem($data["pubkey"]);
768                                 }
769                         }
770                 }
771
772                 if (!isset($data["network"]) OR ($hcard_url == "")) {
773                         return false;
774                 }
775
776                 // Fetch data via noscrape - this is faster
777                 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
778                 $data = self::pollNoscrape($noscrape_url, $data);
779
780                 if (isset($data["notify"])
781                         AND isset($data["confirm"])
782                         AND isset($data["request"])
783                         AND isset($data["poll"])
784                         AND isset($data["name"])
785                         AND isset($data["photo"])
786                 ) {
787                         return $data;
788                 }
789
790                 $data = self::pollHcard($hcard_url, $data, true);
791
792                 return $data;
793         }
794
795         /**
796          * @brief Poll the hcard page (Diaspora and Friendica specific)
797          *
798          * @param string $hcard_url Link to the hcard page
799          * @param array $data The already fetched data
800          * @param boolean $dfrn Poll DFRN specific data
801          *
802          * @return array hcard data
803          */
804         private function pollHcard($hcard_url, $data, $dfrn = false) {
805                 $ret = z_fetch_url($hcard_url);
806                 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
807                         return false;
808                 }
809                 $content = $ret['body'];
810                 if (!$content) {
811                         return false;
812                 }
813
814                 $doc = new \DOMDocument();
815                 if (!@$doc->loadHTML($content)) {
816                         return false;
817                 }
818
819                 $xpath = new \DomXPath($doc);
820
821                 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
822                 if (!is_object($vcards)) {
823                         return false;
824                 }
825
826                 if ($vcards->length > 0) {
827                         $vcard = $vcards->item(0);
828
829                         // We have to discard the guid from the hcard in favour of the guid from lrdd
830                         // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
831                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
832                         if (($search->length > 0) AND ($data["guid"] == "")) {
833                                 $data["guid"] = $search->item(0)->nodeValue;
834                         }
835
836                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
837                         if ($search->length > 0) {
838                                 $data["nick"] = $search->item(0)->nodeValue;
839                         }
840
841                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
842                         if ($search->length > 0) {
843                                 $data["name"] = $search->item(0)->nodeValue;
844                         }
845
846                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
847                         if ($search->length > 0) {
848                                 $data["searchable"] = $search->item(0)->nodeValue;
849                         }
850
851                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
852                         if ($search->length > 0) {
853                                 $data["pubkey"] = $search->item(0)->nodeValue;
854                                 if (strstr($data["pubkey"], 'RSA ')) {
855                                         $data["pubkey"] = rsatopem($data["pubkey"]);
856                                 }
857                         }
858
859                         $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
860                         if ($search->length > 0) {
861                                 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
862                         }
863                 }
864
865                 $avatar = array();
866                 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
867                 foreach ($photos as $photo) {
868                         $attr = array();
869                         foreach ($photo->attributes as $attribute) {
870                                 $attr[$attribute->name] = trim($attribute->value);
871                         }
872
873                         if (isset($attr["src"]) AND isset($attr["width"])) {
874                                 $avatar[$attr["width"]] = $attr["src"];
875                         }
876
877                         // We don't have a width. So we just take everything that we got.
878                         // This is a Hubzilla workaround which doesn't send a width.
879                         if ((sizeof($avatar) == 0) AND isset($attr["src"])) {
880                                 $avatar[] = $attr["src"];
881                         }
882                 }
883
884                 if (sizeof($avatar)) {
885                         ksort($avatar);
886                         $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
887                 }
888
889                 if ($dfrn) {
890                         // Poll DFRN specific data
891                         $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
892                         if ($search->length > 0) {
893                                 foreach ($search as $link) {
894                                         //$data["request"] = $search->item(0)->nodeValue;
895                                         $attr = array();
896                                         foreach ($link->attributes as $attribute) {
897                                                 $attr[$attribute->name] = trim($attribute->value);
898                                         }
899
900                                         $data[substr($attr["rel"], 5)] = $attr["href"];
901                                 }
902                         }
903
904                         // Older Friendica versions had used the "uid" field differently than newer versions
905                         if ($data["nick"] == $data["guid"]) {
906                                 unset($data["guid"]);
907                         }
908                 }
909
910
911                 return $data;
912         }
913
914         /**
915          * @brief Check for Diaspora contact
916          *
917          * @param array $webfinger Webfinger data
918          *
919          * @return array Diaspora data
920          */
921         private function diaspora($webfinger) {
922
923                 $hcard_url = "";
924                 $data = array();
925                 foreach ($webfinger["links"] as $link) {
926                         if (($link["rel"] == "http://microformats.org/profile/hcard") AND ($link["href"] != "")) {
927                                 $hcard_url = $link["href"];
928                         } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") AND ($link["href"] != "")) {
929                                 $data["baseurl"] = trim($link["href"], '/');
930                         } elseif (($link["rel"] == "http://joindiaspora.com/guid") AND ($link["href"] != "")) {
931                                 $data["guid"] = $link["href"];
932                         } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") AND ($link["type"] == "text/html") AND ($link["href"] != "")) {
933                                 $data["url"] = $link["href"];
934                         } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
935                                 $data["poll"] = $link["href"];
936                         } elseif (($link["rel"] == NAMESPACE_POCO) AND ($link["href"] != "")) {
937                                 $data["poco"] = $link["href"];
938                         } elseif (($link["rel"] == "salmon") AND ($link["href"] != "")) {
939                                 $data["notify"] = $link["href"];
940                         } elseif (($link["rel"] == "diaspora-public-key") AND ($link["href"] != "")) {
941                                 $data["pubkey"] = base64_decode($link["href"]);
942
943                                 //if (strstr($data["pubkey"], 'RSA ') OR ($link["type"] == "RSA"))
944                                 if (strstr($data["pubkey"], 'RSA ')) {
945                                         $data["pubkey"] = rsatopem($data["pubkey"]);
946                                 }
947                         }
948                 }
949
950                 if (!isset($data["url"]) OR ($hcard_url == "")) {
951                         return false;
952                 }
953
954                 if (is_array($webfinger["aliases"])) {
955                         foreach ($webfinger["aliases"] as $alias) {
956                                 if (normalise_link($alias) != normalise_link($data["url"]) AND ! strstr($alias, "@")) {
957                                         $data["alias"] = $alias;
958                                 }
959                         }
960                 }
961
962                 // Fetch further information from the hcard
963                 $data = self::pollHcard($hcard_url, $data);
964
965                 if (!$data) {
966                         return false;
967                 }
968
969                 if (isset($data["url"])
970                         AND isset($data["guid"])
971                         AND isset($data["baseurl"])
972                         AND isset($data["pubkey"])
973                         AND ($hcard_url != "")
974                 ) {
975                         $data["network"] = NETWORK_DIASPORA;
976
977                         // The Diaspora handle must always be lowercase
978                         $data["addr"] = strtolower($data["addr"]);
979
980                         // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
981                         $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
982                         $data["batch"]  = $data["baseurl"] . "/receive/public";
983                 } else {
984                         return false;
985                 }
986
987                 return $data;
988         }
989
990         /**
991          * @brief Check for OStatus contact
992          *
993          * @param array $webfinger Webfinger data
994          *
995          * @return array OStatus data
996          */
997         private function ostatus($webfinger) {
998                 $data = array();
999                 if (is_array($webfinger["aliases"])) {
1000                         foreach ($webfinger["aliases"] as $alias) {
1001                                 if (strstr($alias, "@")) {
1002                                         $data["addr"] = str_replace('acct:', '', $alias);
1003                                 }
1004                         }
1005                 }
1006
1007                 if (is_string($webfinger["subject"]) AND strstr($webfinger["subject"], "@")) {
1008                         $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1009                 }
1010                 $pubkey = "";
1011                 foreach ($webfinger["links"] as $link) {
1012                         if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1013                                 AND ($link["type"] == "text/html")
1014                                 AND ($link["href"] != "")
1015                         ) {
1016                                 $data["url"] = $link["href"];
1017                         } elseif (($link["rel"] == "salmon") AND ($link["href"] != "")) {
1018                                 $data["notify"] = $link["href"];
1019                         } elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != "")) {
1020                                 $data["poll"] = $link["href"];
1021                         } elseif (($link["rel"] == "magic-public-key") AND ($link["href"] != "")) {
1022                                 $pubkey = $link["href"];
1023
1024                                 if (substr($pubkey, 0, 5) === 'data:') {
1025                                         if (strstr($pubkey, ',')) {
1026                                                 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1027                                         } else {
1028                                                 $pubkey = substr($pubkey, 5);
1029                                         }
1030                                 } elseif (normalise_link($pubkey) == 'http://') {
1031                                         $ret = z_fetch_url($pubkey);
1032                                         if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1033                                                 return false;
1034                                         }
1035                                         $pubkey = $ret['body'];
1036                                 }
1037
1038                                 $key = explode(".", $pubkey);
1039
1040                                 if (sizeof($key) >= 3) {
1041                                         $m = base64url_decode($key[1]);
1042                                         $e = base64url_decode($key[2]);
1043                                         $data["pubkey"] = metopem($m, $e);
1044                                 }
1045                         }
1046                 }
1047
1048                 if (isset($data["notify"]) AND isset($data["pubkey"])
1049                         AND isset($data["poll"])
1050                         AND isset($data["url"])
1051                 ) {
1052                         $data["network"] = NETWORK_OSTATUS;
1053                 } else {
1054                         return false;
1055                 }
1056                 // Fetch all additional data from the feed
1057                 $ret = z_fetch_url($data["poll"]);
1058                 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1059                         return false;
1060                 }
1061                 $feed = $ret['body'];
1062                 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1063                 if (!$feed_data) {
1064                         return false;
1065                 }
1066                 if ($feed_data["header"]["author-name"] != "") {
1067                         $data["name"] = $feed_data["header"]["author-name"];
1068                 }
1069                 if ($feed_data["header"]["author-nick"] != "") {
1070                         $data["nick"] = $feed_data["header"]["author-nick"];
1071                 }
1072                 if ($feed_data["header"]["author-avatar"] != "") {
1073                         $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1074                 }
1075                 if ($feed_data["header"]["author-id"] != "") {
1076                         $data["alias"] = $feed_data["header"]["author-id"];
1077                 }
1078                 if ($feed_data["header"]["author-location"] != "") {
1079                         $data["location"] = $feed_data["header"]["author-location"];
1080                 }
1081                 if ($feed_data["header"]["author-about"] != "") {
1082                         $data["about"] = $feed_data["header"]["author-about"];
1083                 }
1084                 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1085                 // So we take the value that we just fetched, although the other one worked as well
1086                 if ($feed_data["header"]["author-link"] != "") {
1087                         $data["url"] = $feed_data["header"]["author-link"];
1088                 }
1089                 /// @todo Fetch location and "about" from the feed as well
1090                 return $data;
1091         }
1092
1093         /**
1094          * @brief Fetch data from a pump.io profile page
1095          *
1096          * @param string $profile_link Link to the profile page
1097          *
1098          * @return array profile data
1099          */
1100         private function pumpioProfileData($profile_link) {
1101
1102                 $doc = new \DOMDocument();
1103                 if (!@$doc->loadHTMLFile($profile_link)) {
1104                         return false;
1105                 }
1106
1107                 $xpath = new \DomXPath($doc);
1108
1109                 $data = array();
1110
1111                 // This is ugly - but pump.io doesn't seem to know a better way for it
1112                 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1113                 $pos = strpos($data["name"], chr(10));
1114                 if ($pos) {
1115                         $data["name"] = trim(substr($data["name"], 0, $pos));
1116                 }
1117
1118                 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1119                 if ($avatar) {
1120                         foreach ($avatar->attributes as $attribute) {
1121                                 if ($attribute->name == "src") {
1122                                         $data["photo"] = trim($attribute->value);
1123                                 }
1124                         }
1125                 }
1126
1127                 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
1128                 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
1129
1130                 return $data;
1131         }
1132
1133         /**
1134          * @brief Check for pump.io contact
1135          *
1136          * @param array $webfinger Webfinger data
1137          *
1138          * @return array pump.io data
1139          */
1140         private function pumpio($webfinger) {
1141
1142                 $data = array();
1143                 foreach ($webfinger["links"] as $link) {
1144                         if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1145                                 AND ($link["type"] == "text/html")
1146                                 AND ($link["href"] != "")
1147                         ) {
1148                                 $data["url"] = $link["href"];
1149                         } elseif (($link["rel"] == "activity-inbox") AND ($link["href"] != "")) {
1150                                 $data["notify"] = $link["href"];
1151                         } elseif (($link["rel"] == "activity-outbox") AND ($link["href"] != "")) {
1152                                 $data["poll"] = $link["href"];
1153                         } elseif (($link["rel"] == "dialback") AND ($link["href"] != "")) {
1154                                 $data["dialback"] = $link["href"];
1155                         }
1156                 }
1157                 if (isset($data["poll"]) AND isset($data["notify"])
1158                         AND isset($data["dialback"])
1159                         AND isset($data["url"])
1160                 ) {
1161                         // by now we use these fields only for the network type detection
1162                         // So we unset all data that isn't used at the moment
1163                         unset($data["dialback"]);
1164
1165                         $data["network"] = NETWORK_PUMPIO;
1166                 } else {
1167                         return false;
1168                 }
1169
1170                 $profile_data = self::pumpioProfileData($data["url"]);
1171
1172                 if (!$profile_data) {
1173                         return false;
1174                 }
1175
1176                 $data = array_merge($data, $profile_data);
1177
1178                 return $data;
1179         }
1180
1181         /**
1182          * @brief Check page for feed link
1183          *
1184          * @param string $url Page link
1185          *
1186          * @return string feed link
1187          */
1188         private function getFeedLink($url) {
1189                 $doc = new \DOMDocument();
1190
1191                 if (!@$doc->loadHTMLFile($url)) {
1192                         return false;
1193                 }
1194
1195                 $xpath = new \DomXPath($doc);
1196
1197                 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1198                 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1199                 if (!is_object($feeds)) {
1200                         return false;
1201                 }
1202
1203                 if ($feeds->length == 0) {
1204                         return false;
1205                 }
1206
1207                 $feed_url = "";
1208
1209                 foreach ($feeds as $feed) {
1210                         $attr = array();
1211                         foreach ($feed->attributes as $attribute) {
1212                                 $attr[$attribute->name] = trim($attribute->value);
1213                         }
1214
1215                         if ($feed_url == "") {
1216                                 $feed_url = $attr["href"];
1217                         }
1218                 }
1219
1220                 return $feed_url;
1221         }
1222
1223         /**
1224          * @brief Check for feed contact
1225          *
1226          * @param string $url Profile link
1227          * @param boolean $probe Do a probe if the page contains a feed link
1228          *
1229          * @return array feed data
1230          */
1231         private function feed($url, $probe = true) {
1232                 $ret = z_fetch_url($url);
1233                 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1234                         return false;
1235                 }
1236                 $feed = $ret['body'];
1237                 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1238
1239                 if (!$feed_data) {
1240                         if (!$probe) {
1241                                 return false;
1242                         }
1243
1244                         $feed_url = self::getFeedLink($url);
1245
1246                         if (!$feed_url) {
1247                                 return false;
1248                         }
1249
1250                         return self::feed($feed_url, false);
1251                 }
1252
1253                 if ($feed_data["header"]["author-name"] != "") {
1254                         $data["name"] = $feed_data["header"]["author-name"];
1255                 }
1256
1257                 if ($feed_data["header"]["author-nick"] != "") {
1258                         $data["nick"] = $feed_data["header"]["author-nick"];
1259                 }
1260
1261                 if ($feed_data["header"]["author-avatar"] != "") {
1262                         $data["photo"] = $feed_data["header"]["author-avatar"];
1263                 }
1264
1265                 if ($feed_data["header"]["author-id"] != "") {
1266                         $data["alias"] = $feed_data["header"]["author-id"];
1267                 }
1268
1269                 $data["url"] = $url;
1270                 $data["poll"] = $url;
1271
1272                 if ($feed_data["header"]["author-link"] != "") {
1273                         $data["baseurl"] = $feed_data["header"]["author-link"];
1274                 } else {
1275                         $data["baseurl"] = $data["url"];
1276                 }
1277
1278                 $data["network"] = NETWORK_FEED;
1279
1280                 return $data;
1281         }
1282
1283         /**
1284          * @brief Check for mail contact
1285          *
1286          * @param string $uri Profile link
1287          * @param integer $uid User ID
1288          *
1289          * @return array mail data
1290          */
1291         private function mail($uri, $uid) {
1292
1293                 if (!validate_email($uri)) {
1294                         return false;
1295                 }
1296
1297                 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1298
1299                 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1300
1301                 if (\dbm::is_result($x) && \dbm::is_result($r)) {
1302                         $mailbox = construct_mailbox_name($r[0]);
1303                         $password = '';
1304                         openssl_private_decrypt(hex2bin($r[0]['pass']), $password, $x[0]['prvkey']);
1305                         $mbox = email_connect($mailbox, $r[0]['user'], $password);
1306                         if (!mbox) {
1307                                 return false;
1308                         }
1309                 }
1310
1311                 $msgs = email_poll($mbox, $uri);
1312                 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1313
1314                 if (!count($msgs)) {
1315                         return false;
1316                 }
1317
1318                 $phost = substr($uri, strpos($uri, '@') + 1);
1319
1320                 $data = array();
1321                 $data["addr"]    = $uri;
1322                 $data["network"] = NETWORK_MAIL;
1323                 $data["name"]    = substr($uri, 0, strpos($uri, '@'));
1324                 $data["nick"]    = $data["name"];
1325                 $data["photo"]   = avatar_img($uri);
1326                 $data["url"]     = 'http://'.$phost."/".$data["nick"];
1327                 $data["notify"]  = 'smtp '.random_string();
1328                 $data["poll"]    = 'email '.random_string();
1329
1330                 $x = email_msg_meta($mbox, $msgs[0]);
1331                 if (stristr($x[0]->from, $uri)) {
1332                         $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1333                 } elseif (stristr($x[0]->to, $uri)) {
1334                         $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1335                 }
1336                 if (isset($adr)) {
1337                         foreach ($adr as $feadr) {
1338                                 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1339                                         &&(strcasecmp($feadr->host, $phost) == 0)
1340                                         && (strlen($feadr->personal))
1341                                 ) {
1342                                         $personal = imap_mime_header_decode($feadr->personal);
1343                                         $data["name"] = "";
1344                                         foreach ($personal as $perspart) {
1345                                                 if ($perspart->charset != "default") {
1346                                                         $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1347                                                 } else {
1348                                                         $data["name"] .= $perspart->text;
1349                                                 }
1350                                         }
1351
1352                                         $data["name"] = notags($data["name"]);
1353                                 }
1354                         }
1355                 }
1356                 imap_close($mbox);
1357
1358                 return $data;
1359         }
1360
1361         /**
1362          * @brief Mix two paths together to possibly fix missing parts
1363          *
1364          * @param string $avatar Path to the avatar
1365          * @param string $base Another path that is hopefully complete
1366          *
1367          * @return string fixed avatar path
1368          */
1369         public static function fixAvatar($avatar, $base) {
1370                 $base_parts = parse_url($base);
1371
1372                 // Remove all parts that could create a problem
1373                 unset($base_parts['path']);
1374                 unset($base_parts['query']);
1375                 unset($base_parts['fragment']);
1376
1377                 $avatar_parts = parse_url($avatar);
1378
1379                 // Now we mix them
1380                 $parts = array_merge($base_parts, $avatar_parts);
1381
1382                 // And put them together again
1383                 $scheme   = isset($parts['scheme'])   ? $parts['scheme'] . '://' : '';
1384                 $host     = isset($parts['host'])     ? $parts['host']           : '';
1385                 $port     = isset($parts['port'])     ? ':' . $parts['port']     : '';
1386                 $path     = isset($parts['path'])     ? $parts['path']           : '';
1387                 $query    = isset($parts['query'])    ? '?' . $parts['query']    : '';
1388                 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1389
1390                 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1391
1392                 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);
1393
1394                 return $fixed;
1395         }
1396 }