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