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