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