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