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