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