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