]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_confirm.php
cleanup to ensure protocol version is passed properly. We will need it if/when any...
[friendica.git] / mod / dfrn_confirm.php
1 <?php
2
3 // There are two possible entry points. Both are called via POST.
4
5 function dfrn_confirm_post(&$a) {
6
7         if($a->argc > 1)
8                 $node = $a->argv[1];
9
10                 // Main entry point. Our user received a friend request notification (perhaps 
11                 // from another site) and clicked 'Accept'. $POST['source_url'] is not set.
12                 // They will perform the following:
13
14         if(! x($_POST,'source_url')) {
15
16                 $uid = get_uid();
17
18                 if(! $uid) {
19                         notice( t('Permission denied.') . EOL );
20                         return;
21                 }       
22
23                 // These come from the friend request notification form.
24         
25                 $dfrn_id  = ((x($_POST,'dfrn_id')) ? notags(trim($_POST['dfrn_id'])) : "");
26                 $intro_id = intval($_POST['intro_id']);
27                 $duplex   = intval($_POST['duplex']);
28
29
30                 // The other person will have been issued an ID when they first requested friendship.
31                 // Locate their record. At this time, their record will have both pending and blocked set to 1. 
32
33                 $r = q("SELECT * FROM `contact` WHERE `issued-id` = '%s' AND `uid` = %d LIMIT 1",
34                                 dbesc($dfrn_id),
35                                 intval($uid)
36                 );
37
38                 if(! count($r)) {
39                         notice( t('Contact not found.') . EOL );
40                         return;
41                 }
42
43                 $contact_id   = $r[0]['id'];
44                 $relation     = $r[0]['rel'];
45                 $site_pubkey  = $r[0]['site-pubkey'];
46                 $dfrn_confirm = $r[0]['confirm'];
47                 $aes_allow    = $r[0]['aes_allow'];
48
49
50                 // Generate a key pair for all further communications with this person.
51                 // We have a keypair for every contact, and a site key for unknown people.
52                 // This provides a means to carry on relationships with other people if 
53                 // any single key is compromised. It is a robust key. We're much more 
54                 // worried about key leakage than anybody cracking it.  
55
56                 $res = openssl_pkey_new(array(
57                         'digest_alg' => 'whirlpool',
58                         'private_key_bits' => 4096,
59                         'encrypt_key' => false )
60                 );
61
62
63                 $private_key = '';
64
65                 openssl_pkey_export($res, $private_key);
66
67                 $pubkey = openssl_pkey_get_details($res);
68                 $public_key = $pubkey["key"];
69
70                 // Save the private key. Send them the public key.
71
72                 $r = q("UPDATE `contact` SET `prvkey` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
73                         dbesc($private_key),
74                         intval($contact_id),
75                         intval($uid) 
76                 );
77
78
79                 $params = array();
80
81                 // Per the protocol document, we will verify both ends by encrypting the dfrn_id with our 
82                 // site private key (person on the other end can decrypt it with our site public key).
83                 // Then encrypt our profile URL with the other person's site public key. They can decrypt
84                 // it with their site private key. If the decryption on the other end fails for either
85                 // item, it indicates tampering or key failure on at least one site and we will not be 
86                 // able to provide a secure communication pathway.
87
88                 // If other site is willing to accept full encryption, (aes_allow is 1 AND we have php5.3 
89                 // or later) then we encrypt the personal public key we send them using AES-256-CBC and a 
90                 // random key which is encrypted with their site public key.  
91
92                 $src_aes_key = random_string();
93
94                 $result = '';
95                 openssl_private_encrypt($dfrn_id,$result,$a->user['prvkey']);
96
97                 $params['dfrn_id'] = bin2hex($result);
98                 $params['public_key'] = $public_key;
99
100
101                 $my_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
102
103                 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
104                 $params['source_url'] = bin2hex($params['source_url']);
105
106                 if($aes_allow && function_exists('openssl_encrypt')) {
107                         openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
108                         $params['aes_key'] = bin2hex($params['aes_key']);
109                         $params['public_key'] = bin2hex(openssl_encrypt($public_key,'AES-256-CBC',$src_aes_key));
110                 }
111
112                 $params['dfrn_version'] = DFRN_PROTOCOL_VERSION ;
113                 if($duplex == 1)
114                         $params['duplex'] = 1;
115
116                 // POST all this stuff to the other site.
117
118                 $res = post_url($dfrn_confirm,$params);
119
120                 // Now figure out what they responded. Try to be robust if the remote site is 
121                 // having difficulty and throwing up errors of some kind. 
122
123                 $leading_junk = substr($res,0,strpos($res,'<?xml'));
124
125                 $res = substr($res,strpos($res,'<?xml'));
126                 if(! strlen($res)) {
127
128                                 // No XML at all, this exchange is messed up really bad.
129                                 // We shouldn't proceed, because the xml parser might choke,
130                                 // and $status is going to be zero, which indicates success.
131                                 // We can hardly call this a success.  
132
133                         notice( t('Response from remote site was not understood.') . EOL);
134                         return;
135                 }
136
137                 if(strlen($leading_junk) && get_config('system','debugging')) {
138
139                                 // This might be more common. Mixed error text and some XML.
140                                 // If we're configured for debugging, show the text. Proceed in either case.
141
142                         notice( t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL );
143                 }
144
145                 $xml = simplexml_load_string($res);
146                 $status = (int) $xml->status;
147                 $message = unxmlify($xml->message);   // human readable text of what may have gone wrong.
148                 switch($status) {
149                         case 0:
150                                 notice( t("Confirmation completed successfully.") . EOL);
151                                 if(strlen($message))
152                                         notice( t('Remote site reported: ') . $message . EOL);
153                                 break;
154                         case 1:
155                                 // birthday paradox - generate new dfrn-id and fall through.
156                                 $new_dfrn_id = random_string();
157                                 $r = q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
158                                         dbesc($new_dfrn_id),
159                                         intval($contact_id),
160                                         intval($uid) 
161                                 );
162
163                         case 2:
164                                 notice( t("Temporary failure. Please wait and try again.") . EOL);
165                                 if(strlen($message))
166                                         notice( t('Remote site reported: ') . $message . EOL);
167                                 break;
168
169
170                         case 3:
171                                 notice( t("Introduction failed or was revoked.") . EOL);
172                                 if(strlen($message))
173                                         notice( t('Remote site reported: ') . $message . EOL);
174                                 break;
175                         }
176
177                 if(($status == 0) && ($intro_id)) {
178
179                         // Success. Delete the notification.
180
181                         $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d LIMIT 1",
182                                 intval($intro_id),
183                                 intval($uid)
184                         );
185                         
186                 }
187
188                 if($status != 0) 
189                         return;
190                 
191                 // We have now established a relationship with the other site.
192                 // Let's make our own personal copy of their profile photo so we don't have
193                 // to always load it from their site.
194
195                 require_once("Photo.php");
196
197                 $photo_failure = false;
198
199                 $r = q("SELECT `photo` FROM `contact` WHERE `id` = %d LIMIT 1",
200                         intval($contact_id));
201                 if(count($r)) {
202
203                         $filename = basename($r[0]['photo']);
204                         $img_str = fetch_url($r[0]['photo'],true);
205                         $img = new Photo($img_str);
206                         if($img->is_valid()) {
207
208                                 $img->scaleImageSquare(175);
209                                         
210                                 $hash = photo_new_resource();
211
212                                 $r = $img->store($uid, $contact_id, $hash, $filename, t('Contact Photos'), 4 );
213
214                                 if($r === false)
215                                         $photo_failure = true;
216
217                                 $img->scaleImage(80);
218
219                                 $r = $img->store($uid, $contact_id, $hash, $filename, t('Contact Photos'), 5 );
220
221                                 if($r === false)
222                                         $photo_failure = true;
223
224                                 $photo = $a->get_baseurl() . '/photo/' . $hash . '-4.jpg';
225                                 $thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.jpg';
226                         }
227                         else
228                                 $photo_failure = true;
229                 }
230                 else
231                         $photo_failure = true;
232
233                 if($photo_failure) {
234                         $photo = $a->get_baseurl() . '/images/default-profile.jpg';
235                         $thumb = $a->get_baseurl() . '/images/default-profile-sm.jpg';
236                 }
237
238                 $new_relation = REL_VIP;
239                 if(($relation == REL_FAN) || ($duplex))
240                         $new_relation = REL_BUD;
241
242                 $r = q("UPDATE `contact` SET `photo` = '%s', 
243                         `thumb` = '%s', 
244                         `rel` = %d, 
245                         `name-date` = '%s', 
246                         `uri-date` = '%s', 
247                         `avatar-date` = '%s', 
248                         `blocked` = 0, 
249                         `pending` = 0,
250                         `duplex` = %d,
251                         `network` = 'dfrn' WHERE `id` = %d LIMIT 1
252                 ",
253                         dbesc($photo),
254                         dbesc($thumb),
255                         intval($new_relation),
256                         dbesc(datetime_convert()),
257                         dbesc(datetime_convert()),
258                         dbesc(datetime_convert()),
259                         intval($duplex),
260                         intval($contact_id)
261                 );
262                 if($r === false)
263                         notice( t('Unable to set contact photo.') . EOL);
264
265
266                 // Let's send our user to the contact editor in case they want to
267                 // do anything special with this new friend.
268  
269                 goaway($a->get_baseurl() . '/contacts/' . intval($contact_id));
270                 return;  //NOTREACHED
271         }
272
273
274
275         // End of first scenario. [Local confirmation of remote friend request].
276
277
278
279         // Begin scenario two. This is the remote response to the above scenario.
280         // This will take place on the site that originally initiated the friend request.
281         // In the section above where the confirming party makes a POST and 
282         // retrieves xml status information, they are communicating with the following code.
283
284         if(x($_POST,'source_url')) {
285
286                 // We are processing an external confirmation to an introduction created by our user.
287
288                 $public_key = $_POST['public_key'];
289                 $dfrn_id    = hex2bin($_POST['dfrn_id']);
290                 $source_url = hex2bin($_POST['source_url']);
291                 $aes_key    = $_POST['aes_key'];
292                 $duplex     = $_POST['duplex'];
293                 $version_id = (float) $_POST['dfrn_version'];
294
295
296                 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
297
298                 if(x($aes_key)) {
299                         $aes_key = hex2bin($aes_key);
300                         $public_key = hex2bin($public_key);
301                 }
302
303                 // Find our user's account
304
305                 $r = q("SELECT * FROM `user` WHERE `nickname` = '%s' LIMIT 1",
306                         dbesc($node));
307
308                 if(! count($r)) {
309                         $message = t('No user record found for ') . '\'' . $node . '\'';
310                         xml_status(3,$message); // failure
311                         // NOTREACHED
312                 }
313
314                 $my_prvkey = $r[0]['prvkey'];
315                 $local_uid = $r[0]['uid'];
316
317
318                 if(! strstr($my_prvkey,'BEGIN RSA PRIVATE KEY')) {
319                         $message = t('Our site encryption key is apparently messed up.');
320                         xml_status(3,$message);
321                 }
322
323                 // verify everything
324
325                 $decrypted_source_url = "";
326                 openssl_private_decrypt($source_url,$decrypted_source_url,$my_prvkey);
327
328
329                 if(! strlen($decrypted_source_url)) {
330                         $message = t('Empty site URL was provided or URL could not be decrypted by us.');
331                         xml_status(3,$message);
332                         // NOTREACHED
333                 }
334
335                 $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
336                         dbesc($decrypted_source_url),
337                         intval($local_uid)
338                 );
339
340                 if(! count($ret)) {
341                         // this is either a bogus confirmation (?) or we deleted the original introduction.
342                         $message = t('Contact record was not found for you on our site.');
343                         xml_status(3,$message);
344                         return; // NOTREACHED 
345                 }
346
347                 $relation = $ret[0]['rel'];
348
349                 // Decrypt all this stuff we just received
350
351                 $foreign_pubkey = $ret[0]['site-pubkey'];
352                 $dfrn_record    = $ret[0]['id'];
353
354                 $decrypted_dfrn_id = "";
355                 openssl_public_decrypt($dfrn_id,$decrypted_dfrn_id,$foreign_pubkey);
356
357                 if(strlen($aes_key)) {
358                         $decrypted_aes_key = "";
359                         openssl_private_decrypt($aes_key,$decrypted_aes_key,$my_prvkey);
360                         $dfrn_pubkey = openssl_decrypt($public_key,'AES-256-CBC',$decrypted_aes_key);
361                 }
362                 else {
363                         $dfrn_pubkey = $public_key;
364                 }
365
366                 $r = q("SELECT * FROM `contact` WHERE `dfrn-id` = '%s' LIMIT 1",
367                         dbesc($decrypted_dfrn_id),
368                         intval($local_uid)
369                 );
370                 if(count($r)) {
371                         $message = t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
372                         xml_status(1,$message); // Birthday paradox - duplicate dfrn-id
373                         // NOTREACHED
374                 }
375
376                 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d LIMIT 1",
377                         dbesc($decrypted_dfrn_id),
378                         dbesc($dfrn_pubkey),
379                         intval($dfrn_record)
380                 );
381                 if(! count($r)) {
382                         $message = t('Unable to set your contact credentials on our system.');
383                         xml_status(3,$message);
384                 }
385
386                 // We're good but now we have to scrape the profile photo and send notifications.
387
388                 require_once("Photo.php");
389
390                 $photo_failure = false;
391
392                 $r = q("SELECT `photo` FROM `contact` WHERE `id` = %d LIMIT 1",
393                         intval($dfrn_record));
394                 if(count($r)) {
395
396                         $filename = basename($r[0]['photo']);
397                         $img_str = fetch_url($r[0]['photo'],true);
398                         $img = new Photo($img_str);
399                         if($img->is_valid()) {
400
401                                 $img->scaleImageSquare(175);
402                                         
403                                 $hash = photo_new_resource();
404
405                                 $r = $img->store($local_uid, $dfrn_record, $hash, $filename, t('Contact Photos') , 4);
406
407                                 if($r === false)
408                                         $photo_failure = true;
409                                         
410                                 $img->scaleImage(80);
411                                 $r = $img->store($local_uid, $dfrn_record, $hash, $filename, t('Contact Photos') , 5);
412
413                                 if($r === false)
414                                         $photo_failure = true;
415
416                                 $photo = $a->get_baseurl() . '/photo/' . $hash . '-4.jpg';
417                                 $thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.jpg';      
418                         }
419                         else
420                                 $photo_failure = true;
421                 }
422                 else
423                         $photo_failure = true;
424
425                 if($photo_failure) {
426                         $photo = $a->get_baseurl() . '/images/default-profile.jpg';
427                         $thumb = $a->get_baseurl() . '/images/default-profile-sm.jpg';
428                 }
429
430                 $new_relation = REL_FAN;
431                 if(($relation == REL_VIP) || ($duplex))
432                         $new_relation = REL_BUD;
433
434                 $r = q("UPDATE `contact` SET 
435                         `photo` = '%s', 
436                         `thumb` = '%s', 
437                         `rel` = %d, 
438                         `name-date` = '%s', 
439                         `uri-date` = '%s', 
440                         `avatar-date` = '%s', 
441                         `blocked` = 0, 
442                         `pending` = 0,
443                         `duplex` = %d, 
444                         `network` = 'dfrn' WHERE `id` = %d LIMIT 1
445                 ",
446                         dbesc($photo),
447                         dbesc($thumb),
448                         intval($new_relation),
449                         dbesc(datetime_convert()),
450                         dbesc(datetime_convert()),
451                         dbesc(datetime_convert()),
452                         intval($duplex),
453                         intval($dfrn_record)
454                 );
455                 if($r === false) { // indicates schema is messed up or total db failure
456                         $message = t('Unable to update your contact profile details on our system');
457                         xml_status(3,$message);
458                 }
459
460                 // Otherwise everything seems to have worked and we are almost done. Yay!
461                 // Send an email notification
462
463                 $r = q("SELECT * FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
464                         WHERE `contact`.`id` = %d LIMIT 1",
465                         intval($dfrn_record)
466                 );
467                 if((count($r)) && ($r[0]['notify-flags'] & NOTIFY_CONFIRM)) {
468
469                         $tpl = (($new_relation == REL_BUD) 
470                                 ? load_view_file('view/friend_complete_eml.tpl')
471                                 : load_view_file('view/intro_complete_eml.tpl'));
472                 
473                         $email_tpl = replace_macros($tpl, array(
474                                 '$sitename' => $a->config['sitename'],
475                                 '$siteurl' =>  $a->get_baseurl(),
476                                 '$username' => $r[0]['username'],
477                                 '$email' => $r[0]['email'],
478                                 '$fn' => $r[0]['name'],
479                                 '$dfrn_url' => $r[0]['url'],
480                                 '$uid' => $newuid )
481                         );
482         
483                         $res = mail($r[0]['email'], t("Connection accepted at ") . $a->config['sitename'],
484                                 $email_tpl, 'From: ' . t('Administrator') . '@' . $_SERVER[SERVER_NAME] );
485                         if(!$res) {
486                                 // pointless throwing an error here and confusing the person at the other end of the wire.
487                         }
488                 }
489                 xml_status(0); // Success
490                 return; // NOTREACHED
491
492                         ////////////////////// End of this scenario ///////////////////////////////////////////////
493         }
494
495         // somebody arrived here by mistake or they are fishing. Send them to the homepage.
496
497         goaway($a->get_baseurl());
498         // NOTREACHED
499
500 }