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