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