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