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