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