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