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