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