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