Move Config::get() to DI::config()->get()
[friendica.git/.git] / mod / dfrn_poll.php
1 <?php
2
3 /**
4  * @file mod/dfrn_poll.php
5  */
6
7 use Friendica\App;
8 use Friendica\Core\Config;
9 use Friendica\Core\Logger;
10 use Friendica\Core\System;
11 use Friendica\Core\Session;
12 use Friendica\Database\DBA;
13 use Friendica\DI;
14 use Friendica\Protocol\DFRN;
15 use Friendica\Protocol\OStatus;
16 use Friendica\Util\Network;
17 use Friendica\Util\Strings;
18 use Friendica\Util\XML;
19
20 function dfrn_poll_init(App $a)
21 {
22         DI::auth()->withSession($a);
23
24         $dfrn_id         =  $_GET['dfrn_id']         ?? '';
25         $type            = ($_GET['type']            ?? '') ?: 'data';
26         $last_update     =  $_GET['last_update']     ?? '';
27         $destination_url =  $_GET['destination_url'] ?? '';
28         $challenge       =  $_GET['challenge']       ?? '';
29         $sec             =  $_GET['sec']             ?? '';
30         $dfrn_version    = floatval(($_GET['dfrn_version'] ?? 0.0) ?: 2.0);
31         $quiet                   = !empty($_GET['quiet']);
32
33         // Possibly it is an OStatus compatible server that requests a user feed
34         $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
35         if (($a->argc > 1) && ($dfrn_id == '') && !strstr($user_agent, 'Friendica')) {
36                 $nickname = $a->argv[1];
37                 header("Content-type: application/atom+xml");
38                 echo OStatus::feed($nickname, $last_update, 10);
39                 exit();
40         }
41
42         $direction = -1;
43
44         if (strpos($dfrn_id, ':') == 1) {
45                 $direction = intval(substr($dfrn_id, 0, 1));
46                 $dfrn_id = substr($dfrn_id, 2);
47         }
48
49         $hidewall = false;
50
51         if (($dfrn_id === '') && empty($_POST['dfrn_id'])) {
52                 if (DI::config()->get('system', 'block_public') && !Session::isAuthenticated()) {
53                         throw new \Friendica\Network\HTTPException\ForbiddenException();
54                 }
55
56                 $user = '';
57                 if ($a->argc > 1) {
58                         $r = q("SELECT `hidewall`,`nickname` FROM `user` WHERE `user`.`nickname` = '%s' LIMIT 1",
59                                 DBA::escape($a->argv[1])
60                         );
61                         if (!$r) {
62                                 throw new \Friendica\Network\HTTPException\NotFoundException();
63                         }
64
65                         $hidewall = ($r[0]['hidewall'] && !local_user());
66
67                         $user = $r[0]['nickname'];
68                 }
69
70                 Logger::log('dfrn_poll: public feed request from ' . $_SERVER['REMOTE_ADDR'] . ' for ' . $user);
71                 header("Content-type: application/atom+xml");
72                 echo DFRN::feed('', $user, $last_update, 0, $hidewall);
73                 exit();
74         }
75
76         if (($type === 'profile') && (!strlen($sec))) {
77                 $sql_extra = '';
78                 switch ($direction) {
79                         case -1:
80                                 $sql_extra = sprintf(" AND ( `dfrn-id` = '%s' OR `issued-id` = '%s' ) ", DBA::escape($dfrn_id), DBA::escape($dfrn_id));
81                                 $my_id = $dfrn_id;
82                                 break;
83                         case 0:
84                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
85                                 $my_id = '1:' . $dfrn_id;
86                                 break;
87                         case 1:
88                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
89                                 $my_id = '0:' . $dfrn_id;
90                                 break;
91                         default:
92                                 DI::baseUrl()->redirect();
93                                 break; // NOTREACHED
94                 }
95
96                 $r = q("SELECT `contact`.*, `user`.`username`, `user`.`nickname`
97                         FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
98                         WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
99                         AND `user`.`nickname` = '%s' $sql_extra LIMIT 1",
100                         DBA::escape($a->argv[1])
101                 );
102
103                 if (DBA::isResult($r)) {
104                         $s = Network::fetchUrl($r[0]['poll'] . '?dfrn_id=' . $my_id . '&type=profile-check');
105
106                         Logger::log("dfrn_poll: old profile returns " . $s, Logger::DATA);
107
108                         if (strlen($s)) {
109                                 $xml = XML::parseString($s);
110
111                                 if ((int)$xml->status === 1) {
112                                         $_SESSION['authenticated'] = 1;
113                                         $_SESSION['visitor_id'] = $r[0]['id'];
114                                         $_SESSION['visitor_home'] = $r[0]['url'];
115                                         $_SESSION['visitor_handle'] = $r[0]['addr'];
116                                         $_SESSION['visitor_visiting'] = $r[0]['uid'];
117                                         $_SESSION['my_url'] = $r[0]['url'];
118
119                                         Session::setVisitorsContacts();
120
121                                         if (!$quiet) {
122                                                 info(DI::l10n()->t('%1$s welcomes %2$s', $r[0]['username'], $r[0]['name']) . EOL);
123                                         }
124
125                                         // Visitors get 1 day session.
126                                         $session_id = session_id();
127                                         $expire = time() + 86400;
128                                         q("UPDATE `session` SET `expire` = '%s' WHERE `sid` = '%s'",
129                                                 DBA::escape($expire),
130                                                 DBA::escape($session_id)
131                                         );
132                                 }
133                         }
134
135                         $profile = (count($r) > 0 && isset($r[0]['nickname']) ? $r[0]['nickname'] : '');
136                         if (!empty($destination_url)) {
137                                 System::externalRedirect($destination_url);
138                         } else {
139                                 DI::baseUrl()->redirect('profile/' . $profile);
140                         }
141                 }
142                 DI::baseUrl()->redirect();
143         }
144
145         if ($type === 'profile-check' && $dfrn_version < 2.2) {
146                 if ((strlen($challenge)) && (strlen($sec))) {
147                         DBA::delete('profile_check', ["`expire` < ?", time()]);
148                         $r = q("SELECT * FROM `profile_check` WHERE `sec` = '%s' ORDER BY `expire` DESC LIMIT 1",
149                                 DBA::escape($sec)
150                         );
151                         if (!DBA::isResult($r)) {
152                                 System::xmlExit(3, 'No ticket');
153                                 // NOTREACHED
154                         }
155
156                         $orig_id = $r[0]['dfrn_id'];
157                         if (strpos($orig_id, ':')) {
158                                 $orig_id = substr($orig_id, 2);
159                         }
160
161                         $c = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
162                                 intval($r[0]['cid'])
163                         );
164                         if (!DBA::isResult($c)) {
165                                 System::xmlExit(3, 'No profile');
166                         }
167
168                         $contact = $c[0];
169
170                         $sent_dfrn_id = hex2bin($dfrn_id);
171                         $challenge = hex2bin($challenge);
172
173                         $final_dfrn_id = '';
174
175                         if (($contact['duplex']) && strlen($contact['prvkey'])) {
176                                 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
177                                 openssl_private_decrypt($challenge, $decoded_challenge, $contact['prvkey']);
178                         } else {
179                                 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
180                                 openssl_public_decrypt($challenge, $decoded_challenge, $contact['pubkey']);
181                         }
182
183                         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
184
185                         if (strpos($final_dfrn_id, ':') == 1) {
186                                 $final_dfrn_id = substr($final_dfrn_id, 2);
187                         }
188
189                         if ($final_dfrn_id != $orig_id) {
190                                 Logger::log('profile_check: ' . $final_dfrn_id . ' != ' . $orig_id, Logger::DEBUG);
191                                 // did not decode properly - cannot trust this site
192                                 System::xmlExit(3, 'Bad decryption');
193                         }
194
195                         header("Content-type: text/xml");
196                         echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?><dfrn_poll><status>0</status><challenge>$decoded_challenge</challenge><sec>$sec</sec></dfrn_poll>";
197                         exit();
198                         // NOTREACHED
199                 } else {
200                         // old protocol
201                         switch ($direction) {
202                                 case 1:
203                                         $dfrn_id = '0:' . $dfrn_id;
204                                         break;
205                                 case 0:
206                                         $dfrn_id = '1:' . $dfrn_id;
207                                         break;
208                                 default:
209                                         break;
210                         }
211
212                         DBA::delete('profile_check', ["`expire` < ?", time()]);
213                         $r = q("SELECT * FROM `profile_check` WHERE `dfrn_id` = '%s' ORDER BY `expire` DESC",
214                                 DBA::escape($dfrn_id));
215                         if (DBA::isResult($r)) {
216                                 System::xmlExit(1);
217                                 return; // NOTREACHED
218                         }
219                         System::xmlExit(0);
220                         return; // NOTREACHED
221                 }
222         }
223 }
224
225 function dfrn_poll_post(App $a)
226 {
227         $dfrn_id      =  $_POST['dfrn_id']   ?? '';
228         $challenge    =  $_POST['challenge'] ?? '';
229         $url          =  $_POST['url']       ?? '';
230         $sec          =  $_POST['sec']       ?? '';
231         $ptype        =  $_POST['type']      ?? '';
232         $perm         = ($_POST['perm']      ?? '') ?: 'r';
233         $dfrn_version = floatval(($_GET['dfrn_version'] ?? 0.0) ?: 2.0);
234
235         if ($ptype === 'profile-check') {
236                 if (strlen($challenge) && strlen($sec)) {
237                         Logger::log('dfrn_poll: POST: profile-check');
238
239                         DBA::delete('profile_check', ["`expire` < ?", time()]);
240                         $r = q("SELECT * FROM `profile_check` WHERE `sec` = '%s' ORDER BY `expire` DESC LIMIT 1",
241                                 DBA::escape($sec)
242                         );
243                         if (!DBA::isResult($r)) {
244                                 System::xmlExit(3, 'No ticket');
245                                 // NOTREACHED
246                         }
247
248                         $orig_id = $r[0]['dfrn_id'];
249                         if (strpos($orig_id, ':')) {
250                                 $orig_id = substr($orig_id, 2);
251                         }
252
253                         $c = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
254                                 intval($r[0]['cid'])
255                         );
256                         if (!DBA::isResult($c)) {
257                                 System::xmlExit(3, 'No profile');
258                         }
259
260                         $contact = $c[0];
261
262                         $sent_dfrn_id = hex2bin($dfrn_id);
263                         $challenge = hex2bin($challenge);
264
265                         $final_dfrn_id = '';
266
267                         if ($contact['duplex'] && strlen($contact['prvkey'])) {
268                                 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
269                                 openssl_private_decrypt($challenge, $decoded_challenge, $contact['prvkey']);
270                         } else {
271                                 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
272                                 openssl_public_decrypt($challenge, $decoded_challenge, $contact['pubkey']);
273                         }
274
275                         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
276
277                         if (strpos($final_dfrn_id, ':') == 1) {
278                                 $final_dfrn_id = substr($final_dfrn_id, 2);
279                         }
280
281                         if ($final_dfrn_id != $orig_id) {
282                                 Logger::log('profile_check: ' . $final_dfrn_id . ' != ' . $orig_id, Logger::DEBUG);
283                                 // did not decode properly - cannot trust this site
284                                 System::xmlExit(3, 'Bad decryption');
285                         }
286
287                         header("Content-type: text/xml");
288                         echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?><dfrn_poll><status>0</status><challenge>$decoded_challenge</challenge><sec>$sec</sec></dfrn_poll>";
289                         exit();
290                         // NOTREACHED
291                 }
292         }
293
294         $direction = -1;
295         if (strpos($dfrn_id, ':') == 1) {
296                 $direction = intval(substr($dfrn_id, 0, 1));
297                 $dfrn_id = substr($dfrn_id, 2);
298         }
299
300         $r = q("SELECT * FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1",
301                 DBA::escape($dfrn_id),
302                 DBA::escape($challenge)
303         );
304
305         if (!DBA::isResult($r)) {
306                 exit();
307         }
308
309         $type = $r[0]['type'];
310         $last_update = $r[0]['last_update'];
311
312         DBA::delete('challenge', ['dfrn-id' => $dfrn_id, 'challenge' => $challenge]);
313
314         $sql_extra = '';
315         switch ($direction) {
316                 case -1:
317                         $sql_extra = sprintf(" AND `issued-id` = '%s' ", DBA::escape($dfrn_id));
318                         break;
319                 case 0:
320                         $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
321                         break;
322                 case 1:
323                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
324                         break;
325                 default:
326                         DI::baseUrl()->redirect();
327                         break; // NOTREACHED
328         }
329
330         $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 $sql_extra LIMIT 1");
331         if (!DBA::isResult($r)) {
332                 exit();
333         }
334
335         $contact = $r[0];
336         $owner_uid = $r[0]['uid'];
337         $contact_id = $r[0]['id'];
338
339         if ($type === 'reputation' && strlen($url)) {
340                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
341                         DBA::escape($url),
342                         intval($owner_uid)
343                 );
344                 $reputation = 0;
345                 $text = '';
346
347                 if (DBA::isResult($r)) {
348                         $reputation = $r[0]['rating'];
349                         $text = $r[0]['reason'];
350
351                         if ($r[0]['id'] == $contact_id) { // inquiring about own reputation not allowed
352                                 $reputation = 0;
353                                 $text = '';
354                         }
355                 }
356
357                 echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
358                 <reputation>
359                         <url>$url</url>
360                         <rating>$reputation</rating>
361                         <description>$text</description>
362                 </reputation>
363                 ";
364                 exit();
365                 // NOTREACHED
366         } else {
367                 // Update the writable flag if it changed
368                 Logger::log('dfrn_poll: post request feed: ' . print_r($_POST, true), Logger::DATA);
369                 if ($dfrn_version >= 2.21) {
370                         if ($perm === 'rw') {
371                                 $writable = 1;
372                         } else {
373                                 $writable = 0;
374                         }
375
376                         if ($writable != $contact['writable']) {
377                                 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d",
378                                         intval($writable),
379                                         intval($contact_id)
380                                 );
381                         }
382                 }
383
384                 header("Content-type: application/atom+xml");
385                 $o = DFRN::feed($dfrn_id, $a->argv[1], $last_update, $direction);
386                 echo $o;
387                 exit();
388         }
389 }
390
391 function dfrn_poll_content(App $a)
392 {
393         $dfrn_id         =  $_GET['dfrn_id']         ?? '';
394         $type            = ($_GET['type']            ?? '') ?: 'data';
395         $last_update     =  $_GET['last_update']     ?? '';
396         $destination_url =  $_GET['destination_url'] ?? '';
397         $sec             =  $_GET['sec']             ?? '';
398         $dfrn_version    = floatval(($_GET['dfrn_version'] ?? 0.0) ?: 2.0);
399         $quiet           = !empty($_GET['quiet']);
400
401         $direction = -1;
402         if (strpos($dfrn_id, ':') == 1) {
403                 $direction = intval(substr($dfrn_id, 0, 1));
404                 $dfrn_id = substr($dfrn_id, 2);
405         }
406
407         if ($dfrn_id != '') {
408                 // initial communication from external contact
409                 $hash = Strings::getRandomHex();
410
411                 $status = 0;
412
413                 DBA::delete('challenge', ["`expire` < ?", time()]);
414
415                 if ($type !== 'profile') {
416                         q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` , `type`, `last_update` )
417                                 VALUES( '%s', '%s', '%s', '%s', '%s' ) ",
418                                 DBA::escape($hash),
419                                 DBA::escape($dfrn_id),
420                                 intval(time() + 60 ),
421                                 DBA::escape($type),
422                                 DBA::escape($last_update)
423                         );
424                 }
425
426                 $sql_extra = '';
427                 switch ($direction) {
428                         case -1:
429                                 if ($type === 'profile') {
430                                         $sql_extra = sprintf(" AND (`dfrn-id` = '%s' OR `issued-id` = '%s') ", DBA::escape($dfrn_id), DBA::escape($dfrn_id));
431                                 } else {
432                                         $sql_extra = sprintf(" AND `issued-id` = '%s' ", DBA::escape($dfrn_id));
433                                 }
434
435                                 $my_id = $dfrn_id;
436                                 break;
437                         case 0:
438                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
439                                 $my_id = '1:' . $dfrn_id;
440                                 break;
441                         case 1:
442                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
443                                 $my_id = '0:' . $dfrn_id;
444                                 break;
445                         default:
446                                 DI::baseUrl()->redirect();
447                                 break; // NOTREACHED
448                 }
449
450                 $nickname = $a->argv[1];
451
452                 $r = q("SELECT `contact`.*, `user`.`username`, `user`.`nickname`
453                         FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
454                         WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
455                         AND `user`.`nickname` = '%s' $sql_extra LIMIT 1",
456                         DBA::escape($nickname)
457                 );
458                 if (DBA::isResult($r)) {
459                         $challenge = '';
460                         $encrypted_id = '';
461                         $id_str = $my_id . '.' . mt_rand(1000, 9999);
462
463                         if (($r[0]['duplex'] && strlen($r[0]['pubkey'])) || !strlen($r[0]['prvkey'])) {
464                                 openssl_public_encrypt($hash, $challenge, $r[0]['pubkey']);
465                                 openssl_public_encrypt($id_str, $encrypted_id, $r[0]['pubkey']);
466                         } else {
467                                 openssl_private_encrypt($hash, $challenge, $r[0]['prvkey']);
468                                 openssl_private_encrypt($id_str, $encrypted_id, $r[0]['prvkey']);
469                         }
470
471                         $challenge = bin2hex($challenge);
472                         $encrypted_id = bin2hex($encrypted_id);
473                 } else {
474                         $status = 1;
475                         $challenge = '';
476                         $encrypted_id = '';
477                 }
478
479                 if (($type === 'profile') && (strlen($sec))) {
480                         // heluecht: I don't know why we don't fail immediately when the user or contact hadn't been found.
481                         // Since it doesn't make sense to continue from this point on, we now fail here. This should be safe.
482                         if (!DBA::isResult($r)) {
483                                 throw new \Friendica\Network\HTTPException\NotFoundException();
484                         }
485
486                         // URL reply
487                         if ($dfrn_version < 2.2) {
488                                 $s = Network::fetchUrl($r[0]['poll']
489                                         . '?dfrn_id=' . $encrypted_id
490                                         . '&type=profile-check'
491                                         . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
492                                         . '&challenge=' . $challenge
493                                         . '&sec=' . $sec
494                                 );
495                         } else {
496                                 $s = Network::post($r[0]['poll'], [
497                                         'dfrn_id' => $encrypted_id,
498                                         'type' => 'profile-check',
499                                         'dfrn_version' => DFRN_PROTOCOL_VERSION,
500                                         'challenge' => $challenge,
501                                         'sec' => $sec
502                                 ])->getBody();
503                         }
504
505                         Logger::log("dfrn_poll: sec profile: " . $s, Logger::DATA);
506
507                         if (strlen($s) && strstr($s, '<?xml')) {
508                                 $xml = XML::parseString($s);
509
510                                 Logger::log('dfrn_poll: profile: parsed xml: ' . print_r($xml, true), Logger::DATA);
511
512                                 Logger::log('dfrn_poll: secure profile: challenge: ' . $xml->challenge . ' expecting ' . $hash);
513                                 Logger::log('dfrn_poll: secure profile: sec: ' . $xml->sec . ' expecting ' . $sec);
514
515                                 if (((int) $xml->status == 0) && ($xml->challenge == $hash) && ($xml->sec == $sec)) {
516                                         $_SESSION['authenticated'] = 1;
517                                         $_SESSION['visitor_id'] = $r[0]['id'];
518                                         $_SESSION['visitor_home'] = $r[0]['url'];
519                                         $_SESSION['visitor_visiting'] = $r[0]['uid'];
520                                         $_SESSION['my_url'] = $r[0]['url'];
521
522                                         Session::setVisitorsContacts();
523
524                                         if (!$quiet) {
525                                                 info(DI::l10n()->t('%1$s welcomes %2$s', $r[0]['username'], $r[0]['name']) . EOL);
526                                         }
527
528                                         // Visitors get 1 day session.
529                                         $session_id = session_id();
530                                         $expire = time() + 86400;
531                                         q("UPDATE `session` SET `expire` = '%s' WHERE `sid` = '%s'",
532                                                 DBA::escape($expire),
533                                                 DBA::escape($session_id)
534                                         );
535                                 }
536                         }
537
538                         $profile = ((DBA::isResult($r) && $r[0]['nickname']) ? $r[0]['nickname'] : $nickname);
539
540                         switch ($destination_url) {
541                                 case 'profile':
542                                         DI::baseUrl()->redirect('profile/' . $profile . '?tab=profile');
543                                         break;
544                                 case 'photos':
545                                         DI::baseUrl()->redirect('photos/' . $profile);
546                                         break;
547                                 case 'status':
548                                 case '':
549                                         DI::baseUrl()->redirect('profile/' . $profile);
550                                         break;
551                                 default:
552                                         $appendix = (strstr($destination_url, '?') ? '&redir=1' : '?redir=1');
553                                         DI::baseUrl()->redirect($destination_url . $appendix);
554                                         break;
555                         }
556                         // NOTREACHED
557                 } else {
558                         // XML reply
559                         header("Content-type: text/xml");
560                         echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n"
561                                 . '<dfrn_poll>' . "\r\n"
562                                 . "\t" . '<status>' . $status . '</status>' . "\r\n"
563                                 . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
564                                 . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n"
565                                 . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
566                                 . '</dfrn_poll>' . "\r\n";
567                         exit();
568                         // NOTREACHED
569                 }
570         }
571 }