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