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