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