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