]> git.mxchange.org Git - friendica.git/blob - src/Network/Probe.php
Merge pull request #3577 from annando/2in1
[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) && !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                                 && ($attributes["type"] == "application/xrd+xml")
148                         ) {
149                                 $xrd_data["lrdd-xml"] = $attributes["template"];
150                         } elseif (($attributes["rel"] == "lrdd")
151                                 && ($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) && ($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 && (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 && (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 && 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"]) || ($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"]) || ($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                                 && ($network == "")
381                                 && $data["name"]
382                                 && $data["nick"]
383                                 && $data["url"]
384                                 && $data["addr"]
385                                 && $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"]) && isset($parts["host"]) && 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 && (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 && ($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 && ($network == "")) || ($network == NETWORK_DIASPORA)) {
533                         $result = self::diaspora($webfinger);
534                 }
535                 if ((!$result && ($network == "")) || ($network == NETWORK_OSTATUS)) {
536                         $result = self::ostatus($webfinger);
537                 }
538                 if ((!$result && ($network == "")) || ($network == NETWORK_PUMPIO)) {
539                         $result = self::pumpio($webfinger);
540                 }
541                 if ((!$result && ($network == "")) || ($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"]) || ($result["nick"] == "") || (strstr($result["nick"], " "))) && ($nick != "")) {
547                                 $result["nick"] = $nick;
548                         }
549
550                         if ((!isset($result["addr"]) || ($result["addr"] == "")) && ($addr != "")) {
551                                 $result["addr"] = $addr;
552                         }
553                 }
554
555                 logger($uri." is ".$result["network"], LOGGER_DEBUG);
556
557                 if (!isset($result["baseurl"]) || ($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                         || !isset($data["confirm"])
766                         || !isset($data["request"])
767                         || !isset($data["poll"])
768                         || !isset($data["poco"])
769                         || !isset($data["name"])
770                         || !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) && ($link["href"] != "")) {
805                                 $data["network"] = NETWORK_DFRN;
806                         } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
807                                 $data["poll"] = $link["href"];
808                         } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
809                                 $data["url"] = $link["href"];
810                         } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
811                                 $hcard_url = $link["href"];
812                         } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
813                                 $data["poco"] = $link["href"];
814                         } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && ($link["href"] != "")) {
815                                 $data["photo"] = $link["href"];
816                         } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
817                                 $data["baseurl"] = trim($link["href"], '/');
818                         } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
819                                 $data["guid"] = $link["href"];
820                         } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
821                                 $data["pubkey"] = base64_decode($link["href"]);
822
823                                 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
824                                 if (strstr($data["pubkey"], 'RSA ')) {
825                                         $data["pubkey"] = rsatopem($data["pubkey"]);
826                                 }
827                         }
828                 }
829
830                 foreach ($webfinger["aliases"] as $alias) {
831                         if (substr($alias, 0, 5) == 'acct:') {
832                                 $data["addr"] = substr($alias, 5);
833                         }
834                 }
835
836                 if (!isset($data["network"]) || ($hcard_url == "")) {
837                         return false;
838                 }
839
840                 // Fetch data via noscrape - this is faster
841                 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
842                 $data = self::pollNoscrape($noscrape_url, $data);
843
844                 if (isset($data["notify"])
845                         && isset($data["confirm"])
846                         && isset($data["request"])
847                         && isset($data["poll"])
848                         && isset($data["name"])
849                         && isset($data["photo"])
850                 ) {
851                         return $data;
852                 }
853
854                 $data = self::pollHcard($hcard_url, $data, true);
855
856                 return $data;
857         }
858
859         /**
860          * @brief Poll the hcard page (Diaspora and Friendica specific)
861          *
862          * @param string $hcard_url Link to the hcard page
863          * @param array $data The already fetched data
864          * @param boolean $dfrn Poll DFRN specific data
865          *
866          * @return array hcard data
867          */
868         private function pollHcard($hcard_url, $data, $dfrn = false) {
869                 $ret = z_fetch_url($hcard_url);
870                 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
871                         return false;
872                 }
873                 $content = $ret['body'];
874                 if (!$content) {
875                         return false;
876                 }
877
878                 $doc = new DOMDocument();
879                 if (!@$doc->loadHTML($content)) {
880                         return false;
881                 }
882
883                 $xpath = new DomXPath($doc);
884
885                 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
886                 if (!is_object($vcards)) {
887                         return false;
888                 }
889
890                 if ($vcards->length > 0) {
891                         $vcard = $vcards->item(0);
892
893                         // We have to discard the guid from the hcard in favour of the guid from lrdd
894                         // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
895                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
896                         if (($search->length > 0) && ($data["guid"] == "")) {
897                                 $data["guid"] = $search->item(0)->nodeValue;
898                         }
899
900                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
901                         if ($search->length > 0) {
902                                 $data["nick"] = $search->item(0)->nodeValue;
903                         }
904
905                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
906                         if ($search->length > 0) {
907                                 $data["name"] = $search->item(0)->nodeValue;
908                         }
909
910                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
911                         if ($search->length > 0) {
912                                 $data["searchable"] = $search->item(0)->nodeValue;
913                         }
914
915                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
916                         if ($search->length > 0) {
917                                 $data["pubkey"] = $search->item(0)->nodeValue;
918                                 if (strstr($data["pubkey"], 'RSA ')) {
919                                         $data["pubkey"] = rsatopem($data["pubkey"]);
920                                 }
921                         }
922
923                         $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
924                         if ($search->length > 0) {
925                                 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
926                         }
927                 }
928
929                 $avatar = array();
930                 $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
931                 foreach ($photos as $photo) {
932                         $attr = array();
933                         foreach ($photo->attributes as $attribute) {
934                                 $attr[$attribute->name] = trim($attribute->value);
935                         }
936
937                         if (isset($attr["src"]) && isset($attr["width"])) {
938                                 $avatar[$attr["width"]] = $attr["src"];
939                         }
940
941                         // We don't have a width. So we just take everything that we got.
942                         // This is a Hubzilla workaround which doesn't send a width.
943                         if ((sizeof($avatar) == 0) && isset($attr["src"])) {
944                                 $avatar[] = $attr["src"];
945                         }
946                 }
947
948                 if (sizeof($avatar)) {
949                         ksort($avatar);
950                         $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
951                 }
952
953                 if ($dfrn) {
954                         // Poll DFRN specific data
955                         $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
956                         if ($search->length > 0) {
957                                 foreach ($search as $link) {
958                                         //$data["request"] = $search->item(0)->nodeValue;
959                                         $attr = array();
960                                         foreach ($link->attributes as $attribute) {
961                                                 $attr[$attribute->name] = trim($attribute->value);
962                                         }
963
964                                         $data[substr($attr["rel"], 5)] = $attr["href"];
965                                 }
966                         }
967
968                         // Older Friendica versions had used the "uid" field differently than newer versions
969                         if ($data["nick"] == $data["guid"]) {
970                                 unset($data["guid"]);
971                         }
972                 }
973
974
975                 return $data;
976         }
977
978         /**
979          * @brief Check for Diaspora contact
980          *
981          * @param array $webfinger Webfinger data
982          *
983          * @return array Diaspora data
984          */
985         private function diaspora($webfinger) {
986
987                 $hcard_url = "";
988                 $data = array();
989                 foreach ($webfinger["links"] as $link) {
990                         if (($link["rel"] == "http://microformats.org/profile/hcard") && ($link["href"] != "")) {
991                                 $hcard_url = $link["href"];
992                         } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && ($link["href"] != "")) {
993                                 $data["baseurl"] = trim($link["href"], '/');
994                         } elseif (($link["rel"] == "http://joindiaspora.com/guid") && ($link["href"] != "")) {
995                                 $data["guid"] = $link["href"];
996                         } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && ($link["type"] == "text/html") && ($link["href"] != "")) {
997                                 $data["url"] = $link["href"];
998                         } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
999                                 $data["poll"] = $link["href"];
1000                         } elseif (($link["rel"] == NAMESPACE_POCO) && ($link["href"] != "")) {
1001                                 $data["poco"] = $link["href"];
1002                         } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1003                                 $data["notify"] = $link["href"];
1004                         } elseif (($link["rel"] == "diaspora-public-key") && ($link["href"] != "")) {
1005                                 $data["pubkey"] = base64_decode($link["href"]);
1006
1007                                 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1008                                 if (strstr($data["pubkey"], 'RSA ')) {
1009                                         $data["pubkey"] = rsatopem($data["pubkey"]);
1010                                 }
1011                         }
1012                 }
1013
1014                 if (!isset($data["url"]) || ($hcard_url == "")) {
1015                         return false;
1016                 }
1017
1018                 if (is_array($webfinger["aliases"])) {
1019                         foreach ($webfinger["aliases"] as $alias) {
1020                                 if (normalise_link($alias) != normalise_link($data["url"]) && ! strstr($alias, "@")) {
1021                                         $data["alias"] = $alias;
1022                                 }
1023                         }
1024                 }
1025
1026                 // Fetch further information from the hcard
1027                 $data = self::pollHcard($hcard_url, $data);
1028
1029                 if (!$data) {
1030                         return false;
1031                 }
1032
1033                 if (isset($data["url"])
1034                         && isset($data["guid"])
1035                         && isset($data["baseurl"])
1036                         && isset($data["pubkey"])
1037                         && ($hcard_url != "")
1038                 ) {
1039                         $data["network"] = NETWORK_DIASPORA;
1040
1041                         // The Diaspora handle must always be lowercase
1042                         $data["addr"] = strtolower($data["addr"]);
1043
1044                         // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1045                         $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1046                         $data["batch"]  = $data["baseurl"] . "/receive/public";
1047                 } else {
1048                         return false;
1049                 }
1050
1051                 return $data;
1052         }
1053
1054         /**
1055          * @brief Check for OStatus contact
1056          *
1057          * @param array $webfinger Webfinger data
1058          *
1059          * @return array OStatus data
1060          */
1061         private function ostatus($webfinger) {
1062                 $data = array();
1063                 if (is_array($webfinger["aliases"])) {
1064                         foreach ($webfinger["aliases"] as $alias) {
1065                                 if (strstr($alias, "@")) {
1066                                         $data["addr"] = str_replace('acct:', '', $alias);
1067                                 }
1068                         }
1069                 }
1070
1071                 if (is_string($webfinger["subject"]) && strstr($webfinger["subject"], "@")) {
1072                         $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1073                 }
1074                 $pubkey = "";
1075                 foreach ($webfinger["links"] as $link) {
1076                         if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1077                                 && ($link["type"] == "text/html")
1078                                 && ($link["href"] != "")
1079                         ) {
1080                                 $data["url"] = $link["href"];
1081                         } elseif (($link["rel"] == "salmon") && ($link["href"] != "")) {
1082                                 $data["notify"] = $link["href"];
1083                         } elseif (($link["rel"] == NAMESPACE_FEED) && ($link["href"] != "")) {
1084                                 $data["poll"] = $link["href"];
1085                         } elseif (($link["rel"] == "magic-public-key") && ($link["href"] != "")) {
1086                                 $pubkey = $link["href"];
1087
1088                                 if (substr($pubkey, 0, 5) === 'data:') {
1089                                         if (strstr($pubkey, ',')) {
1090                                                 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1091                                         } else {
1092                                                 $pubkey = substr($pubkey, 5);
1093                                         }
1094                                 } elseif (normalise_link($pubkey) == 'http://') {
1095                                         $ret = z_fetch_url($pubkey);
1096                                         if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1097                                                 return false;
1098                                         }
1099                                         $pubkey = $ret['body'];
1100                                 }
1101
1102                                 $key = explode(".", $pubkey);
1103
1104                                 if (sizeof($key) >= 3) {
1105                                         $m = base64url_decode($key[1]);
1106                                         $e = base64url_decode($key[2]);
1107                                         $data["pubkey"] = metopem($m, $e);
1108                                 }
1109                         }
1110                 }
1111
1112                 if (isset($data["notify"]) && isset($data["pubkey"])
1113                         && isset($data["poll"])
1114                         && isset($data["url"])
1115                 ) {
1116                         $data["network"] = NETWORK_OSTATUS;
1117                 } else {
1118                         return false;
1119                 }
1120                 // Fetch all additional data from the feed
1121                 $ret = z_fetch_url($data["poll"]);
1122                 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1123                         return false;
1124                 }
1125                 $feed = $ret['body'];
1126                 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1127                 if (!$feed_data) {
1128                         return false;
1129                 }
1130                 if ($feed_data["header"]["author-name"] != "") {
1131                         $data["name"] = $feed_data["header"]["author-name"];
1132                 }
1133                 if ($feed_data["header"]["author-nick"] != "") {
1134                         $data["nick"] = $feed_data["header"]["author-nick"];
1135                 }
1136                 if ($feed_data["header"]["author-avatar"] != "") {
1137                         $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1138                 }
1139                 if ($feed_data["header"]["author-id"] != "") {
1140                         $data["alias"] = $feed_data["header"]["author-id"];
1141                 }
1142                 if ($feed_data["header"]["author-location"] != "") {
1143                         $data["location"] = $feed_data["header"]["author-location"];
1144                 }
1145                 if ($feed_data["header"]["author-about"] != "") {
1146                         $data["about"] = $feed_data["header"]["author-about"];
1147                 }
1148                 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1149                 // So we take the value that we just fetched, although the other one worked as well
1150                 if ($feed_data["header"]["author-link"] != "") {
1151                         $data["url"] = $feed_data["header"]["author-link"];
1152                 }
1153                 /// @todo Fetch location and "about" from the feed as well
1154                 return $data;
1155         }
1156
1157         /**
1158          * @brief Fetch data from a pump.io profile page
1159          *
1160          * @param string $profile_link Link to the profile page
1161          *
1162          * @return array profile data
1163          */
1164         private function pumpioProfileData($profile_link) {
1165
1166                 $doc = new DOMDocument();
1167                 if (!@$doc->loadHTMLFile($profile_link)) {
1168                         return false;
1169                 }
1170
1171                 $xpath = new DomXPath($doc);
1172
1173                 $data = array();
1174
1175                 // This is ugly - but pump.io doesn't seem to know a better way for it
1176                 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1177                 $pos = strpos($data["name"], chr(10));
1178                 if ($pos) {
1179                         $data["name"] = trim(substr($data["name"], 0, $pos));
1180                 }
1181
1182                 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1183                 if ($avatar) {
1184                         foreach ($avatar->attributes as $attribute) {
1185                                 if ($attribute->name == "src") {
1186                                         $data["photo"] = trim($attribute->value);
1187                                 }
1188                         }
1189                 }
1190
1191                 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
1192                 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
1193
1194                 return $data;
1195         }
1196
1197         /**
1198          * @brief Check for pump.io contact
1199          *
1200          * @param array $webfinger Webfinger data
1201          *
1202          * @return array pump.io data
1203          */
1204         private function pumpio($webfinger) {
1205
1206                 $data = array();
1207                 foreach ($webfinger["links"] as $link) {
1208                         if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1209                                 && ($link["type"] == "text/html")
1210                                 && ($link["href"] != "")
1211                         ) {
1212                                 $data["url"] = $link["href"];
1213                         } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1214                                 $data["notify"] = $link["href"];
1215                         } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1216                                 $data["poll"] = $link["href"];
1217                         } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1218                                 $data["dialback"] = $link["href"];
1219                         }
1220                 }
1221                 if (isset($data["poll"]) && isset($data["notify"])
1222                         && isset($data["dialback"])
1223                         && isset($data["url"])
1224                 ) {
1225                         // by now we use these fields only for the network type detection
1226                         // So we unset all data that isn't used at the moment
1227                         unset($data["dialback"]);
1228
1229                         $data["network"] = NETWORK_PUMPIO;
1230                 } else {
1231                         return false;
1232                 }
1233
1234                 $profile_data = self::pumpioProfileData($data["url"]);
1235
1236                 if (!$profile_data) {
1237                         return false;
1238                 }
1239
1240                 $data = array_merge($data, $profile_data);
1241
1242                 return $data;
1243         }
1244
1245         /**
1246          * @brief Check page for feed link
1247          *
1248          * @param string $url Page link
1249          *
1250          * @return string feed link
1251          */
1252         private function getFeedLink($url) {
1253                 $doc = new DOMDocument();
1254
1255                 if (!@$doc->loadHTMLFile($url)) {
1256                         return false;
1257                 }
1258
1259                 $xpath = new DomXPath($doc);
1260
1261                 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1262                 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1263                 if (!is_object($feeds)) {
1264                         return false;
1265                 }
1266
1267                 if ($feeds->length == 0) {
1268                         return false;
1269                 }
1270
1271                 $feed_url = "";
1272
1273                 foreach ($feeds as $feed) {
1274                         $attr = array();
1275                         foreach ($feed->attributes as $attribute) {
1276                                 $attr[$attribute->name] = trim($attribute->value);
1277                         }
1278
1279                         if ($feed_url == "") {
1280                                 $feed_url = $attr["href"];
1281                         }
1282                 }
1283
1284                 return $feed_url;
1285         }
1286
1287         /**
1288          * @brief Check for feed contact
1289          *
1290          * @param string $url Profile link
1291          * @param boolean $probe Do a probe if the page contains a feed link
1292          *
1293          * @return array feed data
1294          */
1295         private function feed($url, $probe = true) {
1296                 $ret = z_fetch_url($url);
1297                 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1298                         return false;
1299                 }
1300                 $feed = $ret['body'];
1301                 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1302
1303                 if (!$feed_data) {
1304                         if (!$probe) {
1305                                 return false;
1306                         }
1307
1308                         $feed_url = self::getFeedLink($url);
1309
1310                         if (!$feed_url) {
1311                                 return false;
1312                         }
1313
1314                         return self::feed($feed_url, false);
1315                 }
1316
1317                 if ($feed_data["header"]["author-name"] != "") {
1318                         $data["name"] = $feed_data["header"]["author-name"];
1319                 }
1320
1321                 if ($feed_data["header"]["author-nick"] != "") {
1322                         $data["nick"] = $feed_data["header"]["author-nick"];
1323                 }
1324
1325                 if ($feed_data["header"]["author-avatar"] != "") {
1326                         $data["photo"] = $feed_data["header"]["author-avatar"];
1327                 }
1328
1329                 if ($feed_data["header"]["author-id"] != "") {
1330                         $data["alias"] = $feed_data["header"]["author-id"];
1331                 }
1332
1333                 $data["url"] = $url;
1334                 $data["poll"] = $url;
1335
1336                 if ($feed_data["header"]["author-link"] != "") {
1337                         $data["baseurl"] = $feed_data["header"]["author-link"];
1338                 } else {
1339                         $data["baseurl"] = $data["url"];
1340                 }
1341
1342                 $data["network"] = NETWORK_FEED;
1343
1344                 return $data;
1345         }
1346
1347         /**
1348          * @brief Check for mail contact
1349          *
1350          * @param string $uri Profile link
1351          * @param integer $uid User ID
1352          *
1353          * @return array mail data
1354          */
1355         private function mail($uri, $uid) {
1356
1357                 if (!validate_email($uri)) {
1358                         return false;
1359                 }
1360
1361                 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1362
1363                 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1364
1365                 if (dbm::is_result($x) && dbm::is_result($r)) {
1366                         $mailbox = construct_mailbox_name($r[0]);
1367                         $password = '';
1368                         openssl_private_decrypt(hex2bin($r[0]['pass']), $password, $x[0]['prvkey']);
1369                         $mbox = email_connect($mailbox, $r[0]['user'], $password);
1370                         if (!mbox) {
1371                                 return false;
1372                         }
1373                 }
1374
1375                 $msgs = email_poll($mbox, $uri);
1376                 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1377
1378                 if (!count($msgs)) {
1379                         return false;
1380                 }
1381
1382                 $phost = substr($uri, strpos($uri, '@') + 1);
1383
1384                 $data = array();
1385                 $data["addr"]    = $uri;
1386                 $data["network"] = NETWORK_MAIL;
1387                 $data["name"]    = substr($uri, 0, strpos($uri, '@'));
1388                 $data["nick"]    = $data["name"];
1389                 $data["photo"]   = avatar_img($uri);
1390                 $data["url"]     = 'http://'.$phost."/".$data["nick"];
1391                 $data["notify"]  = 'smtp '.random_string();
1392                 $data["poll"]    = 'email '.random_string();
1393
1394                 $x = email_msg_meta($mbox, $msgs[0]);
1395                 if (stristr($x[0]->from, $uri)) {
1396                         $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1397                 } elseif (stristr($x[0]->to, $uri)) {
1398                         $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1399                 }
1400                 if (isset($adr)) {
1401                         foreach ($adr as $feadr) {
1402                                 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1403                                         &&(strcasecmp($feadr->host, $phost) == 0)
1404                                         && (strlen($feadr->personal))
1405                                 ) {
1406                                         $personal = imap_mime_header_decode($feadr->personal);
1407                                         $data["name"] = "";
1408                                         foreach ($personal as $perspart) {
1409                                                 if ($perspart->charset != "default") {
1410                                                         $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1411                                                 } else {
1412                                                         $data["name"] .= $perspart->text;
1413                                                 }
1414                                         }
1415
1416                                         $data["name"] = notags($data["name"]);
1417                                 }
1418                         }
1419                 }
1420                 imap_close($mbox);
1421
1422                 return $data;
1423         }
1424
1425         /**
1426          * @brief Mix two paths together to possibly fix missing parts
1427          *
1428          * @param string $avatar Path to the avatar
1429          * @param string $base Another path that is hopefully complete
1430          *
1431          * @return string fixed avatar path
1432          */
1433         public static function fixAvatar($avatar, $base) {
1434                 $base_parts = parse_url($base);
1435
1436                 // Remove all parts that could create a problem
1437                 unset($base_parts['path']);
1438                 unset($base_parts['query']);
1439                 unset($base_parts['fragment']);
1440
1441                 $avatar_parts = parse_url($avatar);
1442
1443                 // Now we mix them
1444                 $parts = array_merge($base_parts, $avatar_parts);
1445
1446                 // And put them together again
1447                 $scheme   = isset($parts['scheme'])   ? $parts['scheme'] . '://' : '';
1448                 $host     = isset($parts['host'])     ? $parts['host']           : '';
1449                 $port     = isset($parts['port'])     ? ':' . $parts['port']     : '';
1450                 $path     = isset($parts['path'])     ? $parts['path']           : '';
1451                 $query    = isset($parts['query'])    ? '?' . $parts['query']    : '';
1452                 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
1453
1454                 $fixed = $scheme.$host.$port.$path.$query.$fragment;
1455
1456                 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);
1457
1458                 return $fixed;
1459         }
1460 }