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