]> git.mxchange.org Git - friendica.git/blob - src/Network/Probe.php
60f085fb09e7a9bf67621394481e3ad9dcaae651
[friendica.git] / src / Network / Probe.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Network;
23
24 use DOMDocument;
25 use DomXPath;
26 use Friendica\Core\Cache\Duration;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
32 use Friendica\DI;
33 use Friendica\Model\Contact;
34 use Friendica\Model\GServer;
35 use Friendica\Model\Profile;
36 use Friendica\Protocol\ActivityNamespace;
37 use Friendica\Protocol\ActivityPub;
38 use Friendica\Protocol\Email;
39 use Friendica\Protocol\Feed;
40 use Friendica\Util\Crypto;
41 use Friendica\Util\Network;
42 use Friendica\Util\Strings;
43 use Friendica\Util\XML;
44
45 /**
46  * This class contain functions for probing URL
47  */
48 class Probe
49 {
50         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 = Network::curl($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], Logger::DEBUG);
181                         self::$istimeout = true;
182                         return [];
183                 }
184
185                 if (!is_object($xrd) && !empty($url)) {
186                         $curlResult = Network::curl($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], Logger::DEBUG);
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::log("No xrd object found for ".$host, Logger::DEBUG);
203                         return [];
204                 }
205
206                 $links = XML::elementToArray($xrd);
207                 if (!isset($links["xrd"]["link"])) {
208                         Logger::log("No xrd data found for ".$host, Logger::DEBUG);
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::log("Probing successful for ".$host, Logger::DEBUG);
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::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA);
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::log("No webfinger links found for ".$uri, Logger::DEBUG);
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, !$cache);
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 = Network::curl($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 ($parts['host'] == '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 (strpos($uri, '@twitter.com')) {
710                                 return self::twitter($uri);
711                         }
712                 } else {
713                         Logger::info('URI was not detectable', ['uri' => $uri]);
714                         return [];
715                 }
716
717                 Logger::info('Probing start', ['uri' => $uri]);
718
719                 $data = self::getWebfingerArray($uri);
720                 if (empty($data)) {
721                         if (!empty($parts['scheme'])) {
722                                 return self::feed($uri);
723                         } elseif (!empty($uid)) {
724                                 return self::mail($uri, $uid);
725                         } else {
726                                 return [];
727                         }
728                 }
729
730                 $webfinger = $data['webfinger'];
731                 $nick = $data['nick'] ?? '';
732                 $addr = $data['addr'] ?? '';
733                 $baseurl = $data['baseurl'] ?? '';
734
735                 $result = [];
736
737                 if (in_array($network, ["", Protocol::DFRN])) {
738                         $result = self::dfrn($webfinger);
739                 }
740                 if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
741                         $result = self::diaspora($webfinger);
742                 }
743                 if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
744                         $result = self::ostatus($webfinger);
745                 }
746                 if (in_array($network, ['', Protocol::ZOT])) {
747                         $result = self::zot($webfinger, $result, $baseurl);
748                 }
749                 if ((!$result && ($network == "")) || ($network == Protocol::PUMPIO)) {
750                         $result = self::pumpio($webfinger, $addr);
751                 }
752
753                 if (empty($result['network']) && empty($ap_profile['network']) || ($network == Protocol::FEED)) {
754                         $result = self::feed($uri);
755                 } else {
756                         // We overwrite the detected nick with our try if the previois routines hadn't detected it.
757                         // Additionally it is overwritten when the nickname doesn't make sense (contains spaces).
758                         if ((empty($result["nick"]) || (strstr($result["nick"], " "))) && ($nick != "")) {
759                                 $result["nick"] = $nick;
760                         }
761
762                         if (empty($result["addr"]) && ($addr != "")) {
763                                 $result["addr"] = $addr;
764                         }
765                 }
766
767                 $result = self::getSubscribeLink($result, $webfinger);
768
769                 if (empty($result["network"])) {
770                         $result["network"] = Protocol::PHANTOM;
771                 }
772
773                 if (empty($result['baseurl']) && !empty($baseurl)) {
774                         $result['baseurl'] = $baseurl;
775                 }
776
777                 if (empty($result["url"])) {
778                         $result["url"] = $uri;
779                 }
780
781                 Logger::info('Probing done', ['uri' => $uri, 'network' => $result["network"]]);
782
783                 return $result;
784         }
785
786         /**
787          * Check for Zot contact
788          *
789          * @param array $webfinger Webfinger data
790          * @param array $data      previously probed data
791          *
792          * @return array Zot data
793          * @throws HTTPException\InternalServerErrorException
794          */
795         private static function zot($webfinger, $data, $baseurl)
796         {
797                 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
798                         foreach ($webfinger["aliases"] as $alias) {
799                                 if (substr($alias, 0, 5) == 'acct:') {
800                                         $data["addr"] = substr($alias, 5);
801                                 }
802                         }
803                 }
804
805                 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
806                         $data["addr"] = substr($webfinger["subject"], 5);
807                 }
808
809                 $zot_url = '';
810                 foreach ($webfinger['links'] as $link) {
811                         if (($link['rel'] == 'http://purl.org/zot/protocol') && !empty($link['href'])) {
812                                 $zot_url = $link['href'];
813                         }
814                 }
815
816                 if (empty($zot_url) && !empty($data['addr']) && !empty($baseurl)) {
817                         $condition = ['nurl' => Strings::normaliseLink($baseurl), 'platform' => ['hubzilla']];
818                         if (!DBA::exists('gserver', $condition)) {
819                                 return $data;
820                         }
821                         $zot_url = $baseurl . '/.well-known/zot-info?address=' . $data['addr'];
822                 }
823
824                 if (empty($zot_url)) {
825                         return $data;
826                 }
827
828                 $data = self::pollZot($zot_url, $data);
829
830                 if (!empty($data['url']) && !empty($webfinger['aliases']) && is_array($webfinger['aliases'])) {
831                         foreach ($webfinger['aliases'] as $alias) {
832                                 if (!strstr($alias, '@') && Strings::normaliseLink($alias) != Strings::normaliseLink($data['url'])) {
833                                         $data['alias'] = $alias;
834                                 }
835                         }
836                 }
837
838                 return $data;
839         }
840
841         public static function pollZot($url, $data)
842         {
843                 $curlResult = Network::curl($url);
844                 if ($curlResult->isTimeout()) {
845                         return $data;
846                 }
847                 $content = $curlResult->getBody();
848                 if (!$content) {
849                         return $data;
850                 }
851
852                 $json = json_decode($content, true);
853                 if (!is_array($json)) {
854                         return $data;
855                 }
856
857                 if (empty($data['network'])) {
858                         if (!empty($json['protocols']) && in_array('zot', $json['protocols'])) {
859                                 $data['network'] = Protocol::ZOT;
860                         } elseif (!isset($json['protocols'])) {
861                                 $data['network'] = Protocol::ZOT;
862                         }
863                 }
864
865                 if (!empty($json['guid']) && empty($data['guid'])) {
866                         $data['guid'] = $json['guid'];
867                 }
868                 if (!empty($json['key']) && empty($data['pubkey'])) {
869                         $data['pubkey'] = $json['key'];
870                 }
871                 if (!empty($json['name'])) {
872                         $data['name'] = $json['name'];
873                 }
874                 if (!empty($json['photo'])) {
875                         $data['photo'] = $json['photo'];
876                         if (!empty($json['photo_updated'])) {
877                                 $data['photo'] .= '?rev=' . urlencode($json['photo_updated']);
878                         }
879                 }
880                 if (!empty($json['address'])) {
881                         $data['addr'] = $json['address'];
882                 }
883                 if (!empty($json['url'])) {
884                         $data['url'] = $json['url'];
885                 }
886                 if (!empty($json['connections_url'])) {
887                         $data['poco'] = $json['connections_url'];
888                 }
889                 if (isset($json['searchable'])) {
890                         $data['hide'] = !$json['searchable'];
891                 }
892                 if (!empty($json['public_forum'])) {
893                         $data['community'] = $json['public_forum'];
894                         $data['account-type'] = Contact::PAGE_COMMUNITY;
895                 }
896
897                 if (!empty($json['profile'])) {
898                         $profile = $json['profile'];
899                         if (!empty($profile['description'])) {
900                                 $data['about'] = $profile['description'];
901                         }
902                         if (!empty($profile['keywords'])) {
903                                 $keywords = implode(', ', $profile['keywords']);
904                                 if (!empty($keywords)) {
905                                         $data['keywords'] = $keywords;
906                                 }
907                         }
908
909                         $loc = [];
910                         if (!empty($profile['region'])) {
911                                 $loc['region'] = $profile['region'];
912                         }
913                         if (!empty($profile['country'])) {
914                                 $loc['country-name'] = $profile['country'];
915                         }
916                         $location = Profile::formatLocation($loc);
917                         if (!empty($location)) {
918                                 $data['location'] = $location;
919                         }
920                 }
921
922                 return $data;
923         }
924
925         /**
926          * Perform a webfinger request.
927          *
928          * For details see RFC 7033: <https://tools.ietf.org/html/rfc7033>
929          *
930          * @param string $url  Address that should be probed
931          * @param string $type type
932          *
933          * @return array webfinger data
934          * @throws HTTPException\InternalServerErrorException
935          */
936         public static function webfinger($url, $type)
937         {
938                 $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
939
940                 $curlResult = Network::curl($url, false, ['timeout' => $xrd_timeout, 'accept_content' => $type]);
941                 if ($curlResult->isTimeout()) {
942                         self::$istimeout = true;
943                         return [];
944                 }
945                 $data = $curlResult->getBody();
946
947                 $webfinger = json_decode($data, true);
948                 if (!empty($webfinger)) {
949                         if (!isset($webfinger["links"])) {
950                                 Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
951                                 return [];
952                         }
953                         return $webfinger;
954                 }
955
956                 // If it is not JSON, maybe it is XML
957                 $xrd = XML::parseString($data, true);
958                 if (!is_object($xrd)) {
959                         Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
960                         return [];
961                 }
962
963                 $xrd_arr = XML::elementToArray($xrd);
964                 if (!isset($xrd_arr["xrd"]["link"])) {
965                         Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
966                         return [];
967                 }
968
969                 $webfinger = [];
970
971                 if (!empty($xrd_arr["xrd"]["subject"])) {
972                         $webfinger["subject"] = $xrd_arr["xrd"]["subject"];
973                 }
974
975                 if (!empty($xrd_arr["xrd"]["alias"])) {
976                         $webfinger["aliases"] = $xrd_arr["xrd"]["alias"];
977                 }
978
979                 $webfinger["links"] = [];
980
981                 foreach ($xrd_arr["xrd"]["link"] as $value => $data) {
982                         if (!empty($data["@attributes"])) {
983                                 $attributes = $data["@attributes"];
984                         } elseif ($value == "@attributes") {
985                                 $attributes = $data;
986                         } else {
987                                 continue;
988                         }
989
990                         $webfinger["links"][] = $attributes;
991                 }
992                 return $webfinger;
993         }
994
995         /**
996          * Poll the Friendica specific noscrape page.
997          *
998          * "noscrape" is a faster alternative to fetch the data from the hcard.
999          * This functionality was originally created for the directory.
1000          *
1001          * @param string $noscrape_url Link to the noscrape page
1002          * @param array  $data         The already fetched data
1003          *
1004          * @return array noscrape data
1005          * @throws HTTPException\InternalServerErrorException
1006          */
1007         private static function pollNoscrape($noscrape_url, $data)
1008         {
1009                 $curlResult = Network::curl($noscrape_url);
1010                 if ($curlResult->isTimeout()) {
1011                         self::$istimeout = true;
1012                         return [];
1013                 }
1014                 $content = $curlResult->getBody();
1015                 if (!$content) {
1016                         Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
1017                         return [];
1018                 }
1019
1020                 $json = json_decode($content, true);
1021                 if (!is_array($json)) {
1022                         Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
1023                         return [];
1024                 }
1025
1026                 if (!empty($json["fn"])) {
1027                         $data["name"] = $json["fn"];
1028                 }
1029
1030                 if (!empty($json["addr"])) {
1031                         $data["addr"] = $json["addr"];
1032                 }
1033
1034                 if (!empty($json["nick"])) {
1035                         $data["nick"] = $json["nick"];
1036                 }
1037
1038                 if (!empty($json["guid"])) {
1039                         $data["guid"] = $json["guid"];
1040                 }
1041
1042                 if (!empty($json["comm"])) {
1043                         $data["community"] = $json["comm"];
1044                 }
1045
1046                 if (!empty($json["tags"])) {
1047                         $keywords = implode(", ", $json["tags"]);
1048                         if ($keywords != "") {
1049                                 $data["keywords"] = $keywords;
1050                         }
1051                 }
1052
1053                 $location = Profile::formatLocation($json);
1054                 if ($location) {
1055                         $data["location"] = $location;
1056                 }
1057
1058                 if (!empty($json["about"])) {
1059                         $data["about"] = $json["about"];
1060                 }
1061
1062                 if (!empty($json["key"])) {
1063                         $data["pubkey"] = $json["key"];
1064                 }
1065
1066                 if (!empty($json["photo"])) {
1067                         $data["photo"] = $json["photo"];
1068                 }
1069
1070                 if (!empty($json["dfrn-request"])) {
1071                         $data["request"] = $json["dfrn-request"];
1072                 }
1073
1074                 if (!empty($json["dfrn-confirm"])) {
1075                         $data["confirm"] = $json["dfrn-confirm"];
1076                 }
1077
1078                 if (!empty($json["dfrn-notify"])) {
1079                         $data["notify"] = $json["dfrn-notify"];
1080                 }
1081
1082                 if (!empty($json["dfrn-poll"])) {
1083                         $data["poll"] = $json["dfrn-poll"];
1084                 }
1085
1086                 if (isset($json["hide"])) {
1087                         $data["hide"] = (bool)$json["hide"];
1088                 } else {
1089                         $data["hide"] = false;
1090                 }
1091
1092                 return $data;
1093         }
1094
1095         /**
1096          * Check for valid DFRN data
1097          *
1098          * @param array $data DFRN data
1099          *
1100          * @return int Number of errors
1101          */
1102         public static function validDfrn($data)
1103         {
1104                 $errors = 0;
1105                 if (!isset($data['key'])) {
1106                         $errors ++;
1107                 }
1108                 if (!isset($data['dfrn-request'])) {
1109                         $errors ++;
1110                 }
1111                 if (!isset($data['dfrn-confirm'])) {
1112                         $errors ++;
1113                 }
1114                 if (!isset($data['dfrn-notify'])) {
1115                         $errors ++;
1116                 }
1117                 if (!isset($data['dfrn-poll'])) {
1118                         $errors ++;
1119                 }
1120                 return $errors;
1121         }
1122
1123         /**
1124          * Fetch data from a DFRN profile page and via "noscrape"
1125          *
1126          * @param string $profile_link Link to the profile page
1127          *
1128          * @return array profile data
1129          * @throws HTTPException\InternalServerErrorException
1130          * @throws \ImagickException
1131          */
1132         public static function profile($profile_link)
1133         {
1134                 $data = [];
1135
1136                 Logger::log("Check profile ".$profile_link, Logger::DEBUG);
1137
1138                 // Fetch data via noscrape - this is faster
1139                 $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
1140                 $data = self::pollNoscrape($noscrape_url, $data);
1141
1142                 if (!isset($data["notify"])
1143                         || !isset($data["confirm"])
1144                         || !isset($data["request"])
1145                         || !isset($data["poll"])
1146                         || !isset($data["name"])
1147                         || !isset($data["photo"])
1148                 ) {
1149                         $data = self::pollHcard($profile_link, $data, true);
1150                 }
1151
1152                 $prof_data = [];
1153
1154                 if (empty($data["addr"]) || empty($data["nick"])) {
1155                         $probe_data = self::uri($profile_link);
1156                         $data["addr"] = ($data["addr"] ?? '') ?: $probe_data["addr"];
1157                         $data["nick"] = ($data["nick"] ?? '') ?: $probe_data["nick"];
1158                 }
1159
1160                 $prof_data["addr"]         = $data["addr"];
1161                 $prof_data["nick"]         = $data["nick"];
1162                 $prof_data["dfrn-request"] = $data['request'] ?? null;
1163                 $prof_data["dfrn-confirm"] = $data['confirm'] ?? null;
1164                 $prof_data["dfrn-notify"]  = $data['notify']  ?? null;
1165                 $prof_data["dfrn-poll"]    = $data['poll']    ?? null;
1166                 $prof_data["photo"]        = $data['photo']   ?? null;
1167                 $prof_data["fn"]           = $data['name']    ?? null;
1168                 $prof_data["key"]          = $data['pubkey']  ?? null;
1169
1170                 Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
1171
1172                 return $prof_data;
1173         }
1174
1175         /**
1176          * Check for DFRN contact
1177          *
1178          * @param array $webfinger Webfinger data
1179          *
1180          * @return array DFRN data
1181          * @throws HTTPException\InternalServerErrorException
1182          */
1183         private static function dfrn($webfinger)
1184         {
1185                 $hcard_url = "";
1186                 $data = [];
1187                 // The array is reversed to take into account the order of preference for same-rel links
1188                 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1189                 foreach (array_reverse($webfinger["links"]) as $link) {
1190                         if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) {
1191                                 $data["network"] = Protocol::DFRN;
1192                         } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1193                                 $data["poll"] = $link["href"];
1194                         } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1195                                 $data["url"] = $link["href"];
1196                         } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1197                                 $hcard_url = $link["href"];
1198                         } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1199                                 $data["poco"] = $link["href"];
1200                         } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) {
1201                                 $data["photo"] = $link["href"];
1202                         } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1203                                 $data["baseurl"] = trim($link["href"], '/');
1204                         } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1205                                 $data["guid"] = $link["href"];
1206                         } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1207                                 $data["pubkey"] = base64_decode($link["href"]);
1208
1209                                 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1210                                 if (strstr($data["pubkey"], 'RSA ')) {
1211                                         $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1212                                 }
1213                         }
1214                 }
1215
1216                 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1217                         foreach ($webfinger["aliases"] as $alias) {
1218                                 if (empty($data["url"]) && !strstr($alias, "@")) {
1219                                         $data["url"] = $alias;
1220                                 } elseif (!strstr($alias, "@") && Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"])) {
1221                                         $data["alias"] = $alias;
1222                                 } elseif (substr($alias, 0, 5) == 'acct:') {
1223                                         $data["addr"] = substr($alias, 5);
1224                                 }
1225                         }
1226                 }
1227
1228                 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == "acct:")) {
1229                         $data["addr"] = substr($webfinger["subject"], 5);
1230                 }
1231
1232                 if (!isset($data["network"]) || ($hcard_url == "")) {
1233                         return [];
1234                 }
1235
1236                 // Fetch data via noscrape - this is faster
1237                 $noscrape_url = str_replace("/hcard/", "/noscrape/", $hcard_url);
1238                 $data = self::pollNoscrape($noscrape_url, $data);
1239
1240                 if (isset($data["notify"])
1241                         && isset($data["confirm"])
1242                         && isset($data["request"])
1243                         && isset($data["poll"])
1244                         && isset($data["name"])
1245                         && isset($data["photo"])
1246                 ) {
1247                         return $data;
1248                 }
1249
1250                 $data = self::pollHcard($hcard_url, $data, true);
1251
1252                 return $data;
1253         }
1254
1255         /**
1256          * Poll the hcard page (Diaspora and Friendica specific)
1257          *
1258          * @param string  $hcard_url Link to the hcard page
1259          * @param array   $data      The already fetched data
1260          * @param boolean $dfrn      Poll DFRN specific data
1261          *
1262          * @return array hcard data
1263          * @throws HTTPException\InternalServerErrorException
1264          */
1265         private static function pollHcard($hcard_url, $data, $dfrn = false)
1266         {
1267                 $curlResult = Network::curl($hcard_url);
1268                 if ($curlResult->isTimeout()) {
1269                         self::$istimeout = true;
1270                         return [];
1271                 }
1272                 $content = $curlResult->getBody();
1273                 if (!$content) {
1274                         return [];
1275                 }
1276
1277                 $doc = new DOMDocument();
1278                 if (!@$doc->loadHTML($content)) {
1279                         return [];
1280                 }
1281
1282                 $xpath = new DomXPath($doc);
1283
1284                 $vcards = $xpath->query("//div[contains(concat(' ', @class, ' '), ' vcard ')]");
1285                 if (!is_object($vcards)) {
1286                         return [];
1287                 }
1288
1289                 if (!isset($data["baseurl"])) {
1290                         $data["baseurl"] = "";
1291                 }
1292
1293                 if ($vcards->length > 0) {
1294                         $vcard = $vcards->item(0);
1295
1296                         // We have to discard the guid from the hcard in favour of the guid from lrdd
1297                         // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
1298                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
1299                         if (($search->length > 0) && empty($data["guid"])) {
1300                                 $data["guid"] = $search->item(0)->nodeValue;
1301                         }
1302
1303                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
1304                         if ($search->length > 0) {
1305                                 $data["nick"] = $search->item(0)->nodeValue;
1306                         }
1307
1308                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
1309                         if ($search->length > 0) {
1310                                 $data["name"] = $search->item(0)->nodeValue;
1311                         }
1312
1313                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
1314                         if ($search->length > 0) {
1315                                 $data["searchable"] = $search->item(0)->nodeValue;
1316                         }
1317
1318                         $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
1319                         if ($search->length > 0) {
1320                                 $data["pubkey"] = $search->item(0)->nodeValue;
1321                                 if (strstr($data["pubkey"], 'RSA ')) {
1322                                         $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1323                                 }
1324                         }
1325
1326                         $search = $xpath->query("//*[@id='pod_location']", $vcard); // */
1327                         if ($search->length > 0) {
1328                                 $data["baseurl"] = trim($search->item(0)->nodeValue, "/");
1329                         }
1330                 }
1331
1332                 $avatar = [];
1333                 if (!empty($vcard)) {
1334                         $photos = $xpath->query("//*[contains(concat(' ', @class, ' '), ' photo ') or contains(concat(' ', @class, ' '), ' avatar ')]", $vcard); // */
1335                         foreach ($photos as $photo) {
1336                                 $attr = [];
1337                                 foreach ($photo->attributes as $attribute) {
1338                                         $attr[$attribute->name] = trim($attribute->value);
1339                                 }
1340
1341                                 if (isset($attr["src"]) && isset($attr["width"])) {
1342                                         $avatar[$attr["width"]] = $attr["src"];
1343                                 }
1344
1345                                 // We don't have a width. So we just take everything that we got.
1346                                 // This is a Hubzilla workaround which doesn't send a width.
1347                                 if ((sizeof($avatar) == 0) && !empty($attr["src"])) {
1348                                         $avatar[] = $attr["src"];
1349                                 }
1350                         }
1351                 }
1352
1353                 if (sizeof($avatar)) {
1354                         ksort($avatar);
1355                         $data["photo"] = self::fixAvatar(array_pop($avatar), $data["baseurl"]);
1356                 }
1357
1358                 if ($dfrn) {
1359                         // Poll DFRN specific data
1360                         $search = $xpath->query("//link[contains(concat(' ', @rel), ' dfrn-')]");
1361                         if ($search->length > 0) {
1362                                 foreach ($search as $link) {
1363                                         //$data["request"] = $search->item(0)->nodeValue;
1364                                         $attr = [];
1365                                         foreach ($link->attributes as $attribute) {
1366                                                 $attr[$attribute->name] = trim($attribute->value);
1367                                         }
1368
1369                                         $data[substr($attr["rel"], 5)] = $attr["href"];
1370                                 }
1371                         }
1372
1373                         // Older Friendica versions had used the "uid" field differently than newer versions
1374                         if (!empty($data["nick"]) && !empty($data["guid"]) && ($data["nick"] == $data["guid"])) {
1375                                 unset($data["guid"]);
1376                         }
1377                 }
1378
1379
1380                 return $data;
1381         }
1382
1383         /**
1384          * Check for Diaspora contact
1385          *
1386          * @param array $webfinger Webfinger data
1387          *
1388          * @return array Diaspora data
1389          * @throws HTTPException\InternalServerErrorException
1390          */
1391         private static function diaspora($webfinger)
1392         {
1393                 $hcard_url = "";
1394                 $data = [];
1395
1396                 // The array is reversed to take into account the order of preference for same-rel links
1397                 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1398                 foreach (array_reverse($webfinger["links"]) as $link) {
1399                         if (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) {
1400                                 $hcard_url = $link["href"];
1401                         } elseif (($link["rel"] == "http://joindiaspora.com/seed_location") && !empty($link["href"])) {
1402                                 $data["baseurl"] = trim($link["href"], '/');
1403                         } elseif (($link["rel"] == "http://joindiaspora.com/guid") && !empty($link["href"])) {
1404                                 $data["guid"] = $link["href"];
1405                         } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) {
1406                                 $data["url"] = $link["href"];
1407                         } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1408                                 $data["poll"] = $link["href"];
1409                         } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) {
1410                                 $data["poco"] = $link["href"];
1411                         } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1412                                 $data["notify"] = $link["href"];
1413                         } elseif (($link["rel"] == "diaspora-public-key") && !empty($link["href"])) {
1414                                 $data["pubkey"] = base64_decode($link["href"]);
1415
1416                                 //if (strstr($data["pubkey"], 'RSA ') || ($link["type"] == "RSA"))
1417                                 if (strstr($data["pubkey"], 'RSA ')) {
1418                                         $data["pubkey"] = Crypto::rsaToPem($data["pubkey"]);
1419                                 }
1420                         }
1421                 }
1422
1423                 if (empty($data["url"]) || empty($hcard_url)) {
1424                         return [];
1425                 }
1426
1427                 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1428                         foreach ($webfinger["aliases"] as $alias) {
1429                                 if (Strings::normaliseLink($alias) != Strings::normaliseLink($data["url"]) && ! strstr($alias, "@")) {
1430                                         $data["alias"] = $alias;
1431                                 } elseif (substr($alias, 0, 5) == 'acct:') {
1432                                         $data["addr"] = substr($alias, 5);
1433                                 }
1434                         }
1435                 }
1436
1437                 if (!empty($webfinger["subject"]) && (substr($webfinger["subject"], 0, 5) == 'acct:')) {
1438                         $data["addr"] = substr($webfinger["subject"], 5);
1439                 }
1440
1441                 // Fetch further information from the hcard
1442                 $data = self::pollHcard($hcard_url, $data);
1443
1444                 if (!$data) {
1445                         return [];
1446                 }
1447
1448                 if (!empty($data["url"])
1449                         && !empty($data["guid"])
1450                         && !empty($data["baseurl"])
1451                         && !empty($data["pubkey"])
1452                         && !empty($hcard_url)
1453                 ) {
1454                         $data["network"] = Protocol::DIASPORA;
1455
1456                         // The Diaspora handle must always be lowercase
1457                         if (!empty($data["addr"])) {
1458                                 $data["addr"] = strtolower($data["addr"]);
1459                         }
1460
1461                         // We have to overwrite the detected value for "notify" since Hubzilla doesn't send it
1462                         $data["notify"] = $data["baseurl"] . "/receive/users/" . $data["guid"];
1463                         $data["batch"]  = $data["baseurl"] . "/receive/public";
1464                 } else {
1465                         return [];
1466                 }
1467
1468                 return $data;
1469         }
1470
1471         /**
1472          * Check for OStatus contact
1473          *
1474          * @param array $webfinger Webfinger data
1475          * @param bool  $short     Short detection mode
1476          *
1477          * @return array|bool OStatus data or "false" on error or "true" on short mode
1478          * @throws HTTPException\InternalServerErrorException
1479          */
1480         private static function ostatus($webfinger, $short = false)
1481         {
1482                 $data = [];
1483
1484                 if (!empty($webfinger["aliases"]) && is_array($webfinger["aliases"])) {
1485                         foreach ($webfinger["aliases"] as $alias) {
1486                                 if (strstr($alias, "@") && !strstr(Strings::normaliseLink($alias), "http://")) {
1487                                         $data["addr"] = str_replace('acct:', '', $alias);
1488                                 }
1489                         }
1490                 }
1491
1492                 if (!empty($webfinger["subject"]) && strstr($webfinger["subject"], "@")
1493                         && !strstr(Strings::normaliseLink($webfinger["subject"]), "http://")
1494                 ) {
1495                         $data["addr"] = str_replace('acct:', '', $webfinger["subject"]);
1496                 }
1497
1498                 if (!empty($webfinger["links"])) {
1499                         // The array is reversed to take into account the order of preference for same-rel links
1500                         // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1501                         foreach (array_reverse($webfinger["links"]) as $link) {
1502                                 if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1503                                         && (($link["type"] ?? "") == "text/html")
1504                                         && ($link["href"] != "")
1505                                 ) {
1506                                         $data["url"] = $data["alias"] = $link["href"];
1507                                 } elseif (($link["rel"] == "salmon") && !empty($link["href"])) {
1508                                         $data["notify"] = $link["href"];
1509                                 } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) {
1510                                         $data["poll"] = $link["href"];
1511                                 } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) {
1512                                         $pubkey = $link["href"];
1513
1514                                         if (substr($pubkey, 0, 5) === 'data:') {
1515                                                 if (strstr($pubkey, ',')) {
1516                                                         $pubkey = substr($pubkey, strpos($pubkey, ',') + 1);
1517                                                 } else {
1518                                                         $pubkey = substr($pubkey, 5);
1519                                                 }
1520                                         } elseif (Strings::normaliseLink($pubkey) == 'http://') {
1521                                                 $curlResult = Network::curl($pubkey);
1522                                                 if ($curlResult->isTimeout()) {
1523                                                         self::$istimeout = true;
1524                                                         return $short ? false : [];
1525                                                 }
1526                                                 $pubkey = $curlResult->getBody();
1527                                         }
1528
1529                                         $key = explode(".", $pubkey);
1530
1531                                         if (sizeof($key) >= 3) {
1532                                                 $m = Strings::base64UrlDecode($key[1]);
1533                                                 $e = Strings::base64UrlDecode($key[2]);
1534                                                 $data["pubkey"] = Crypto::meToPem($m, $e);
1535                                         }
1536                                 }
1537                         }
1538                 }
1539
1540                 if (isset($data["notify"]) && isset($data["pubkey"])
1541                         && isset($data["poll"])
1542                         && isset($data["url"])
1543                 ) {
1544                         $data["network"] = Protocol::OSTATUS;
1545                 } else {
1546                         return $short ? false : [];
1547                 }
1548
1549                 if ($short) {
1550                         return true;
1551                 }
1552
1553                 // Fetch all additional data from the feed
1554                 $curlResult = Network::curl($data["poll"]);
1555                 if ($curlResult->isTimeout()) {
1556                         self::$istimeout = true;
1557                         return [];
1558                 }
1559                 $feed = $curlResult->getBody();
1560                 $feed_data = Feed::import($feed);
1561                 if (!$feed_data) {
1562                         return [];
1563                 }
1564
1565                 if (!empty($feed_data["header"]["author-name"])) {
1566                         $data["name"] = $feed_data["header"]["author-name"];
1567                 }
1568                 if (!empty($feed_data["header"]["author-nick"])) {
1569                         $data["nick"] = $feed_data["header"]["author-nick"];
1570                 }
1571                 if (!empty($feed_data["header"]["author-avatar"])) {
1572                         $data["photo"] = self::fixAvatar($feed_data["header"]["author-avatar"], $data["url"]);
1573                 }
1574                 if (!empty($feed_data["header"]["author-id"])) {
1575                         $data["alias"] = $feed_data["header"]["author-id"];
1576                 }
1577                 if (!empty($feed_data["header"]["author-location"])) {
1578                         $data["location"] = $feed_data["header"]["author-location"];
1579                 }
1580                 if (!empty($feed_data["header"]["author-about"])) {
1581                         $data["about"] = $feed_data["header"]["author-about"];
1582                 }
1583                 // OStatus has serious issues when the the url doesn't fit (ssl vs. non ssl)
1584                 // So we take the value that we just fetched, although the other one worked as well
1585                 if (!empty($feed_data["header"]["author-link"])) {
1586                         $data["url"] = $feed_data["header"]["author-link"];
1587                 }
1588
1589                 if ($data["url"] == $data["alias"]) {
1590                         $data["alias"] = '';
1591                 }
1592
1593                 /// @todo Fetch location and "about" from the feed as well
1594                 return $data;
1595         }
1596
1597         /**
1598          * Fetch data from a pump.io profile page
1599          *
1600          * @param string $profile_link Link to the profile page
1601          *
1602          * @return array profile data
1603          */
1604         private static function pumpioProfileData($profile_link)
1605         {
1606                 $curlResult = Network::curl($profile_link);
1607                 if (!$curlResult->isSuccess()) {
1608                         return [];
1609                 }
1610
1611                 $doc = new DOMDocument();
1612                 if (!@$doc->loadHTML($curlResult->getBody())) {
1613                         return [];
1614                 }
1615
1616                 $xpath = new DomXPath($doc);
1617
1618                 $data = [];
1619
1620                 $data["name"] = $xpath->query("//span[contains(@class, 'p-name')]")->item(0)->nodeValue;
1621
1622                 if ($data["name"] == '') {
1623                         // This is ugly - but pump.io doesn't seem to know a better way for it
1624                         $data["name"] = trim($xpath->query("//h1[@class='media-header']")->item(0)->nodeValue);
1625                         $pos = strpos($data["name"], chr(10));
1626                         if ($pos) {
1627                                 $data["name"] = trim(substr($data["name"], 0, $pos));
1628                         }
1629                 }
1630
1631                 $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-locality')]");
1632
1633                 if ($data["location"] == '') {
1634                         $data["location"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'location')]");
1635                 }
1636
1637                 $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'p-note')]");
1638
1639                 if ($data["about"] == '') {
1640                         $data["about"] = XML::getFirstNodeValue($xpath, "//p[contains(@class, 'summary')]");
1641                 }
1642
1643                 $avatar = $xpath->query("//img[contains(@class, 'u-photo')]")->item(0);
1644                 if (!$avatar) {
1645                         $avatar = $xpath->query("//img[@class='img-rounded media-object']")->item(0);
1646                 }
1647                 if ($avatar) {
1648                         foreach ($avatar->attributes as $attribute) {
1649                                 if ($attribute->name == "src") {
1650                                         $data["photo"] = trim($attribute->value);
1651                                 }
1652                         }
1653                 }
1654
1655                 return $data;
1656         }
1657
1658         /**
1659          * Check for pump.io contact
1660          *
1661          * @param array  $webfinger Webfinger data
1662          * @param string $addr
1663          * @return array pump.io data
1664          */
1665         private static function pumpio($webfinger, $addr)
1666         {
1667                 $data = [];
1668                 // The array is reversed to take into account the order of preference for same-rel links
1669                 // See: https://tools.ietf.org/html/rfc7033#section-4.4.4
1670                 foreach (array_reverse($webfinger["links"]) as $link) {
1671                         if (($link["rel"] == "http://webfinger.net/rel/profile-page")
1672                                 && (($link["type"] ?? "") == "text/html")
1673                                 && ($link["href"] != "")
1674                         ) {
1675                                 $data["url"] = $link["href"];
1676                         } elseif (($link["rel"] == "activity-inbox") && ($link["href"] != "")) {
1677                                 $data["notify"] = $link["href"];
1678                         } elseif (($link["rel"] == "activity-outbox") && ($link["href"] != "")) {
1679                                 $data["poll"] = $link["href"];
1680                         } elseif (($link["rel"] == "dialback") && ($link["href"] != "")) {
1681                                 $data["dialback"] = $link["href"];
1682                         }
1683                 }
1684                 if (isset($data["poll"]) && isset($data["notify"])
1685                         && isset($data["dialback"])
1686                         && isset($data["url"])
1687                 ) {
1688                         // by now we use these fields only for the network type detection
1689                         // So we unset all data that isn't used at the moment
1690                         unset($data["dialback"]);
1691
1692                         $data["network"] = Protocol::PUMPIO;
1693                 } else {
1694                         return [];
1695                 }
1696
1697                 $profile_data = self::pumpioProfileData($data["url"]);
1698
1699                 if (!$profile_data) {
1700                         return [];
1701                 }
1702
1703                 $data = array_merge($data, $profile_data);
1704
1705                 if (($addr != '') && ($data['name'] != '')) {
1706                         $name = trim(str_replace($addr, '', $data['name']));
1707                         if ($name != '') {
1708                                 $data['name'] = $name;
1709                         }
1710                 }
1711
1712                 return $data;
1713         }
1714
1715         /**
1716          * Check for twitter contact
1717          *
1718          * @param string $uri
1719          *
1720          * @return array twitter data
1721          */
1722         private static function twitter($uri)
1723         {
1724                 if (preg_match('=(.*)@twitter.com=i', $uri, $matches)) {
1725                         $nick = $matches[1];
1726                 } elseif (preg_match('=https?://twitter.com/(.*)=i', $uri, $matches)) {
1727                         $nick = $matches[1];
1728                 } else {
1729                         return [];
1730                 }
1731
1732                 $data = [];
1733                 $data['url'] = 'https://twitter.com/' . $nick;
1734                 $data['addr'] = $nick . '@twitter.com';
1735                 $data['nick'] = $data['name'] = $nick;
1736                 $data['network'] = Protocol::TWITTER;
1737                 $data['baseurl'] = 'https://twitter.com';
1738
1739                 return $data;
1740         }
1741
1742         /**
1743          * Checks HTML page for RSS feed link
1744          *
1745          * @param string $url  Page link
1746          * @param string $body Page body string
1747          * @return string|false Feed link or false if body was invalid HTML document
1748          */
1749         public static function getFeedLink(string $url, string $body)
1750         {
1751                 $doc = new DOMDocument();
1752                 if (!@$doc->loadHTML($body)) {
1753                         return false;
1754                 }
1755
1756                 $xpath = new DOMXPath($doc);
1757
1758                 $feedUrl = $xpath->evaluate('string(/html/head/link[@type="application/rss+xml" and @rel="alternate"]/@href)');
1759
1760                 $feedUrl = $feedUrl ? self::ensureAbsoluteLinkFromHTMLDoc($feedUrl, $url, $xpath) : '';
1761
1762                 return $feedUrl;
1763         }
1764
1765         /**
1766          * Return an absolute URL in the context of a HTML document retrieved from the provided URL.
1767          *
1768          * Loosely based on RFC 1808
1769          *
1770          * @see https://tools.ietf.org/html/rfc1808
1771          *
1772          * @param string   $href  The potential relative href found in the HTML document
1773          * @param string   $base  The HTML document URL
1774          * @param DOMXPath $xpath The HTML document XPath
1775          * @return string
1776          */
1777         private static function ensureAbsoluteLinkFromHTMLDoc(string $href, string $base, DOMXPath $xpath)
1778         {
1779                 if (filter_var($href, FILTER_VALIDATE_URL)) {
1780                         return $href;
1781                 }
1782
1783                 $base = $xpath->evaluate('string(/html/head/base/@href)') ?: $base;
1784
1785                 $baseParts = parse_url($base);
1786
1787                 // Naked domain case (scheme://basehost)
1788                 $path = $baseParts['path'] ?? '/';
1789
1790                 // Remove the filename part of the path if it exists (/base/path/file)
1791                 $path = implode('/', array_slice(explode('/', $path), 0, -1));
1792
1793                 $hrefParts = parse_url($href);
1794
1795                 // Root path case (/path) including relative scheme case (//host/path)
1796                 if ($hrefParts['path'] && $hrefParts['path'][0] == '/') {
1797                         $path = $hrefParts['path'];
1798                 } else {
1799                         $path = $path . '/' . $hrefParts['path'];
1800
1801                         // Resolve arbitrary relative path
1802                         // Lifted from https://www.php.net/manual/en/function.realpath.php#84012
1803                         $parts = array_filter(explode('/', $path), 'strlen');
1804                         $absolutes = array();
1805                         foreach ($parts as $part) {
1806                                 if ('.' == $part) continue;
1807                                 if ('..' == $part) {
1808                                         array_pop($absolutes);
1809                                 } else {
1810                                         $absolutes[] = $part;
1811                                 }
1812                         }
1813
1814                         $path = '/' . implode('/', $absolutes);
1815                 }
1816
1817                 // Relative scheme case (//host/path)
1818                 $baseParts['host'] = $hrefParts['host'] ?? $baseParts['host'];
1819                 $baseParts['path'] = $path;
1820                 unset($baseParts['query']);
1821                 unset($baseParts['fragment']);
1822
1823                 return Network::unparseURL($baseParts);
1824         }
1825
1826         /**
1827          * Check for feed contact
1828          *
1829          * @param string  $url   Profile link
1830          * @param boolean $probe Do a probe if the page contains a feed link
1831          *
1832          * @return array feed data
1833          * @throws HTTPException\InternalServerErrorException
1834          */
1835         private static function feed($url, $probe = true)
1836         {
1837                 $curlResult = Network::curl($url);
1838                 if ($curlResult->isTimeout()) {
1839                         self::$istimeout = true;
1840                         return [];
1841                 }
1842                 $feed = $curlResult->getBody();
1843                 $feed_data = Feed::import($feed);
1844
1845                 if (!$feed_data) {
1846                         if (!$probe) {
1847                                 return [];
1848                         }
1849
1850                         $feed_url = self::getFeedLink($url, $feed);
1851
1852                         if (!$feed_url) {
1853                                 return [];
1854                         }
1855
1856                         return self::feed($feed_url, false);
1857                 }
1858
1859                 if (!empty($feed_data["header"]["author-name"])) {
1860                         $data["name"] = $feed_data["header"]["author-name"];
1861                 }
1862
1863                 if (!empty($feed_data["header"]["author-nick"])) {
1864                         $data["nick"] = $feed_data["header"]["author-nick"];
1865                 }
1866
1867                 if (!empty($feed_data["header"]["author-avatar"])) {
1868                         $data["photo"] = $feed_data["header"]["author-avatar"];
1869                 }
1870
1871                 if (!empty($feed_data["header"]["author-id"])) {
1872                         $data["alias"] = $feed_data["header"]["author-id"];
1873                 }
1874
1875                 $data["url"] = $url;
1876                 $data["poll"] = $url;
1877
1878                 $data["network"] = Protocol::FEED;
1879
1880                 return $data;
1881         }
1882
1883         /**
1884          * Check for mail contact
1885          *
1886          * @param string  $uri Profile link
1887          * @param integer $uid User ID
1888          *
1889          * @return array mail data
1890          * @throws \Exception
1891          */
1892         private static function mail($uri, $uid)
1893         {
1894                 if (!Network::isEmailDomainValid($uri)) {
1895                         return [];
1896                 }
1897
1898                 if ($uid == 0) {
1899                         return [];
1900                 }
1901
1902                 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
1903
1904                 $condition = ["`uid` = ? AND `server` != ''", $uid];
1905                 $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox'];
1906                 $mailacct = DBA::selectFirst('mailacct', $fields, $condition);
1907
1908                 if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
1909                         return [];
1910                 }
1911
1912                 $mailbox = Email::constructMailboxName($mailacct);
1913                 $password = '';
1914                 openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
1915                 $mbox = Email::connect($mailbox, $mailacct['user'], $password);
1916                 if (!$mbox) {
1917                         return [];
1918                 }
1919
1920                 $msgs = Email::poll($mbox, $uri);
1921                 Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
1922
1923                 if (!count($msgs)) {
1924                         return [];
1925                 }
1926
1927                 $phost = substr($uri, strpos($uri, '@') + 1);
1928
1929                 $data = [];
1930                 $data["addr"]    = $uri;
1931                 $data["network"] = Protocol::MAIL;
1932                 $data["name"]    = substr($uri, 0, strpos($uri, '@'));
1933                 $data["nick"]    = $data["name"];
1934                 $data["photo"]   = Network::lookupAvatarByEmail($uri);
1935                 $data["url"]     = 'mailto:'.$uri;
1936                 $data["notify"]  = 'smtp ' . Strings::getRandomHex();
1937                 $data["poll"]    = 'email ' . Strings::getRandomHex();
1938
1939                 $x = Email::messageMeta($mbox, $msgs[0]);
1940                 if (stristr($x[0]->from, $uri)) {
1941                         $adr = imap_rfc822_parse_adrlist($x[0]->from, '');
1942                 } elseif (stristr($x[0]->to, $uri)) {
1943                         $adr = imap_rfc822_parse_adrlist($x[0]->to, '');
1944                 }
1945                 if (isset($adr)) {
1946                         foreach ($adr as $feadr) {
1947                                 if ((strcasecmp($feadr->mailbox, $data["name"]) == 0)
1948                                         &&(strcasecmp($feadr->host, $phost) == 0)
1949                                         && (strlen($feadr->personal))
1950                                 ) {
1951                                         $personal = imap_mime_header_decode($feadr->personal);
1952                                         $data["name"] = "";
1953                                         foreach ($personal as $perspart) {
1954                                                 if ($perspart->charset != "default") {
1955                                                         $data["name"] .= iconv($perspart->charset, 'UTF-8//IGNORE', $perspart->text);
1956                                                 } else {
1957                                                         $data["name"] .= $perspart->text;
1958                                                 }
1959                                         }
1960
1961                                         $data["name"] = Strings::escapeTags($data["name"]);
1962                                 }
1963                         }
1964                 }
1965                 if (!empty($mbox)) {
1966                         imap_close($mbox);
1967                 }
1968                 return $data;
1969         }
1970
1971         /**
1972          * Mix two paths together to possibly fix missing parts
1973          *
1974          * @param string $avatar Path to the avatar
1975          * @param string $base   Another path that is hopefully complete
1976          *
1977          * @return string fixed avatar path
1978          * @throws \Exception
1979          */
1980         public static function fixAvatar($avatar, $base)
1981         {
1982                 $base_parts = parse_url($base);
1983
1984                 // Remove all parts that could create a problem
1985                 unset($base_parts['path']);
1986                 unset($base_parts['query']);
1987                 unset($base_parts['fragment']);
1988
1989                 $avatar_parts = parse_url($avatar);
1990
1991                 // Now we mix them
1992                 $parts = array_merge($base_parts, $avatar_parts);
1993
1994                 // And put them together again
1995                 $scheme   = isset($parts['scheme'])   ? $parts['scheme'] . '://' : '';
1996                 $host     = isset($parts['host'])     ? $parts['host']           : '';
1997                 $port     = isset($parts['port'])     ? ':' . $parts['port']     : '';
1998                 $path     = isset($parts['path'])     ? $parts['path']           : '';
1999                 $query    = isset($parts['query'])    ? '?' . $parts['query']    : '';
2000                 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
2001
2002                 $fixed = $scheme.$host.$port.$path.$query.$fragment;
2003
2004                 Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);
2005
2006                 return $fixed;
2007         }
2008 }