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