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