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