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