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