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