]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_poll.php
Remove unused global cache constants
[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                                         if (!$quiet) {
123                                                 info(L10n::t('%1$s welcomes %2$s', $r[0]['username'], $r[0]['name']) . EOL);
124                                         }
125
126                                         // Visitors get 1 day session.
127                                         $session_id = session_id();
128                                         $expire = time() + 86400;
129                                         q("UPDATE `session` SET `expire` = '%s' WHERE `sid` = '%s'",
130                                                 dbesc($expire),
131                                                 dbesc($session_id)
132                                         );
133                                 }
134                         }
135                         $profile = $r[0]['nickname'];
136                         goaway((strlen($destination_url)) ? $destination_url : System::baseUrl() . '/profile/' . $profile);
137                 }
138                 goaway(System::baseUrl());
139         }
140
141         if ($type === 'profile-check' && $dfrn_version < 2.2) {
142                 if ((strlen($challenge)) && (strlen($sec))) {
143                         q("DELETE FROM `profile_check` WHERE `expire` < " . intval(time()));
144                         $r = q("SELECT * FROM `profile_check` WHERE `sec` = '%s' ORDER BY `expire` DESC LIMIT 1",
145                                 dbesc($sec)
146                         );
147                         if (!DBM::is_result($r)) {
148                                 System::xmlExit(3, 'No ticket');
149                                 // NOTREACHED
150                         }
151
152                         $orig_id = $r[0]['dfrn_id'];
153                         if (strpos($orig_id, ':')) {
154                                 $orig_id = substr($orig_id, 2);
155                         }
156
157                         $c = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
158                                 intval($r[0]['cid'])
159                         );
160                         if (!DBM::is_result($c)) {
161                                 System::xmlExit(3, 'No profile');
162                         }
163
164                         $contact = $c[0];
165
166                         $sent_dfrn_id = hex2bin($dfrn_id);
167                         $challenge = hex2bin($challenge);
168
169                         $final_dfrn_id = '';
170
171                         if (($contact['duplex']) && strlen($contact['prvkey'])) {
172                                 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
173                                 openssl_private_decrypt($challenge, $decoded_challenge, $contact['prvkey']);
174                         } else {
175                                 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
176                                 openssl_public_decrypt($challenge, $decoded_challenge, $contact['pubkey']);
177                         }
178
179                         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
180
181                         if (strpos($final_dfrn_id, ':') == 1) {
182                                 $final_dfrn_id = substr($final_dfrn_id, 2);
183                         }
184
185                         if ($final_dfrn_id != $orig_id) {
186                                 logger('profile_check: ' . $final_dfrn_id . ' != ' . $orig_id, LOGGER_DEBUG);
187                                 // did not decode properly - cannot trust this site
188                                 System::xmlExit(3, 'Bad decryption');
189                         }
190
191                         header("Content-type: text/xml");
192                         echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?><dfrn_poll><status>0</status><challenge>$decoded_challenge</challenge><sec>$sec</sec></dfrn_poll>";
193                         killme();
194                         // NOTREACHED
195                 } else {
196                         // old protocol
197                         switch ($direction) {
198                                 case 1:
199                                         $dfrn_id = '0:' . $dfrn_id;
200                                         break;
201                                 case 0:
202                                         $dfrn_id = '1:' . $dfrn_id;
203                                         break;
204                                 default:
205                                         break;
206                         }
207
208                         q("DELETE FROM `profile_check` WHERE `expire` < " . intval(time()));
209                         $r = q("SELECT * FROM `profile_check` WHERE `dfrn_id` = '%s' ORDER BY `expire` DESC",
210                                 dbesc($dfrn_id));
211                         if (DBM::is_result($r)) {
212                                 System::xmlExit(1);
213                                 return; // NOTREACHED
214                         }
215                         System::xmlExit(0);
216                         return; // NOTREACHED
217                 }
218         }
219 }
220
221 function dfrn_poll_post(App $a)
222 {
223         $dfrn_id      = x($_POST,'dfrn_id')      ? $_POST['dfrn_id']              : '';
224         $challenge    = x($_POST,'challenge')    ? $_POST['challenge']            : '';
225         $url          = x($_POST,'url')          ? $_POST['url']                  : '';
226         $sec          = x($_POST,'sec')          ? $_POST['sec']                  : '';
227         $ptype        = x($_POST,'type')         ? $_POST['type']                 : '';
228         $dfrn_version = x($_POST,'dfrn_version') ? (float) $_POST['dfrn_version'] : 2.0;
229         $perm         = x($_POST,'perm')         ? $_POST['perm']                 : 'r';
230
231         if ($ptype === 'profile-check') {
232                 if (strlen($challenge) && strlen($sec)) {
233                         logger('dfrn_poll: POST: profile-check');
234
235                         q("DELETE FROM `profile_check` WHERE `expire` < " . intval(time()));
236                         $r = q("SELECT * FROM `profile_check` WHERE `sec` = '%s' ORDER BY `expire` DESC LIMIT 1",
237                                 dbesc($sec)
238                         );
239                         if (!DBM::is_result($r)) {
240                                 System::xmlExit(3, 'No ticket');
241                                 // NOTREACHED
242                         }
243
244                         $orig_id = $r[0]['dfrn_id'];
245                         if (strpos($orig_id, ':')) {
246                                 $orig_id = substr($orig_id, 2);
247                         }
248
249                         $c = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
250                                 intval($r[0]['cid'])
251                         );
252                         if (!DBM::is_result($c)) {
253                                 System::xmlExit(3, 'No profile');
254                         }
255
256                         $contact = $c[0];
257
258                         $sent_dfrn_id = hex2bin($dfrn_id);
259                         $challenge = hex2bin($challenge);
260
261                         $final_dfrn_id = '';
262
263                         if ($contact['duplex'] && strlen($contact['prvkey'])) {
264                                 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
265                                 openssl_private_decrypt($challenge, $decoded_challenge, $contact['prvkey']);
266                         } else {
267                                 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
268                                 openssl_public_decrypt($challenge, $decoded_challenge, $contact['pubkey']);
269                         }
270
271                         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
272
273                         if (strpos($final_dfrn_id, ':') == 1) {
274                                 $final_dfrn_id = substr($final_dfrn_id, 2);
275                         }
276
277                         if ($final_dfrn_id != $orig_id) {
278                                 logger('profile_check: ' . $final_dfrn_id . ' != ' . $orig_id, LOGGER_DEBUG);
279                                 // did not decode properly - cannot trust this site
280                                 System::xmlExit(3, 'Bad decryption');
281                         }
282
283                         header("Content-type: text/xml");
284                         echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?><dfrn_poll><status>0</status><challenge>$decoded_challenge</challenge><sec>$sec</sec></dfrn_poll>";
285                         killme();
286                         // NOTREACHED
287                 }
288         }
289
290         $direction = -1;
291         if (strpos($dfrn_id, ':') == 1) {
292                 $direction = intval(substr($dfrn_id, 0, 1));
293                 $dfrn_id = substr($dfrn_id, 2);
294         }
295
296         $r = q("SELECT * FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1",
297                 dbesc($dfrn_id),
298                 dbesc($challenge)
299         );
300
301         if (!DBM::is_result($r)) {
302                 killme();
303         }
304
305         $type = $r[0]['type'];
306         $last_update = $r[0]['last_update'];
307
308         $r = q("DELETE FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s'",
309                 dbesc($dfrn_id),
310                 dbesc($challenge)
311         );
312
313
314         $sql_extra = '';
315         switch ($direction) {
316                 case -1:
317                         $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
318                         $my_id = $dfrn_id;
319                         break;
320                 case 0:
321                         $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
322                         $my_id = '1:' . $dfrn_id;
323                         break;
324                 case 1:
325                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
326                         $my_id = '0:' . $dfrn_id;
327                         break;
328                 default:
329                         goaway(System::baseUrl());
330                         break; // NOTREACHED
331         }
332
333         $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 $sql_extra LIMIT 1");
334         if (!DBM::is_result($r)) {
335                 killme();
336         }
337
338         $contact = $r[0];
339         $owner_uid = $r[0]['uid'];
340         $contact_id = $r[0]['id'];
341
342         if ($type === 'reputation' && strlen($url)) {
343                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
344                         dbesc($url),
345                         intval($owner_uid)
346                 );
347                 $reputation = 0;
348                 $text = '';
349
350                 if (DBM::is_result($r)) {
351                         $reputation = $r[0]['rating'];
352                         $text = $r[0]['reason'];
353
354                         if ($r[0]['id'] == $contact_id) { // inquiring about own reputation not allowed
355                                 $reputation = 0;
356                                 $text = '';
357                         }
358                 }
359
360                 echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
361                 <reputation>
362                         <url>$url</url>
363                         <rating>$reputation</rating>
364                         <description>$text</description>
365                 </reputation>
366                 ";
367                 killme();
368                 // NOTREACHED
369         } else {
370                 // Update the writable flag if it changed
371                 logger('dfrn_poll: post request feed: ' . print_r($_POST, true), LOGGER_DATA);
372                 if ($dfrn_version >= 2.21) {
373                         if ($perm === 'rw') {
374                                 $writable = 1;
375                         } else {
376                                 $writable = 0;
377                         }
378
379                         if ($writable != $contact['writable']) {
380                                 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d",
381                                         intval($writable),
382                                         intval($contact_id)
383                                 );
384                         }
385                 }
386
387                 header("Content-type: application/atom+xml");
388                 $o = DFRN::feed($dfrn_id, $a->argv[1], $last_update, $direction);
389                 echo $o;
390                 killme();
391         }
392 }
393
394 function dfrn_poll_content(App $a)
395 {
396         $dfrn_id         = x($_GET,'dfrn_id')         ? $_GET['dfrn_id']              : '';
397         $type            = x($_GET,'type')            ? $_GET['type']                 : 'data';
398         $last_update     = x($_GET,'last_update')     ? $_GET['last_update']          : '';
399         $destination_url = x($_GET,'destination_url') ? $_GET['destination_url']      : '';
400         $sec             = x($_GET,'sec')             ? $_GET['sec']                  : '';
401         $dfrn_version    = x($_GET,'dfrn_version')    ? (float) $_GET['dfrn_version'] : 2.0;
402         $perm            = x($_GET,'perm')            ? $_GET['perm']                 : 'r';
403         $quiet           = x($_GET,'quiet')           ? true                          : false;
404
405         $direction = -1;
406         if (strpos($dfrn_id, ':') == 1) {
407                 $direction = intval(substr($dfrn_id, 0, 1));
408                 $dfrn_id = substr($dfrn_id, 2);
409         }
410
411         if ($dfrn_id != '') {
412                 // initial communication from external contact
413                 $hash = random_string();
414
415                 $status = 0;
416
417                 $r = q("DELETE FROM `challenge` WHERE `expire` < " . intval(time()));
418
419                 if ($type !== 'profile') {
420                         $r = q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` , `type`, `last_update` )
421                                 VALUES( '%s', '%s', '%s', '%s', '%s' ) ",
422                                 dbesc($hash),
423                                 dbesc($dfrn_id),
424                                 intval(time() + 60 ),
425                                 dbesc($type),
426                                 dbesc($last_update)
427                         );
428                 }
429
430                 $sql_extra = '';
431                 switch ($direction) {
432                         case -1:
433                                 if ($type === 'profile') {
434                                         $sql_extra = sprintf(" AND ( `dfrn-id` = '%s' OR `issued-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
435                                 } else {
436                                         $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
437                                 }
438
439                                 $my_id = $dfrn_id;
440                                 break;
441                         case 0:
442                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
443                                 $my_id = '1:' . $dfrn_id;
444                                 break;
445                         case 1:
446                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
447                                 $my_id = '0:' . $dfrn_id;
448                                 break;
449                         default:
450                                 goaway(System::baseUrl());
451                                 break; // NOTREACHED
452                 }
453
454                 $nickname = $a->argv[1];
455
456                 $r = q("SELECT `contact`.*, `user`.`username`, `user`.`nickname`
457                         FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
458                         WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
459                         AND `user`.`nickname` = '%s' $sql_extra LIMIT 1",
460                         dbesc($nickname)
461                 );
462                 if (DBM::is_result($r)) {
463                         $challenge = '';
464                         $encrypted_id = '';
465                         $id_str = $my_id . '.' . mt_rand(1000, 9999);
466
467                         if (($r[0]['duplex'] && strlen($r[0]['pubkey'])) || !strlen($r[0]['prvkey'])) {
468                                 openssl_public_encrypt($hash, $challenge, $r[0]['pubkey']);
469                                 openssl_public_encrypt($id_str, $encrypted_id, $r[0]['pubkey']);
470                         } else {
471                                 openssl_private_encrypt($hash, $challenge, $r[0]['prvkey']);
472                                 openssl_private_encrypt($id_str, $encrypted_id, $r[0]['prvkey']);
473                         }
474
475                         $challenge = bin2hex($challenge);
476                         $encrypted_id = bin2hex($encrypted_id);
477                 } else {
478                         $status = 1;
479                         $challenge = '';
480                         $encrypted_id = '';
481                 }
482
483                 if (($type === 'profile') && (strlen($sec))) {
484                         // URL reply
485                         if ($dfrn_version < 2.2) {
486                                 $s = Network::fetchUrl($r[0]['poll']
487                                         . '?dfrn_id=' . $encrypted_id
488                                         . '&type=profile-check'
489                                         . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
490                                         . '&challenge=' . $challenge
491                                         . '&sec=' . $sec
492                                 );
493                         } else {
494                                 $s = Network::post($r[0]['poll'], [
495                                         'dfrn_id' => $encrypted_id,
496                                         'type' => 'profile-check',
497                                         'dfrn_version' => DFRN_PROTOCOL_VERSION,
498                                         'challenge' => $challenge,
499                                         'sec' => $sec
500                                 ]);
501                         }
502
503                         $profile = ((DBM::is_result($r) && $r[0]['nickname']) ? $r[0]['nickname'] : $nickname);
504
505                         switch ($destination_url) {
506                                 case 'profile':
507                                         $dest = System::baseUrl() . '/profile/' . $profile . '?f=&tab=profile';
508                                         break;
509                                 case 'photos':
510                                         $dest = System::baseUrl() . '/photos/' . $profile;
511                                         break;
512                                 case 'status':
513                                 case '':
514                                         $dest = System::baseUrl() . '/profile/' . $profile;
515                                         break;
516                                 default:
517                                         $appendix = (strstr($destination_url, '?') ? '&f=&redir=1' : '?f=&redir=1');
518                                         $dest = $destination_url . $appendix;
519                                         break;
520                         }
521
522                         logger("dfrn_poll: sec profile: " . $s, LOGGER_DATA);
523
524                         if (strlen($s) && strstr($s, '<?xml')) {
525                                 $xml = XML::parseString($s);
526
527                                 logger('dfrn_poll: profile: parsed xml: ' . print_r($xml, true), LOGGER_DATA);
528
529                                 logger('dfrn_poll: secure profile: challenge: ' . $xml->challenge . ' expecting ' . $hash);
530                                 logger('dfrn_poll: secure profile: sec: ' . $xml->sec . ' expecting ' . $sec);
531
532                                 if (((int) $xml->status == 0) && ($xml->challenge == $hash) && ($xml->sec == $sec)) {
533                                         $_SESSION['authenticated'] = 1;
534                                         if (!x($_SESSION, 'remote')) {
535                                                 $_SESSION['remote'] = [];
536                                         }
537
538                                         $_SESSION['remote'][] = ['cid' => $r[0]['id'], 'uid' => $r[0]['uid'], 'url' => $r[0]['url']];
539                                         $_SESSION['visitor_id'] = $r[0]['id'];
540                                         $_SESSION['visitor_home'] = $r[0]['url'];
541                                         $_SESSION['visitor_visiting'] = $r[0]['uid'];
542                                         if (!$quiet) {
543                                                 info(L10n::t('%1$s welcomes %2$s', $r[0]['username'], $r[0]['name']) . EOL);
544                                         }
545
546                                         // Visitors get 1 day session.
547                                         $session_id = session_id();
548                                         $expire = time() + 86400;
549                                         q("UPDATE `session` SET `expire` = '%s' WHERE `sid` = '%s'",
550                                                 dbesc($expire),
551                                                 dbesc($session_id)
552                                         );
553                                 }
554
555                                 goaway($dest);
556                         }
557                         goaway($dest);
558                         // NOTREACHED
559                 } else {
560                         // XML reply
561                         header("Content-type: text/xml");
562                         echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n"
563                                 . '<dfrn_poll>' . "\r\n"
564                                 . "\t" . '<status>' . $status . '</status>' . "\r\n"
565                                 . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
566                                 . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n"
567                                 . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
568                                 . '</dfrn_poll>' . "\r\n";
569                         killme();
570                         // NOTREACHED
571                 }
572         }
573 }