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