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