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