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