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