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