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