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