]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_poll.php
Misc cleanups (#5417)
[friendica.git] / mod / dfrn_poll.php
1 <?php
2
3 /**
4  * @file mod/dfrn_poll.php
5  */
6 use Friendica\App;
7 use Friendica\Core\Config;
8 use Friendica\Core\L10n;
9 use Friendica\Core\System;
10 use Friendica\Database\DBM;
11 use Friendica\Module\Login;
12 use Friendica\Protocol\DFRN;
13 use Friendica\Protocol\OStatus;
14 use Friendica\Util\Network;
15 use Friendica\Util\XML;
16
17 require_once 'include/items.php';
18
19 function dfrn_poll_init(App $a)
20 {
21         Login::sessionAuth();
22
23         $dfrn_id         = defaults($_GET, 'dfrn_id'        , '');
24         $type            = defaults($_GET, 'type'           , 'data');
25         $last_update     = defaults($_GET, 'last_update'    , '');
26         $destination_url = defaults($_GET, 'destination_url', '');
27         $challenge       = defaults($_GET, 'challenge'      , '');
28         $sec             = defaults($_GET, 'sec'            , '');
29         $dfrn_version    = (float) defaults($_GET, 'dfrn_version'   , 2.0);
30         $perm            = defaults($_GET, 'perm'           , 'r');
31         $quiet                   = x($_GET, 'quiet');
32
33         // Possibly it is an OStatus compatible server that requests a user feed
34         if (($a->argc > 1) && ($dfrn_id == '') && !strstr($_SERVER["HTTP_USER_AGENT"], 'Friendica')) {
35                 $nickname = $a->argv[1];
36                 header("Content-type: application/atom+xml");
37                 echo OStatus::feed($nickname, $last_update, 10);
38                 killme();
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 === '') && (!x($_POST, 'dfrn_id'))) {
51                 if (Config::get('system', 'block_public') && !local_user() && !remote_user()) {
52                         System::httpExit(403);
53                 }
54
55                 $user = '';
56                 if ($a->argc > 1) {
57                         $r = q("SELECT `hidewall`,`nickname` FROM `user` WHERE `user`.`nickname` = '%s' LIMIT 1",
58                                 dbesc($a->argv[1])
59                         );
60                         if (!$r) {
61                                 System::httpExit(404);
62                         }
63
64                         $hidewall = ($r[0]['hidewall'] && !local_user());
65
66                         $user = $r[0]['nickname'];
67                 }
68
69                 logger('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                 killme();
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' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
80                                 $my_id = $dfrn_id;
81                                 break;
82                         case 0:
83                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
84                                 $my_id = '1:' . $dfrn_id;
85                                 break;
86                         case 1:
87                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
88                                 $my_id = '0:' . $dfrn_id;
89                                 break;
90                         default:
91                                 goaway(System::baseUrl());
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                         dbesc($a->argv[1])
100                 );
101
102                 if (DBM::is_result($r)) {
103                         $s = Network::fetchUrl($r[0]['poll'] . '?dfrn_id=' . $my_id . '&type=profile-check');
104
105                         logger("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                                         if (!x($_SESSION, 'remote')) {
113                                                 $_SESSION['remote'] = [];
114                                         }
115
116                                         $_SESSION['remote'][] = ['cid' => $r[0]['id'], 'uid' => $r[0]['uid'], 'url' => $r[0]['url']];
117
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                                         if (!$quiet) {
124                                                 info(L10n::t('%1$s welcomes %2$s', $r[0]['username'], $r[0]['name']) . EOL);
125                                         }
126
127                                         // Visitors get 1 day session.
128                                         $session_id = session_id();
129                                         $expire = time() + 86400;
130                                         q("UPDATE `session` SET `expire` = '%s' WHERE `sid` = '%s'",
131                                                 dbesc($expire),
132                                                 dbesc($session_id)
133                                         );
134                                 }
135                         }
136                         $profile = $r[0]['nickname'];
137                         goaway((strlen($destination_url)) ? $destination_url : System::baseUrl() . '/profile/' . $profile);
138                 }
139                 goaway(System::baseUrl());
140         }
141
142         if ($type === 'profile-check' && $dfrn_version < 2.2) {
143                 if ((strlen($challenge)) && (strlen($sec))) {
144                         dba::delete('profile_check', ["`expire` < ?", time()]);
145                         $r = q("SELECT * FROM `profile_check` WHERE `sec` = '%s' ORDER BY `expire` DESC LIMIT 1",
146                                 dbesc($sec)
147                         );
148                         if (!DBM::is_result($r)) {
149                                 System::xmlExit(3, 'No ticket');
150                                 // NOTREACHED
151                         }
152
153                         $orig_id = $r[0]['dfrn_id'];
154                         if (strpos($orig_id, ':')) {
155                                 $orig_id = substr($orig_id, 2);
156                         }
157
158                         $c = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
159                                 intval($r[0]['cid'])
160                         );
161                         if (!DBM::is_result($c)) {
162                                 System::xmlExit(3, 'No profile');
163                         }
164
165                         $contact = $c[0];
166
167                         $sent_dfrn_id = hex2bin($dfrn_id);
168                         $challenge = hex2bin($challenge);
169
170                         $final_dfrn_id = '';
171
172                         if (($contact['duplex']) && strlen($contact['prvkey'])) {
173                                 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
174                                 openssl_private_decrypt($challenge, $decoded_challenge, $contact['prvkey']);
175                         } else {
176                                 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
177                                 openssl_public_decrypt($challenge, $decoded_challenge, $contact['pubkey']);
178                         }
179
180                         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
181
182                         if (strpos($final_dfrn_id, ':') == 1) {
183                                 $final_dfrn_id = substr($final_dfrn_id, 2);
184                         }
185
186                         if ($final_dfrn_id != $orig_id) {
187                                 logger('profile_check: ' . $final_dfrn_id . ' != ' . $orig_id, LOGGER_DEBUG);
188                                 // did not decode properly - cannot trust this site
189                                 System::xmlExit(3, 'Bad decryption');
190                         }
191
192                         header("Content-type: text/xml");
193                         echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?><dfrn_poll><status>0</status><challenge>$decoded_challenge</challenge><sec>$sec</sec></dfrn_poll>";
194                         killme();
195                         // NOTREACHED
196                 } else {
197                         // old protocol
198                         switch ($direction) {
199                                 case 1:
200                                         $dfrn_id = '0:' . $dfrn_id;
201                                         break;
202                                 case 0:
203                                         $dfrn_id = '1:' . $dfrn_id;
204                                         break;
205                                 default:
206                                         break;
207                         }
208
209                         dba::delete('profile_check', ["`expire` < ?", time()]);
210                         $r = q("SELECT * FROM `profile_check` WHERE `dfrn_id` = '%s' ORDER BY `expire` DESC",
211                                 dbesc($dfrn_id));
212                         if (DBM::is_result($r)) {
213                                 System::xmlExit(1);
214                                 return; // NOTREACHED
215                         }
216                         System::xmlExit(0);
217                         return; // NOTREACHED
218                 }
219         }
220 }
221
222 function dfrn_poll_post(App $a)
223 {
224         $dfrn_id      = x($_POST,'dfrn_id')      ? $_POST['dfrn_id']              : '';
225         $challenge    = x($_POST,'challenge')    ? $_POST['challenge']            : '';
226         $url          = x($_POST,'url')          ? $_POST['url']                  : '';
227         $sec          = x($_POST,'sec')          ? $_POST['sec']                  : '';
228         $ptype        = x($_POST,'type')         ? $_POST['type']                 : '';
229         $dfrn_version = x($_POST,'dfrn_version') ? (float) $_POST['dfrn_version'] : 2.0;
230         $perm         = x($_POST,'perm')         ? $_POST['perm']                 : 'r';
231
232         if ($ptype === 'profile-check') {
233                 if (strlen($challenge) && strlen($sec)) {
234                         logger('dfrn_poll: POST: profile-check');
235
236                         dba::delete('profile_check', ["`expire` < ?", time()]);
237                         $r = q("SELECT * FROM `profile_check` WHERE `sec` = '%s' ORDER BY `expire` DESC LIMIT 1",
238                                 dbesc($sec)
239                         );
240                         if (!DBM::is_result($r)) {
241                                 System::xmlExit(3, 'No ticket');
242                                 // NOTREACHED
243                         }
244
245                         $orig_id = $r[0]['dfrn_id'];
246                         if (strpos($orig_id, ':')) {
247                                 $orig_id = substr($orig_id, 2);
248                         }
249
250                         $c = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
251                                 intval($r[0]['cid'])
252                         );
253                         if (!DBM::is_result($c)) {
254                                 System::xmlExit(3, 'No profile');
255                         }
256
257                         $contact = $c[0];
258
259                         $sent_dfrn_id = hex2bin($dfrn_id);
260                         $challenge = hex2bin($challenge);
261
262                         $final_dfrn_id = '';
263
264                         if ($contact['duplex'] && strlen($contact['prvkey'])) {
265                                 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
266                                 openssl_private_decrypt($challenge, $decoded_challenge, $contact['prvkey']);
267                         } else {
268                                 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
269                                 openssl_public_decrypt($challenge, $decoded_challenge, $contact['pubkey']);
270                         }
271
272                         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
273
274                         if (strpos($final_dfrn_id, ':') == 1) {
275                                 $final_dfrn_id = substr($final_dfrn_id, 2);
276                         }
277
278                         if ($final_dfrn_id != $orig_id) {
279                                 logger('profile_check: ' . $final_dfrn_id . ' != ' . $orig_id, LOGGER_DEBUG);
280                                 // did not decode properly - cannot trust this site
281                                 System::xmlExit(3, 'Bad decryption');
282                         }
283
284                         header("Content-type: text/xml");
285                         echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?><dfrn_poll><status>0</status><challenge>$decoded_challenge</challenge><sec>$sec</sec></dfrn_poll>";
286                         killme();
287                         // NOTREACHED
288                 }
289         }
290
291         $direction = -1;
292         if (strpos($dfrn_id, ':') == 1) {
293                 $direction = intval(substr($dfrn_id, 0, 1));
294                 $dfrn_id = substr($dfrn_id, 2);
295         }
296
297         $r = q("SELECT * FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1",
298                 dbesc($dfrn_id),
299                 dbesc($challenge)
300         );
301
302         if (!DBM::is_result($r)) {
303                 killme();
304         }
305
306         $type = $r[0]['type'];
307         $last_update = $r[0]['last_update'];
308
309         dba::delete('challenge', ['dfrn-id' => $dfrn_id, 'challenge' => $challenge]);
310
311         $sql_extra = '';
312         switch ($direction) {
313                 case -1:
314                         $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
315                         $my_id = $dfrn_id;
316                         break;
317                 case 0:
318                         $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
319                         $my_id = '1:' . $dfrn_id;
320                         break;
321                 case 1:
322                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
323                         $my_id = '0:' . $dfrn_id;
324                         break;
325                 default:
326                         goaway(System::baseUrl());
327                         break; // NOTREACHED
328         }
329
330         $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 $sql_extra LIMIT 1");
331         if (!DBM::is_result($r)) {
332                 killme();
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                         dbesc($url),
342                         intval($owner_uid)
343                 );
344                 $reputation = 0;
345                 $text = '';
346
347                 if (DBM::is_result($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                 killme();
365                 // NOTREACHED
366         } else {
367                 // Update the writable flag if it changed
368                 logger('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                 killme();
388         }
389 }
390
391 function dfrn_poll_content(App $a)
392 {
393         $dfrn_id         = x($_GET,'dfrn_id')         ? $_GET['dfrn_id']              : '';
394         $type            = x($_GET,'type')            ? $_GET['type']                 : 'data';
395         $last_update     = x($_GET,'last_update')     ? $_GET['last_update']          : '';
396         $destination_url = x($_GET,'destination_url') ? $_GET['destination_url']      : '';
397         $sec             = x($_GET,'sec')             ? $_GET['sec']                  : '';
398         $dfrn_version    = x($_GET,'dfrn_version')    ? (float) $_GET['dfrn_version'] : 2.0;
399         $perm            = x($_GET,'perm')            ? $_GET['perm']                 : 'r';
400         $quiet           = x($_GET,'quiet')           ? true                          : false;
401
402         $direction = -1;
403         if (strpos($dfrn_id, ':') == 1) {
404                 $direction = intval(substr($dfrn_id, 0, 1));
405                 $dfrn_id = substr($dfrn_id, 2);
406         }
407
408         if ($dfrn_id != '') {
409                 // initial communication from external contact
410                 $hash = random_string();
411
412                 $status = 0;
413
414                 dba::delete('challenge', ["`expire` < ?", time()]);
415
416                 if ($type !== 'profile') {
417                         $r = q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` , `type`, `last_update` )
418                                 VALUES( '%s', '%s', '%s', '%s', '%s' ) ",
419                                 dbesc($hash),
420                                 dbesc($dfrn_id),
421                                 intval(time() + 60 ),
422                                 dbesc($type),
423                                 dbesc($last_update)
424                         );
425                 }
426
427                 $sql_extra = '';
428                 switch ($direction) {
429                         case -1:
430                                 if ($type === 'profile') {
431                                         $sql_extra = sprintf(" AND ( `dfrn-id` = '%s' OR `issued-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
432                                 } else {
433                                         $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
434                                 }
435
436                                 $my_id = $dfrn_id;
437                                 break;
438                         case 0:
439                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
440                                 $my_id = '1:' . $dfrn_id;
441                                 break;
442                         case 1:
443                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
444                                 $my_id = '0:' . $dfrn_id;
445                                 break;
446                         default:
447                                 goaway(System::baseUrl());
448                                 break; // NOTREACHED
449                 }
450
451                 $nickname = $a->argv[1];
452
453                 $r = q("SELECT `contact`.*, `user`.`username`, `user`.`nickname`
454                         FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
455                         WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
456                         AND `user`.`nickname` = '%s' $sql_extra LIMIT 1",
457                         dbesc($nickname)
458                 );
459                 if (DBM::is_result($r)) {
460                         $challenge = '';
461                         $encrypted_id = '';
462                         $id_str = $my_id . '.' . mt_rand(1000, 9999);
463
464                         if (($r[0]['duplex'] && strlen($r[0]['pubkey'])) || !strlen($r[0]['prvkey'])) {
465                                 openssl_public_encrypt($hash, $challenge, $r[0]['pubkey']);
466                                 openssl_public_encrypt($id_str, $encrypted_id, $r[0]['pubkey']);
467                         } else {
468                                 openssl_private_encrypt($hash, $challenge, $r[0]['prvkey']);
469                                 openssl_private_encrypt($id_str, $encrypted_id, $r[0]['prvkey']);
470                         }
471
472                         $challenge = bin2hex($challenge);
473                         $encrypted_id = bin2hex($encrypted_id);
474                 } else {
475                         $status = 1;
476                         $challenge = '';
477                         $encrypted_id = '';
478                 }
479
480                 if (($type === 'profile') && (strlen($sec))) {
481                         // URL reply
482                         if ($dfrn_version < 2.2) {
483                                 $s = Network::fetchUrl($r[0]['poll']
484                                         . '?dfrn_id=' . $encrypted_id
485                                         . '&type=profile-check'
486                                         . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
487                                         . '&challenge=' . $challenge
488                                         . '&sec=' . $sec
489                                 );
490                         } else {
491                                 $s = Network::post($r[0]['poll'], [
492                                         'dfrn_id' => $encrypted_id,
493                                         'type' => 'profile-check',
494                                         'dfrn_version' => DFRN_PROTOCOL_VERSION,
495                                         'challenge' => $challenge,
496                                         'sec' => $sec
497                                 ]);
498                         }
499
500                         $profile = ((DBM::is_result($r) && $r[0]['nickname']) ? $r[0]['nickname'] : $nickname);
501
502                         switch ($destination_url) {
503                                 case 'profile':
504                                         $dest = System::baseUrl() . '/profile/' . $profile . '?f=&tab=profile';
505                                         break;
506                                 case 'photos':
507                                         $dest = System::baseUrl() . '/photos/' . $profile;
508                                         break;
509                                 case 'status':
510                                 case '':
511                                         $dest = System::baseUrl() . '/profile/' . $profile;
512                                         break;
513                                 default:
514                                         $appendix = (strstr($destination_url, '?') ? '&f=&redir=1' : '?f=&redir=1');
515                                         $dest = $destination_url . $appendix;
516                                         break;
517                         }
518
519                         logger("dfrn_poll: sec profile: " . $s, LOGGER_DATA);
520
521                         if (strlen($s) && strstr($s, '<?xml')) {
522                                 $xml = XML::parseString($s);
523
524                                 logger('dfrn_poll: profile: parsed xml: ' . print_r($xml, true), LOGGER_DATA);
525
526                                 logger('dfrn_poll: secure profile: challenge: ' . $xml->challenge . ' expecting ' . $hash);
527                                 logger('dfrn_poll: secure profile: sec: ' . $xml->sec . ' expecting ' . $sec);
528
529                                 if (((int) $xml->status == 0) && ($xml->challenge == $hash) && ($xml->sec == $sec)) {
530                                         $_SESSION['authenticated'] = 1;
531                                         if (!x($_SESSION, 'remote')) {
532                                                 $_SESSION['remote'] = [];
533                                         }
534
535                                         $_SESSION['remote'][] = ['cid' => $r[0]['id'], 'uid' => $r[0]['uid'], 'url' => $r[0]['url']];
536                                         $_SESSION['visitor_id'] = $r[0]['id'];
537                                         $_SESSION['visitor_home'] = $r[0]['url'];
538                                         $_SESSION['visitor_visiting'] = $r[0]['uid'];
539                                         $_SESSION['my_url'] = $r[0]['url'];
540                                         if (!$quiet) {
541                                                 info(L10n::t('%1$s welcomes %2$s', $r[0]['username'], $r[0]['name']) . EOL);
542                                         }
543
544                                         // Visitors get 1 day session.
545                                         $session_id = session_id();
546                                         $expire = time() + 86400;
547                                         q("UPDATE `session` SET `expire` = '%s' WHERE `sid` = '%s'",
548                                                 dbesc($expire),
549                                                 dbesc($session_id)
550                                         );
551                                 }
552
553                                 goaway($dest);
554                         }
555                         goaway($dest);
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                         killme();
568                         // NOTREACHED
569                 }
570         }
571 }