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