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