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