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