]> git.mxchange.org Git - friendica.git/blob - include/Probe.php
Merge pull request #3281 from annando/issue-3206-2957
[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
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                 if (is_string($webfinger["subject"]) AND strstr($webfinger["subject"], "@"))
899                         $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
900
901                 $pubkey = "";
902                 foreach ($webfinger["links"] AS $link) {
903                         if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
904                                 ($link["type"] == "text/html") AND ($link["href"] != ""))
905                                 $data["url"] = $link["href"];
906                         elseif (($link["rel"] == "salmon") AND ($link["href"] != ""))
907                                 $data["notify"] = $link["href"];
908                         elseif (($link["rel"] == NAMESPACE_FEED) AND ($link["href"] != ""))
909                                 $data["poll"] = $link["href"];
910                         elseif (($link["rel"] == "magic-public-key") AND ($link["href"] != "")) {
911                                 $pubkey = $link["href"];
912
913                                 if (substr($pubkey, 0, 5) === 'data:') {
914                                         if (strstr($pubkey, ','))
915                                                 $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
916                                         else
917                                                 $pubkey = substr($pubkey, 5);
918                                 } elseif (normalise_link($pubkey) == 'http://') {
919                                         $ret = z_fetch_url($pubkey);
920                                         if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
921                                                 return false;
922                                         }
923                                         $pubkey = $ret['body'];
924                                 }
925
926                                 $key = explode(".", $pubkey);
927
928                                 if (sizeof($key) >= 3) {
929                                         $m = base64url_decode($key[1]);
930                                         $e = base64url_decode($key[2]);
931                                         $data["pubkey"] = metopem($m,$e);
932                                 }
933
934                         }
935                 }
936
937                 if (isset($data["notify"]) AND isset($data["pubkey"]) AND
938                         isset($data["poll"]) AND isset($data["url"])) {
939                         $data["network"] = NETWORK_OSTATUS;
940                 } else
941                         return false;
942
943                 // Fetch all additional data from the feed
944                 $ret = z_fetch_url($data["poll"]);
945                 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
946                         return false;
947                 }
948                 $feed = $ret['body'];
949                 $feed_data = feed_import($feed,$dummy1,$dummy2, $dummy3, true);
950                 if (!$feed_data)
951                         return false;
952
953                 if ($feed_data["header"]["author-name"] != "")
954                         $data["name"] = $feed_data["header"]["author-name"];
955
956                 if ($feed_data["header"]["author-nick"] != "")
957                         $data["nick"] = $feed_data["header"]["author-nick"];
958
959                 if ($feed_data["header"]["author-avatar"] != "")
960                         $data["photo"] = $feed_data["header"]["author-avatar"];
961
962                 if ($feed_data["header"]["author-id"] != "")
963                         $data["alias"] = $feed_data["header"]["author-id"];
964
965                 if ($feed_data["header"]["author-location"] != "")
966                         $data["location"] = $feed_data["header"]["author-location"];
967
968                 if ($feed_data["header"]["author-about"] != "")
969                         $data["about"] = $feed_data["header"]["author-about"];
970
971                 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
972                 // So we take the value that we just fetched, although the other one worked as well
973                 if ($feed_data["header"]["author-link"] != "")
974                         $data["url"] = $feed_data["header"]["author-link"];
975
976                 /// @todo Fetch location and "about" from the feed as well
977                 return $data;
978         }
979
980         /**
981          * @brief Fetch data from a pump.io profile page
982          *
983          * @param string $profile Link to the profile page
984          *
985          * @return array profile data
986          */
987         private function pumpio_profile_data($profile) {
988
989                 $doc = new DOMDocument();
990                 if (!@$doc->loadHTMLFile($profile))
991                         return false;
992
993                 $xpath = new DomXPath($doc);
994
995                 $data = array();
996
997                 // This is ugly - but pump.io doesn't seem to know a better way for it
998                 $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
999                 $pos = strpos($data["name"], chr(10));
1000                 if ($pos)
1001                         $data["name"] = trim(substr($data["name"], 0, $pos));
1002
1003                 $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1004                 if ($avatar)
1005                         foreach ($avatar->attributes as $attribute)
1006                                 if ($attribute->name == "src")
1007                                         $data["photo"] = trim($attribute->value);
1008
1009                 $data["location"] = $xpath->query("//p[@class='location']")->item(0)->nodeValue;
1010                 $data["about"] = $xpath->query("//p[@class='summary']")->item(0)->nodeValue;
1011
1012                 return $data;
1013         }
1014
1015         /**
1016          * @brief Check for pump.io contact
1017          *
1018          * @param array $webfinger Webfinger data
1019          *
1020          * @return array pump.io data
1021          */
1022         private function pumpio($webfinger) {
1023
1024                 $data = array();
1025                 foreach ($webfinger["links"] AS $link) {
1026                         if (($link["rel"] == "http://webfinger.net/rel/profile-page") AND
1027                                 ($link["type"] == "text/html") AND ($link["href"] != ""))
1028                                 $data["url"] = $link["href"];
1029                         elseif (($link["rel"] == "activity-inbox") AND ($link["href"] != ""))
1030                                 $data["notify"] = $link["href"];
1031                         elseif (($link["rel"] == "activity-outbox") AND ($link["href"] != ""))
1032                                 $data["poll"] = $link["href"];
1033                         elseif (($link["rel"] == "dialback") AND ($link["href"] != ""))
1034                                 $data["dialback"] = $link["href"];
1035                 }
1036                 if (isset($data["poll"]) AND isset($data["notify"]) AND
1037                         isset($data["dialback"]) AND isset($data["url"])) {
1038
1039                         // by now we use these fields only for the network type detection
1040                         // So we unset all data that isn't used at the moment
1041                         unset($data["dialback"]);
1042
1043                         $data["network"] = NETWORK_PUMPIO;
1044                 } else
1045                         return false;
1046
1047                 $profile_data = self::pumpio_profile_data($data["url"]);
1048
1049                 if (!$profile_data)
1050                         return false;
1051
1052                 $data = array_merge($data, $profile_data);
1053
1054                 return $data;
1055         }
1056
1057         /**
1058          * @brief Check page for feed link
1059          *
1060          * @param string $url Page link
1061          *
1062          * @return string feed link
1063          */
1064         private function get_feed_link($url) {
1065                 $doc = new DOMDocument();
1066
1067                 if (!@$doc->loadHTMLFile($url))
1068                         return false;
1069
1070                 $xpath = new DomXPath($doc);
1071
1072                 //$feeds = $xpath->query("/html/head/link[@type='application/rss+xml']");
1073                 $feeds = $xpath->query("/html/head/link[@type='application/rss+xml' and @rel='alternate']");
1074                 if (!is_object($feeds))
1075                         return false;
1076
1077                 if ($feeds->length == 0)
1078                         return false;
1079
1080                 $feed_url = "";
1081
1082                 foreach ($feeds AS $feed) {
1083                         $attr = array();
1084                         foreach ($feed->attributes as $attribute)
1085                         $attr[$attribute->name] = trim($attribute->value);
1086
1087                         if ($feed_url == "")
1088                                 $feed_url = $attr["href"];
1089                 }
1090
1091                 return $feed_url;
1092         }
1093
1094         /**
1095          * @brief Check for feed contact
1096          *
1097          * @param string $url Profile link
1098          * @param boolean $probe Do a probe if the page contains a feed link
1099          *
1100          * @return array feed data
1101          */
1102         private function feed($url, $probe = true) {
1103                 $ret = z_fetch_url($url);
1104                 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1105                         return false;
1106                 }
1107                 $feed = $ret['body'];
1108                 $feed_data = feed_import($feed, $dummy1, $dummy2, $dummy3, true);
1109
1110                 if (!$feed_data) {
1111                         if (!$probe)
1112                                 return false;
1113
1114                         $feed_url = self::get_feed_link($url);
1115
1116                         if (!$feed_url)
1117                                 return false;
1118
1119                         return self::feed($feed_url, false);
1120                 }
1121
1122                 if ($feed_data["header"]["author-name"] != "")
1123                         $data["name"] = $feed_data["header"]["author-name"];
1124
1125                 if ($feed_data["header"]["author-nick"] != "")
1126                         $data["nick"] = $feed_data["header"]["author-nick"];
1127
1128                 if ($feed_data["header"]["author-avatar"] != "")
1129                         $data["photo"] = $feed_data["header"]["author-avatar"];
1130
1131                 if ($feed_data["header"]["author-id"] != "")
1132                         $data["alias"] = $feed_data["header"]["author-id"];
1133
1134                 $data["url"] = $url;
1135                 $data["poll"] = $url;
1136
1137                 if ($feed_data["header"]["author-link"] != "")
1138                         $data["baseurl"] = $feed_data["header"]["author-link"];
1139                 else
1140                         $data["baseurl"] = $data["url"];
1141
1142                 $data["network"] = NETWORK_FEED;
1143
1144                 return $data;
1145         }
1146
1147         /**
1148          * @brief Check for mail contact
1149          *
1150          * @param string $uri Profile link
1151          * @param integer $uid User ID
1152          *
1153          * @return array mail data
1154          */
1155         private function mail($uri, $uid) {
1156
1157                 if (!validate_email($uri))
1158                         return false;
1159
1160                 $x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
1161
1162                 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid));
1163
1164                 if (dbm::is_result($x) && dbm::is_result($r)) {
1165                         $mailbox = construct_mailbox_name($r[0]);
1166                         $password = '';
1167                         openssl_private_decrypt(hex2bin($r[0]['pass']), $password,$x[0]['prvkey']);
1168                         $mbox = email_connect($mailbox,$r[0]['user'], $password);
1169                         if(!mbox)
1170                                 return false;
1171                 }
1172
1173                 $msgs = email_poll($mbox, $uri);
1174                 logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG);
1175
1176                 if (!count($msgs))
1177                         return false;
1178
1179                 $data = array();
1180
1181                 $data["addr"] = $uri;
1182                 $data["network"] = NETWORK_MAIL;
1183                 $data["name"] = substr($uri, 0, strpos($uri,'@'));
1184                 $data["nick"] = $data["name"];
1185                 $data["photo"] = avatar_img($uri);
1186
1187                 $phost = substr($uri, strpos($uri,'@') + 1);
1188                 $data["url"] = 'http://'.$phost."/".$data["nick"];
1189                 $data["notify"] = 'smtp '.random_string();
1190                 $data["poll"] = 'email '.random_string();
1191
1192                 $x = email_msg_meta($mbox, $msgs[0]);
1193                 if(stristr($x[0]->from, $uri))
1194                         $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1195                 elseif(stristr($x[0]->to, $uri))
1196                         $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1197                 if(isset($adr)) {
1198                         foreach($adr as $feadr) {
1199                                 if((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1200                                         &&(strcasecmp($feadr->host, $phost) == 0)
1201                                         && (strlen($feadr->personal))) {
1202
1203                                         $personal = imap_mime_header_decode($feadr->personal);
1204                                         $data["name"] = "";
1205                                         foreach($personal as $perspart)
1206                                                 if ($perspart->charset != "default")
1207                                                         $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1208                                                 else
1209                                                         $data["name"] .= $perspart->text;
1210
1211                                         $data["name"] = notags($data["name"]);
1212                                 }
1213                         }
1214                 }
1215                 imap_close($mbox);
1216
1217                 return $data;
1218         }
1219 }
1220 ?>