]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_poll.php
Docs: add a note on adding `use` on theme.php
[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                         dba::delete('profile_check', ["`expire` < ?", 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                         dba::delete('profile_check', ["`expire` < ?", 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                         dba::delete('profile_check', ["`expire` < ?", 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         dba::delete('challenge', ['dfrn-id' => $dfrn_id, 'challenge' => $challenge]);
309
310         $sql_extra = '';
311         switch ($direction) {
312                 case -1:
313                         $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
314                         $my_id = $dfrn_id;
315                         break;
316                 case 0:
317                         $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
318                         $my_id = '1:' . $dfrn_id;
319                         break;
320                 case 1:
321                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
322                         $my_id = '0:' . $dfrn_id;
323                         break;
324                 default:
325                         goaway(System::baseUrl());
326                         break; // NOTREACHED
327         }
328
329         $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 $sql_extra LIMIT 1");
330         if (!DBM::is_result($r)) {
331                 killme();
332         }
333
334         $contact = $r[0];
335         $owner_uid = $r[0]['uid'];
336         $contact_id = $r[0]['id'];
337
338         if ($type === 'reputation' && strlen($url)) {
339                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
340                         dbesc($url),
341                         intval($owner_uid)
342                 );
343                 $reputation = 0;
344                 $text = '';
345
346                 if (DBM::is_result($r)) {
347                         $reputation = $r[0]['rating'];
348                         $text = $r[0]['reason'];
349
350                         if ($r[0]['id'] == $contact_id) { // inquiring about own reputation not allowed
351                                 $reputation = 0;
352                                 $text = '';
353                         }
354                 }
355
356                 echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
357                 <reputation>
358                         <url>$url</url>
359                         <rating>$reputation</rating>
360                         <description>$text</description>
361                 </reputation>
362                 ";
363                 killme();
364                 // NOTREACHED
365         } else {
366                 // Update the writable flag if it changed
367                 logger('dfrn_poll: post request feed: ' . print_r($_POST, true), LOGGER_DATA);
368                 if ($dfrn_version >= 2.21) {
369                         if ($perm === 'rw') {
370                                 $writable = 1;
371                         } else {
372                                 $writable = 0;
373                         }
374
375                         if ($writable != $contact['writable']) {
376                                 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d",
377                                         intval($writable),
378                                         intval($contact_id)
379                                 );
380                         }
381                 }
382
383                 header("Content-type: application/atom+xml");
384                 $o = DFRN::feed($dfrn_id, $a->argv[1], $last_update, $direction);
385                 echo $o;
386                 killme();
387         }
388 }
389
390 function dfrn_poll_content(App $a)
391 {
392         $dfrn_id         = x($_GET,'dfrn_id')         ? $_GET['dfrn_id']              : '';
393         $type            = x($_GET,'type')            ? $_GET['type']                 : 'data';
394         $last_update     = x($_GET,'last_update')     ? $_GET['last_update']          : '';
395         $destination_url = x($_GET,'destination_url') ? $_GET['destination_url']      : '';
396         $sec             = x($_GET,'sec')             ? $_GET['sec']                  : '';
397         $dfrn_version    = x($_GET,'dfrn_version')    ? (float) $_GET['dfrn_version'] : 2.0;
398         $perm            = x($_GET,'perm')            ? $_GET['perm']                 : 'r';
399         $quiet           = x($_GET,'quiet')           ? true                          : false;
400
401         $direction = -1;
402         if (strpos($dfrn_id, ':') == 1) {
403                 $direction = intval(substr($dfrn_id, 0, 1));
404                 $dfrn_id = substr($dfrn_id, 2);
405         }
406
407         if ($dfrn_id != '') {
408                 // initial communication from external contact
409                 $hash = random_string();
410
411                 $status = 0;
412
413                 dba::delete('challenge', ["`expire` < ?", time()]);
414
415                 if ($type !== 'profile') {
416                         $r = q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` , `type`, `last_update` )
417                                 VALUES( '%s', '%s', '%s', '%s', '%s' ) ",
418                                 dbesc($hash),
419                                 dbesc($dfrn_id),
420                                 intval(time() + 60 ),
421                                 dbesc($type),
422                                 dbesc($last_update)
423                         );
424                 }
425
426                 $sql_extra = '';
427                 switch ($direction) {
428                         case -1:
429                                 if ($type === 'profile') {
430                                         $sql_extra = sprintf(" AND ( `dfrn-id` = '%s' OR `issued-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
431                                 } else {
432                                         $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
433                                 }
434
435                                 $my_id = $dfrn_id;
436                                 break;
437                         case 0:
438                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
439                                 $my_id = '1:' . $dfrn_id;
440                                 break;
441                         case 1:
442                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
443                                 $my_id = '0:' . $dfrn_id;
444                                 break;
445                         default:
446                                 goaway(System::baseUrl());
447                                 break; // NOTREACHED
448                 }
449
450                 $nickname = $a->argv[1];
451
452                 $r = q("SELECT `contact`.*, `user`.`username`, `user`.`nickname`
453                         FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
454                         WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
455                         AND `user`.`nickname` = '%s' $sql_extra LIMIT 1",
456                         dbesc($nickname)
457                 );
458                 if (DBM::is_result($r)) {
459                         $challenge = '';
460                         $encrypted_id = '';
461                         $id_str = $my_id . '.' . mt_rand(1000, 9999);
462
463                         if (($r[0]['duplex'] && strlen($r[0]['pubkey'])) || !strlen($r[0]['prvkey'])) {
464                                 openssl_public_encrypt($hash, $challenge, $r[0]['pubkey']);
465                                 openssl_public_encrypt($id_str, $encrypted_id, $r[0]['pubkey']);
466                         } else {
467                                 openssl_private_encrypt($hash, $challenge, $r[0]['prvkey']);
468                                 openssl_private_encrypt($id_str, $encrypted_id, $r[0]['prvkey']);
469                         }
470
471                         $challenge = bin2hex($challenge);
472                         $encrypted_id = bin2hex($encrypted_id);
473                 } else {
474                         $status = 1;
475                         $challenge = '';
476                         $encrypted_id = '';
477                 }
478
479                 if (($type === 'profile') && (strlen($sec))) {
480                         // URL reply
481                         if ($dfrn_version < 2.2) {
482                                 $s = Network::fetchUrl($r[0]['poll']
483                                         . '?dfrn_id=' . $encrypted_id
484                                         . '&type=profile-check'
485                                         . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
486                                         . '&challenge=' . $challenge
487                                         . '&sec=' . $sec
488                                 );
489                         } else {
490                                 $s = Network::post($r[0]['poll'], [
491                                         'dfrn_id' => $encrypted_id,
492                                         'type' => 'profile-check',
493                                         'dfrn_version' => DFRN_PROTOCOL_VERSION,
494                                         'challenge' => $challenge,
495                                         'sec' => $sec
496                                 ]);
497                         }
498
499                         $profile = ((DBM::is_result($r) && $r[0]['nickname']) ? $r[0]['nickname'] : $nickname);
500
501                         switch ($destination_url) {
502                                 case 'profile':
503                                         $dest = System::baseUrl() . '/profile/' . $profile . '?f=&tab=profile';
504                                         break;
505                                 case 'photos':
506                                         $dest = System::baseUrl() . '/photos/' . $profile;
507                                         break;
508                                 case 'status':
509                                 case '':
510                                         $dest = System::baseUrl() . '/profile/' . $profile;
511                                         break;
512                                 default:
513                                         $appendix = (strstr($destination_url, '?') ? '&f=&redir=1' : '?f=&redir=1');
514                                         $dest = $destination_url . $appendix;
515                                         break;
516                         }
517
518                         logger("dfrn_poll: sec profile: " . $s, LOGGER_DATA);
519
520                         if (strlen($s) && strstr($s, '<?xml')) {
521                                 $xml = XML::parseString($s);
522
523                                 logger('dfrn_poll: profile: parsed xml: ' . print_r($xml, true), LOGGER_DATA);
524
525                                 logger('dfrn_poll: secure profile: challenge: ' . $xml->challenge . ' expecting ' . $hash);
526                                 logger('dfrn_poll: secure profile: sec: ' . $xml->sec . ' expecting ' . $sec);
527
528                                 if (((int) $xml->status == 0) && ($xml->challenge == $hash) && ($xml->sec == $sec)) {
529                                         $_SESSION['authenticated'] = 1;
530                                         if (!x($_SESSION, 'remote')) {
531                                                 $_SESSION['remote'] = [];
532                                         }
533
534                                         $_SESSION['remote'][] = ['cid' => $r[0]['id'], 'uid' => $r[0]['uid'], 'url' => $r[0]['url']];
535                                         $_SESSION['visitor_id'] = $r[0]['id'];
536                                         $_SESSION['visitor_home'] = $r[0]['url'];
537                                         $_SESSION['visitor_visiting'] = $r[0]['uid'];
538                                         if (!$quiet) {
539                                                 info(L10n::t('%1$s welcomes %2$s', $r[0]['username'], $r[0]['name']) . EOL);
540                                         }
541
542                                         // Visitors get 1 day session.
543                                         $session_id = session_id();
544                                         $expire = time() + 86400;
545                                         q("UPDATE `session` SET `expire` = '%s' WHERE `sid` = '%s'",
546                                                 dbesc($expire),
547                                                 dbesc($session_id)
548                                         );
549                                 }
550
551                                 goaway($dest);
552                         }
553                         goaway($dest);
554                         // NOTREACHED
555                 } else {
556                         // XML reply
557                         header("Content-type: text/xml");
558                         echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n"
559                                 . '<dfrn_poll>' . "\r\n"
560                                 . "\t" . '<status>' . $status . '</status>' . "\r\n"
561                                 . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
562                                 . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n"
563                                 . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
564                                 . '</dfrn_poll>' . "\r\n";
565                         killme();
566                         // NOTREACHED
567                 }
568         }
569 }