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