]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_notify.php
Move Contact::Page_* constants to User::PAGE_FLAGS_*
[friendica.git] / mod / dfrn_notify.php
1 <?php
2
3 /**
4  * @file mod/dfrn_notify.php
5  * @brief The dfrn notify endpoint
6  * @see PDF with dfrn specs: https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
7  */
8
9 use Friendica\App;
10 use Friendica\Core\Config;
11 use Friendica\Core\Logger;
12 use Friendica\Core\System;
13 use Friendica\Database\DBA;
14 use Friendica\Model\Contact;
15 use Friendica\Protocol\DFRN;
16 use Friendica\Protocol\Diaspora;
17 use Friendica\Util\Strings;
18
19 function dfrn_notify_post(App $a) {
20         Logger::log(__function__, Logger::TRACE);
21
22         $postdata = file_get_contents('php://input');
23
24         if (empty($_POST) || !empty($postdata)) {
25                 $data = json_decode($postdata);
26                 if (is_object($data)) {
27                         $nick = defaults($a->argv, 1, '');
28
29                         $user = DBA::selectFirst('user', [], ['nickname' => $nick, 'account_expired' => false, 'account_removed' => false]);
30                         if (!DBA::isResult($user)) {
31                                 System::httpExit(500);
32                         }
33                         dfrn_dispatch_private($user, $postdata);
34                 } elseif (!dfrn_dispatch_public($postdata)) {
35                         require_once 'mod/salmon.php';
36                         salmon_post($a, $postdata);
37                 }
38         }
39
40         $dfrn_id      = (!empty($_POST['dfrn_id'])      ? Strings::escapeTags(trim($_POST['dfrn_id']))   : '');
41         $dfrn_version = (!empty($_POST['dfrn_version']) ? (float) $_POST['dfrn_version']    : 2.0);
42         $challenge    = (!empty($_POST['challenge'])    ? Strings::escapeTags(trim($_POST['challenge'])) : '');
43         $data         = defaults($_POST, 'data', '');
44         $key          = defaults($_POST, 'key', '');
45         $rino_remote  = (!empty($_POST['rino'])         ? intval($_POST['rino'])            :  0);
46         $dissolve     = (!empty($_POST['dissolve'])     ? intval($_POST['dissolve'])        :  0);
47         $perm         = (!empty($_POST['perm'])         ? Strings::escapeTags(trim($_POST['perm']))      : 'r');
48         $ssl_policy   = (!empty($_POST['ssl_policy'])   ? Strings::escapeTags(trim($_POST['ssl_policy'])): 'none');
49         $page         = (!empty($_POST['page'])         ? intval($_POST['page'])            :  0);
50
51         $forum = (($page == 1) ? 1 : 0);
52         $prv   = (($page == 2) ? 1 : 0);
53
54         $writable = (-1);
55         if ($dfrn_version >= 2.21) {
56                 $writable = (($perm === 'rw') ? 1 : 0);
57         }
58
59         $direction = (-1);
60         if (strpos($dfrn_id, ':') == 1) {
61                 $direction = intval(substr($dfrn_id, 0, 1));
62                 $dfrn_id = substr($dfrn_id, 2);
63         }
64
65         if (!DBA::exists('challenge', ['dfrn-id' => $dfrn_id, 'challenge' => $challenge])) {
66                 Logger::log('could not match challenge to dfrn_id ' . $dfrn_id . ' challenge=' . $challenge);
67                 System::xmlExit(3, 'Could not match challenge');
68         }
69
70         DBA::delete('challenge', ['dfrn-id' => $dfrn_id, 'challenge' => $challenge]);
71
72         $user = DBA::selectFirst('user', ['uid'], ['nickname' => $a->argv[1]]);
73         if (!DBA::isResult($user)) {
74                 Logger::log('User not found for nickname ' . $a->argv[1]);
75                 System::xmlExit(3, 'User not found');
76         }
77
78         // find the local user who owns this relationship.
79         $condition = [];
80         switch ($direction) {
81                 case (-1):
82                         $condition = ["(`issued-id` = ? OR `dfrn-id` = ?) AND `uid` = ?", $dfrn_id, $dfrn_id, $user['uid']];
83                         break;
84                 case 0:
85                         $condition = ['issued-id' => $dfrn_id, 'duplex' => true, 'uid' => $user['uid']];
86                         break;
87                 case 1:
88                         $condition = ['dfrn-id' => $dfrn_id, 'duplex' => true, 'uid' => $user['uid']];
89                         break;
90                 default:
91                         System::xmlExit(3, 'Invalid direction');
92                         break; // NOTREACHED
93         }
94
95         $contact = DBA::selectFirst('contact', ['id'], $condition);
96         if (!DBA::isResult($contact)) {
97                 Logger::log('contact not found for dfrn_id ' . $dfrn_id);
98                 System::xmlExit(3, 'Contact not found');
99         }
100
101         // $importer in this case contains the contact record for the remote contact joined with the user record of our user.
102         $importer = DFRN::getImporter($contact['id'], $user['uid']);
103
104         if ((($writable != (-1)) && ($writable != $importer['writable'])) || ($importer['forum'] != $forum) || ($importer['prv'] != $prv)) {
105                 $fields = ['writable' => ($writable == (-1)) ? $importer['writable'] : $writable,
106                         'forum' => $forum, 'prv' => $prv];
107                 DBA::update('contact', $fields, ['id' => $importer['id']]);
108
109                 if ($writable != (-1)) {
110                         $importer['writable'] = $writable;
111                 }
112                 $importer['forum'] = $page;
113         }
114
115
116         // if contact's ssl policy changed, update our links
117
118         $importer = Contact::updateSslPolicy($importer, $ssl_policy);
119
120         Logger::log('data: ' . $data, Logger::DATA);
121
122         if ($dissolve == 1) {
123                 // Relationship is dissolved permanently
124                 Contact::remove($importer['id']);
125                 Logger::log('relationship dissolved : ' . $importer['name'] . ' dissolved ' . $importer['username']);
126                 System::xmlExit(0, 'relationship dissolved');
127         }
128
129         $rino = Config::get('system', 'rino_encrypt');
130         $rino = intval($rino);
131
132         if (strlen($key)) {
133
134                 // if local rino is lower than remote rino, abort: should not happen!
135                 // but only for $remote_rino > 1, because old code did't send rino version
136                 if ($rino_remote > 1 && $rino < $rino_remote) {
137                         Logger::log("rino version '$rino_remote' is lower than supported '$rino'");
138                         System::xmlExit(0, "rino version '$rino_remote' is lower than supported '$rino'");
139                 }
140
141                 $rawkey = hex2bin(trim($key));
142                 Logger::log('rino: md5 raw key: ' . md5($rawkey), Logger::DATA);
143
144                 $final_key = '';
145
146                 if ($dfrn_version >= 2.1) {
147                         if (($importer['duplex'] && strlen($importer['cprvkey'])) || !strlen($importer['cpubkey'])) {
148                                 openssl_private_decrypt($rawkey, $final_key, $importer['cprvkey']);
149                         } else {
150                                 openssl_public_decrypt($rawkey, $final_key, $importer['cpubkey']);
151                         }
152                 } else {
153                         if (($importer['duplex'] && strlen($importer['cpubkey'])) || !strlen($importer['cprvkey'])) {
154                                 openssl_public_decrypt($rawkey, $final_key, $importer['cpubkey']);
155                         } else {
156                                 openssl_private_decrypt($rawkey, $final_key, $importer['cprvkey']);
157                         }
158                 }
159
160                 switch ($rino_remote) {
161                         case 0:
162                         case 1:
163                                 // we got a key. old code send only the key, without RINO version.
164                                 // we assume RINO 1 if key and no RINO version
165                                 $data = DFRN::aesDecrypt(hex2bin($data), $final_key);
166                                 break;
167                         default:
168                                 Logger::log("rino: invalid sent version '$rino_remote'");
169                                 System::xmlExit(0, "Invalid sent version '$rino_remote'");
170                 }
171
172                 Logger::log('rino: decrypted data: ' . $data, Logger::DATA);
173         }
174
175         Logger::log('Importing post from ' . $importer['addr'] . ' to ' . $importer['nickname'] . ' with the RINO ' . $rino_remote . ' encryption.', Logger::DEBUG);
176
177         $ret = DFRN::import($data, $importer);
178         System::xmlExit($ret, 'Processed');
179
180         // NOTREACHED
181 }
182
183 function dfrn_dispatch_public($postdata)
184 {
185         $msg = Diaspora::decodeRaw([], $postdata, true);
186         if (!$msg) {
187                 // We have to fail silently to be able to hand it over to the salmon parser
188                 return false;
189         }
190
191         // Fetch the corresponding public contact
192         $contact = Contact::getDetailsByAddr($msg['author'], 0);
193         if (!$contact) {
194                 Logger::log('Contact not found for address ' . $msg['author']);
195                 System::xmlExit(3, 'Contact ' . $msg['author'] . ' not found');
196         }
197
198         $importer = DFRN::getImporter($contact['id']);
199
200         // This should never fail
201         if (empty($importer)) {
202                 Logger::log('Contact not found for address ' . $msg['author']);
203                 System::xmlExit(3, 'Contact ' . $msg['author'] . ' not found');
204         }
205
206         Logger::log('Importing post from ' . $msg['author'] . ' with the public envelope.', Logger::DEBUG);
207
208         // Now we should be able to import it
209         $ret = DFRN::import($msg['message'], $importer);
210         System::xmlExit($ret, 'Done');
211 }
212
213 function dfrn_dispatch_private($user, $postdata)
214 {
215         $msg = Diaspora::decodeRaw($user, $postdata);
216         if (!$msg) {
217                 System::xmlExit(4, 'Unable to parse message');
218         }
219
220         // Check if the user has got this contact
221         $cid = Contact::getIdForURL($msg['author'], $user['uid']);
222         if (!$cid) {
223                 // Otherwise there should be a public contact
224                 $cid = Contact::getIdForURL($msg['author']);
225                 if (!$cid) {
226                         Logger::log('Contact not found for address ' . $msg['author']);
227                         System::xmlExit(3, 'Contact ' . $msg['author'] . ' not found');
228                 }
229         }
230
231         $importer = DFRN::getImporter($cid, $user['uid']);
232
233         // This should never fail
234         if (empty($importer)) {
235                 Logger::log('Contact not found for address ' . $msg['author']);
236                 System::xmlExit(3, 'Contact ' . $msg['author'] . ' not found');
237         }
238
239         Logger::log('Importing post from ' . $msg['author'] . ' to ' . $user['nickname'] . ' with the private envelope.', Logger::DEBUG);
240
241         // Now we should be able to import it
242         $ret = DFRN::import($msg['message'], $importer);
243         System::xmlExit($ret, 'Done');
244 }
245
246 function dfrn_notify_content(App $a) {
247
248         if (!empty($_GET['dfrn_id'])) {
249
250                 /*
251                  * initial communication from external contact, $direction is their direction.
252                  * If this is a duplex communication, ours will be the opposite.
253                  */
254
255                 $dfrn_id = Strings::escapeTags(trim($_GET['dfrn_id']));
256                 $rino_remote = (!empty($_GET['rino']) ? intval($_GET['rino']) : 0);
257                 $type = "";
258                 $last_update = "";
259
260                 Logger::log('new notification dfrn_id=' . $dfrn_id);
261
262                 $direction = (-1);
263                 if (strpos($dfrn_id,':') == 1) {
264                         $direction = intval(substr($dfrn_id,0,1));
265                         $dfrn_id = substr($dfrn_id,2);
266                 }
267
268                 $hash = Strings::getRandomHex();
269
270                 $status = 0;
271
272                 DBA::delete('challenge', ["`expire` < ?", time()]);
273
274                 $fields = ['challenge' => $hash, 'dfrn-id' => $dfrn_id, 'expire' => time() + 90,
275                         'type' => $type, 'last_update' => $last_update];
276                 DBA::insert('challenge', $fields);
277
278                 Logger::log('challenge=' . $hash, Logger::DATA);
279
280                 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $a->argv[1]]);
281                 if (!DBA::isResult($user)) {
282                         Logger::log('User not found for nickname ' . $a->argv[1]);
283                         exit();
284                 }
285
286                 $condition = [];
287                 switch ($direction) {
288                         case (-1):
289                                 $condition = ["(`issued-id` = ? OR `dfrn-id` = ?) AND `uid` = ?", $dfrn_id, $dfrn_id, $user['uid']];
290                                 $my_id = $dfrn_id;
291                                 break;
292                         case 0:
293                                 $condition = ['issued-id' => $dfrn_id, 'duplex' => true, 'uid' => $user['uid']];
294                                 $my_id = '1:' . $dfrn_id;
295                                 break;
296                         case 1:
297                                 $condition = ['dfrn-id' => $dfrn_id, 'duplex' => true, 'uid' => $user['uid']];
298                                 $my_id = '0:' . $dfrn_id;
299                                 break;
300                         default:
301                                 $status = 1;
302                                 break;
303                 }
304
305                 $contact = DBA::selectFirst('contact', ['id'], $condition);
306                 if (!DBA::isResult($contact)) {
307                         Logger::log('contact not found for dfrn_id ' . $dfrn_id);
308                         System::xmlExit(3, 'Contact not found');
309                 }
310
311                 // $importer in this case contains the contact record for the remote contact joined with the user record of our user.
312                 $importer = DFRN::getImporter($contact['id'], $user['uid']);
313                 if (empty($importer)) {
314                         Logger::log('No importer data found for user ' . $a->argv[1] . ' and contact ' . $dfrn_id);
315                         exit();
316                 }
317
318                 Logger::log("Remote rino version: ".$rino_remote." for ".$importer["url"], Logger::DATA);
319
320                 $challenge    = '';
321                 $encrypted_id = '';
322                 $id_str       = $my_id . '.' . mt_rand(1000,9999);
323
324                 $prv_key = trim($importer['cprvkey']);
325                 $pub_key = trim($importer['cpubkey']);
326                 $dplx    = intval($importer['duplex']);
327
328                 if (($dplx && strlen($prv_key)) || (strlen($prv_key) && !strlen($pub_key))) {
329                         openssl_private_encrypt($hash, $challenge, $prv_key);
330                         openssl_private_encrypt($id_str, $encrypted_id, $prv_key);
331                 } elseif (strlen($pub_key)) {
332                         openssl_public_encrypt($hash, $challenge, $pub_key);
333                         openssl_public_encrypt($id_str, $encrypted_id, $pub_key);
334                 } else {
335                         /// @TODO these kind of else-blocks are making the code harder to understand
336                         $status = 1;
337                 }
338
339                 $challenge    = bin2hex($challenge);
340                 $encrypted_id = bin2hex($encrypted_id);
341
342
343                 $rino = Config::get('system', 'rino_encrypt');
344                 $rino = intval($rino);
345
346                 Logger::log("Local rino version: ". $rino, Logger::DATA);
347
348                 // if requested rino is lower than enabled local rino, lower local rino version
349                 // if requested rino is higher than enabled local rino, reply with local rino
350                 if ($rino_remote < $rino) {
351                         $rino = $rino_remote;
352                 }
353
354                 if (($importer['rel'] && ($importer['rel'] != Contact::SHARING)) || ($importer['page-flags'] == User::PAGE_FLAGS_COMMUNITY)) {
355                         $perm = 'rw';
356                 } else {
357                         $perm = 'r';
358                 }
359
360                 header("Content-type: text/xml");
361
362                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n"
363                         . '<dfrn_notify>' . "\r\n"
364                         . "\t" . '<status>' . $status . '</status>' . "\r\n"
365                         . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
366                         . "\t" . '<rino>' . $rino . '</rino>' . "\r\n"
367                         . "\t" . '<perm>' . $perm . '</perm>' . "\r\n"
368                         . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n"
369                         . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
370                         . '</dfrn_notify>' . "\r\n";
371
372                 exit();
373         }
374 }