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