]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_notify.php
Merge pull request #4713 from MrPetovan/bug/suppress-profile-message-follow
[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\System;
12 use Friendica\Database\DBM;
13 use Friendica\Model\Contact;
14 use Friendica\Protocol\DFRN;
15
16 require_once 'include/items.php';
17
18 function dfrn_notify_post(App $a) {
19         logger(__function__, LOGGER_TRACE);
20
21         if (empty($_POST)) {
22                 require_once 'mod/salmon.php';
23                 salmon_post($a);
24         }
25
26         $dfrn_id      = ((x($_POST,'dfrn_id'))      ? notags(trim($_POST['dfrn_id']))   : '');
27         $dfrn_version = ((x($_POST,'dfrn_version')) ? (float) $_POST['dfrn_version']    : 2.0);
28         $challenge    = ((x($_POST,'challenge'))    ? notags(trim($_POST['challenge'])) : '');
29         $data         = ((x($_POST,'data'))         ? $_POST['data']                    : '');
30         $key          = ((x($_POST,'key'))          ? $_POST['key']                     : '');
31         $rino_remote  = ((x($_POST,'rino'))         ? intval($_POST['rino'])            :  0);
32         $dissolve     = ((x($_POST,'dissolve'))     ? intval($_POST['dissolve'])        :  0);
33         $perm         = ((x($_POST,'perm'))         ? notags(trim($_POST['perm']))      : 'r');
34         $ssl_policy   = ((x($_POST,'ssl_policy'))   ? notags(trim($_POST['ssl_policy'])): 'none');
35         $page         = ((x($_POST,'page'))         ? intval($_POST['page'])            :  0);
36
37         $forum = (($page == 1) ? 1 : 0);
38         $prv   = (($page == 2) ? 1 : 0);
39
40         $writable = (-1);
41         if ($dfrn_version >= 2.21) {
42                 $writable = (($perm === 'rw') ? 1 : 0);
43         }
44
45         $direction = (-1);
46         if (strpos($dfrn_id, ':') == 1) {
47                 $direction = intval(substr($dfrn_id, 0, 1));
48                 $dfrn_id = substr($dfrn_id, 2);
49         }
50
51         $r = q("SELECT * FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1",
52                 dbesc($dfrn_id),
53                 dbesc($challenge)
54         );
55         if (! DBM::is_result($r)) {
56                 logger('dfrn_notify: could not match challenge to dfrn_id ' . $dfrn_id . ' challenge=' . $challenge);
57                 System::xmlExit(3, 'Could not match challenge');
58         }
59
60         $r = q("DELETE FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s'",
61                 dbesc($dfrn_id),
62                 dbesc($challenge)
63         );
64
65         // find the local user who owns this relationship.
66
67         $sql_extra = '';
68         switch ($direction) {
69                 case (-1):
70                         $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
71                         break;
72                 case 0:
73                         $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
74                         break;
75                 case 1:
76                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
77                         break;
78                 default:
79                         System::xmlExit(3, 'Invalid direction');
80                         break; // NOTREACHED
81         }
82
83         /*
84          * be careful - $importer will contain both the contact information for the contact
85          * sending us the post, and also the user information for the person receiving it.
86          * since they are mixed together, it is easy to get them confused.
87          */
88
89         $r = q("SELECT  `contact`.*, `contact`.`uid` AS `importer_uid`,
90                                         `contact`.`pubkey` AS `cpubkey`,
91                                         `contact`.`prvkey` AS `cprvkey`,
92                                         `contact`.`thumb` AS `thumb`,
93                                         `contact`.`url` as `url`,
94                                         `contact`.`name` as `senderName`,
95                                         `user`.*
96                         FROM `contact`
97                         LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
98                         WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
99                                 AND `user`.`nickname` = '%s' AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 $sql_extra LIMIT 1",
100                 dbesc($a->argv[1])
101         );
102
103         if (! DBM::is_result($r)) {
104                 logger('dfrn_notify: contact not found for dfrn_id ' . $dfrn_id);
105                 System::xmlExit(3, 'Contact not found');
106                 //NOTREACHED
107         }
108
109         // $importer in this case contains the contact record for the remote contact joined with the user record of our user.
110
111         $importer = $r[0];
112
113         logger("Remote rino version: ".$rino_remote." for ".$importer["url"], LOGGER_DEBUG);
114
115         if ((($writable != (-1)) && ($writable != $importer['writable'])) || ($importer['forum'] != $forum) || ($importer['prv'] != $prv)) {
116                 q("UPDATE `contact` SET `writable` = %d, forum = %d, prv = %d WHERE `id` = %d",
117                         intval(($writable == (-1)) ? $importer['writable'] : $writable),
118                         intval($forum),
119                         intval($prv),
120                         intval($importer['id'])
121                 );
122                 if ($writable != (-1)) {
123                         $importer['writable'] = $writable;
124                 }
125                 $importer['forum'] = $page;
126         }
127
128
129         // if contact's ssl policy changed, update our links
130
131         $importer = Contact::updateSslPolicy($importer, $ssl_policy);
132
133         logger('dfrn_notify: received notify from ' . $importer['name'] . ' for ' . $importer['username']);
134         logger('dfrn_notify: data: ' . $data, LOGGER_DATA);
135
136         if ($dissolve == 1) {
137                 // Relationship is dissolved permanently
138                 Contact::remove($importer['id']);
139                 logger('relationship dissolved : ' . $importer['name'] . ' dissolved ' . $importer['username']);
140                 System::xmlExit(0, 'relationship dissolved');
141         }
142
143         $rino = Config::get('system', 'rino_encrypt');
144         $rino = intval($rino);
145
146         logger("Local rino version: " .  $rino, LOGGER_DEBUG);
147
148         if (strlen($key)) {
149
150                 // if local rino is lower than remote rino, abort: should not happen!
151                 // but only for $remote_rino > 1, because old code did't send rino version
152                 if ($rino_remote > 1 && $rino < $rino_remote) {
153                         logger("rino version '$rino_remote' is lower than supported '$rino'");
154                         System::xmlExit(0, "rino version '$rino_remote' is lower than supported '$rino'");
155                 }
156
157                 $rawkey = hex2bin(trim($key));
158                 logger('rino: md5 raw key: ' . md5($rawkey));
159                 $final_key = '';
160
161                 if ($dfrn_version >= 2.1) {
162                         if ((($importer['duplex']) && strlen($importer['cprvkey'])) || (! strlen($importer['cpubkey']))) {
163                                 openssl_private_decrypt($rawkey, $final_key, $importer['cprvkey']);
164                         } else {
165                                 openssl_public_decrypt($rawkey, $final_key, $importer['cpubkey']);
166                         }
167                 } else {
168                         if ((($importer['duplex']) && strlen($importer['cpubkey'])) || (! strlen($importer['cprvkey']))) {
169                                 openssl_public_decrypt($rawkey, $final_key, $importer['cpubkey']);
170                         } else {
171                                 openssl_private_decrypt($rawkey, $final_key, $importer['cprvkey']);
172                         }
173                 }
174
175                 switch($rino_remote) {
176                         case 0:
177                         case 1:
178                                 // we got a key. old code send only the key, without RINO version.
179                                 // we assume RINO 1 if key and no RINO version
180                                 $data = DFRN::aesDecrypt(hex2bin($data), $final_key);
181                                 break;
182                         default:
183                                 logger("rino: invalid sent version '$rino_remote'");
184                                 System::xmlExit(0, "Invalid sent version '$rino_remote'");
185                 }
186
187                 logger('rino: decrypted data: ' . $data, LOGGER_DATA);
188         }
189
190         $ret = DFRN::import($data, $importer);
191         System::xmlExit($ret, 'Processed');
192
193         // NOTREACHED
194 }
195
196
197 function dfrn_notify_content(App $a) {
198
199         if(x($_GET,'dfrn_id')) {
200
201                 /*
202                  * initial communication from external contact, $direction is their direction.
203                  * If this is a duplex communication, ours will be the opposite.
204                  */
205
206                 $dfrn_id = notags(trim($_GET['dfrn_id']));
207                 $dfrn_version = (float) $_GET['dfrn_version'];
208                 $rino_remote = ((x($_GET,'rino')) ? intval($_GET['rino']) : 0);
209                 $type = "";
210                 $last_update = "";
211
212                 logger('dfrn_notify: new notification dfrn_id=' . $dfrn_id);
213
214                 $direction = (-1);
215                 if(strpos($dfrn_id,':') == 1) {
216                         $direction = intval(substr($dfrn_id,0,1));
217                         $dfrn_id = substr($dfrn_id,2);
218                 }
219
220                 $hash = random_string();
221
222                 $status = 0;
223
224                 $r = q("DELETE FROM `challenge` WHERE `expire` < " . intval(time()));
225
226                 $r = q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` , `type`, `last_update` )
227                         VALUES( '%s', '%s', %d, '%s', '%s' ) ",
228                         dbesc($hash),
229                         dbesc($dfrn_id),
230                         intval(time() + 90 ),
231                         dbesc($type),
232                         dbesc($last_update)
233                 );
234
235                 logger('dfrn_notify: challenge=' . $hash, LOGGER_DEBUG);
236
237                 $sql_extra = '';
238                 switch($direction) {
239                         case (-1):
240                                 $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
241                                 $my_id = $dfrn_id;
242                                 break;
243                         case 0:
244                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
245                                 $my_id = '1:' . $dfrn_id;
246                                 break;
247                         case 1:
248                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
249                                 $my_id = '0:' . $dfrn_id;
250                                 break;
251                         default:
252                                 $status = 1;
253                                 break; // NOTREACHED
254                 }
255
256                 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`page-flags` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
257                                 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0 AND `user`.`nickname` = '%s'
258                                 AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 $sql_extra LIMIT 1",
259                                 dbesc($a->argv[1])
260                 );
261
262                 if (! DBM::is_result($r)) {
263                         $status = 1;
264                 }
265
266                 logger("Remote rino version: ".$rino_remote." for ".$r[0]["url"], LOGGER_DEBUG);
267
268                 $challenge    = '';
269                 $encrypted_id = '';
270                 $id_str       = $my_id . '.' . mt_rand(1000,9999);
271
272                 $prv_key = trim($r[0]['prvkey']);
273                 $pub_key = trim($r[0]['pubkey']);
274                 $dplx    = intval($r[0]['duplex']);
275
276                 if ((($dplx) && (strlen($prv_key))) || ((strlen($prv_key)) && (!(strlen($pub_key))))) {
277                         openssl_private_encrypt($hash, $challenge, $prv_key);
278                         openssl_private_encrypt($id_str, $encrypted_id, $prv_key);
279                 } elseif (strlen($pub_key)) {
280                         openssl_public_encrypt($hash, $challenge, $pub_key);
281                         openssl_public_encrypt($id_str, $encrypted_id, $pub_key);
282                 } else {
283                         /// @TODO these kind of else-blocks are making the code harder to understand
284                         $status = 1;
285                 }
286
287                 $challenge    = bin2hex($challenge);
288                 $encrypted_id = bin2hex($encrypted_id);
289
290
291                 $rino = Config::get('system', 'rino_encrypt');
292                 $rino = intval($rino);
293
294                 logger("Local rino version: ". $rino, LOGGER_DEBUG);
295
296                 // if requested rino is lower than enabled local rino, lower local rino version
297                 // if requested rino is higher than enabled local rino, reply with local rino
298                 if ($rino_remote < $rino) {
299                         $rino = $rino_remote;
300                 }
301
302                 if((($r[0]['rel']) && ($r[0]['rel'] != CONTACT_IS_SHARING)) || ($r[0]['page-flags'] == PAGE_COMMUNITY)) {
303                         $perm = 'rw';
304                 } else {
305                         $perm = 'r';
306                 }
307
308                 header("Content-type: text/xml");
309
310                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n"
311                         . '<dfrn_notify>' . "\r\n"
312                         . "\t" . '<status>' . $status . '</status>' . "\r\n"
313                         . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
314                         . "\t" . '<rino>' . $rino . '</rino>' . "\r\n"
315                         . "\t" . '<perm>' . $perm . '</perm>' . "\r\n"
316                         . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n"
317                         . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
318                         . '</dfrn_notify>' . "\r\n" ;
319
320                 killme();
321         }
322
323 }