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