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