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