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