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