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