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