]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_confirm.php
77f436374b837be6b94358dc796dce10db9f0832
[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                 // Note: We can send any of these things as binary blobs because they are being POST'ed.
93                 // Any protocol conversations (notify, poll) which perform GET require bin2hex of all the 
94                 // binary stuff. 
95
96                 $src_aes_key = random_string();
97
98                 $result = '';
99                 openssl_private_encrypt($dfrn_id,$result,$a->user['prvkey']);
100
101                 $params['dfrn_id'] = bin2hex($result);
102                 $params['public_key'] = $public_key;
103
104
105                 $my_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
106
107                 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
108                 $params['source_url'] = bin2hex($params['source_url']);
109
110                 if($aes_allow && function_exists('openssl_encrypt')) {
111                         openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
112                         $params['aes_key'] = bin2hex($params['aes_key']);
113                         $params['public_key'] = bin2hex(openssl_encrypt($public_key,'AES-256-CBC',$src_aes_key));
114                 }
115
116                 $params['dfrn_version'] = '2.0';
117                 if($duplex == 1)
118                         $params['duplex'] = 1;
119
120                 // POST all this stuff to the other site.
121
122                 $res = post_url($dfrn_confirm,$params);
123
124                 // Now figure out what they responded. Try to be robust if the remote site is 
125                 // having difficulty and throwing up errors of some kind. 
126
127                 $leading_junk = substr($res,0,strpos($res,'<?xml'));
128
129                 $res = substr($res,strpos($res,'<?xml'));
130                 if(! strlen($res)) {
131
132                                 // No XML at all, this exchange is messed up really bad.
133                                 // We shouldn't proceed, because the xml parser might choke,
134                                 // and $status is going to be zero, which indicates success.
135                                 // We can hardly call this a success.  
136
137                         notice( t('Response from remote site was not understood.') . EOL);
138                         return;
139                 }
140
141                 if(strlen($leading_junk) && get_config('system','debugging')) {
142
143                                 // This might be more common. Mixed error text and some XML.
144                                 // If we're configured for debugging, show the text. Proceed in either case.
145
146                         notice( t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL );
147                 }
148
149                 $xml = simplexml_load_string($res);
150                 $status = (int) $xml->status;
151                 $message = unxmlify($xml->message);   // human readable text of what may have gone wrong.
152                 switch($status) {
153                         case 0:
154                                 notice( t("Confirmation completed successfully.") . EOL);
155                                 if(strlen($message))
156                                         notice( t('Remote site reported: ') . $message . EOL);
157                                 break;
158                         case 1:
159                                 // birthday paradox - generate new dfrn-id and fall through.
160                                 $new_dfrn_id = random_string();
161                                 $r = q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
162                                         dbesc($new_dfrn_id),
163                                         intval($contact_id),
164                                         intval($uid) 
165                                 );
166
167                         case 2:
168                                 notice( t("Temporary failure. Please wait and try again.") . EOL);
169                                 if(strlen($message))
170                                         notice( t('Remote site reported: ') . $message . EOL);
171                                 break;
172
173
174                         case 3:
175                                 notice( t("Introduction failed or was revoked.") . EOL);
176                                 if(strlen($message))
177                                         notice( t('Remote site reported: ') . $message . EOL);
178                                 break;
179                         }
180
181                 if(($status == 0) && ($intro_id)) {
182
183                         // Success. Delete the notification.
184
185                         $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d LIMIT 1",
186                                 intval($intro_id),
187                                 intval($uid)
188                         );
189                         
190                 }
191
192                 if($status != 0) 
193                         return;
194                 
195                 // We have now established a relationship with the other site.
196                 // Let's make our own personal copy of their profile photo so we don't have
197                 // to always load it from their site.
198
199                 require_once("Photo.php");
200
201                 $photo_failure = false;
202
203                 $r = q("SELECT `photo` FROM `contact` WHERE `id` = %d LIMIT 1",
204                         intval($contact_id));
205                 if(count($r)) {
206
207                         $filename = basename($r[0]['photo']);
208                         $img_str = fetch_url($r[0]['photo'],true);
209                         $img = new Photo($img_str);
210                         if($img->is_valid()) {
211
212                                 $img->scaleImageSquare(175);
213                                         
214                                 $hash = photo_new_resource();
215
216                                 $r = $img->store($uid, $contact_id, $hash, $filename, t('Contact Photos'), 4 );
217
218                                 if($r === false)
219                                         $photo_failure = true;
220
221                                 $img->scaleImage(80);
222
223                                 $r = $img->store($uid, $contact_id, $hash, $filename, t('Contact Photos'), 5 );
224
225                                 if($r === false)
226                                         $photo_failure = true;
227
228                                 $photo = $a->get_baseurl() . '/photo/' . $hash . '-4.jpg';
229                                 $thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.jpg';
230                         }
231                         else
232                                 $photo_failure = true;
233                 }
234                 else
235                         $photo_failure = true;
236
237                 if($photo_failure) {
238                         $photo = $a->get_baseurl() . '/images/default-profile.jpg';
239                         $thumb = $a->get_baseurl() . '/images/default-profile-sm.jpg';
240                 }
241
242                 $new_relation = REL_VIP;
243                 if(($relation == REL_FAN) || ($duplex))
244                         $new_relation = REL_BUD;
245
246                 $r = q("UPDATE `contact` SET `photo` = '%s', 
247                         `thumb` = '%s', 
248                         `rel` = %d, 
249                         `name-date` = '%s', 
250                         `uri-date` = '%s', 
251                         `avatar-date` = '%s', 
252                         `blocked` = 0, 
253                         `pending` = 0,
254                         `duplex` = %d,
255                         `network` = 'dfrn' WHERE `id` = %d LIMIT 1
256                 ",
257                         dbesc($photo),
258                         dbesc($thumb),
259                         intval($new_relation),
260                         dbesc(datetime_convert()),
261                         dbesc(datetime_convert()),
262                         dbesc(datetime_convert()),
263                         intval($duplex),
264                         intval($contact_id)
265                 );
266                 if($r === false)
267                         notice( t('Unable to set contact photo.') . EOL);
268
269
270                 // Let's send our user to the contact editor in case they want to
271                 // do anything special with this new friend.
272  
273                 goaway($a->get_baseurl() . '/contacts/' . intval($contact_id));
274                 return;  //NOTREACHED
275         }
276
277
278
279         // End of first scenario. [Local confirmation of remote friend request].
280
281
282
283         // Begin scenario two. This is the remote response to the above scenario.
284         // This will take place on the site that originally initiated the friend request.
285         // In the section above where the confirming party makes a POST and 
286         // retrieves xml status information, they are communicating with the following code.
287
288         if(x($_POST,'source_url')) {
289
290                 // We are processing an external confirmation to an introduction created by our user.
291
292                 $public_key = $_POST['public_key'];
293                 $dfrn_id    = hex2bin($_POST['dfrn_id']);
294                 $source_url = hex2bin($_POST['source_url']);
295                 $aes_key    = hex2bin($_POST['aes_key']);
296                 $duplex     = $_POST['duplex'];
297                 $version_id = $_POST['dfrn_version'];
298
299                 // Find our user's account
300
301                 $r = q("SELECT * FROM `user` WHERE `nickname` = '%s' LIMIT 1",
302                         dbesc($node));
303
304                 if(! count($r)) {
305                         $message = t('No user record found for ') . '\'' . $node . '\'';
306                         xml_status(3,$message); // failure
307                         // NOTREACHED
308                 }
309
310                 $my_prvkey = $r[0]['prvkey'];
311                 $local_uid = $r[0]['uid'];
312
313
314                 if(! strstr($my_prvkey,'BEGIN RSA PRIVATE KEY')) {
315                         $message = t('Our site encryption key is apparently messed up.');
316                         xml_status(3,$message);
317                 }
318
319                 // verify everything
320
321                 $decrypted_source_url = "";
322                 openssl_private_decrypt($source_url,$decrypted_source_url,$my_prvkey);
323
324
325                 if(! strlen($decrypted_source_url)) {
326                         $message = t('Empty site URL was provided or URL could not be decrypted by us.');
327                         xml_status(3,$message);
328                         // NOTREACHED
329                 }
330
331                 $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
332                         dbesc($decrypted_source_url),
333                         intval($local_uid)
334                 );
335
336                 if(! count($ret)) {
337                         // this is either a bogus confirmation (?) or we deleted the original introduction.
338                         $message = t('Contact record was not found for you on our site.');
339                         xml_status(3,$message);
340                         return; // NOTREACHED 
341                 }
342
343                 $relation = $ret[0]['rel'];
344
345                 // Decrypt all this stuff we just received
346
347                 $foreign_pubkey = $ret[0]['site-pubkey'];
348                 $dfrn_record    = $ret[0]['id'];
349
350                 $decrypted_dfrn_id = "";
351                 openssl_public_decrypt($dfrn_id,$decrypted_dfrn_id,$foreign_pubkey);
352
353                 if(strlen($aes_key)) {
354                         $decrypted_aes_key = "";
355                         openssl_private_decrypt($aes_key,$decrypted_aes_key,$my_prvkey);
356                         $dfrn_pubkey = openssl_decrypt($public_key,'AES-256-CBC',$decrypted_aes_key);
357                 }
358                 else {
359                         $dfrn_pubkey = $public_key;
360                 }
361
362                 $r = q("SELECT * FROM `contact` WHERE `dfrn-id` = '%s' LIMIT 1",
363                         dbesc($decrypted_dfrn_id),
364                         intval($local_uid)
365                 );
366                 if(count($r)) {
367                         $message = t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
368                         xml_status(1,$message); // Birthday paradox - duplicate dfrn-id
369                         // NOTREACHED
370                 }
371
372                 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d LIMIT 1",
373                         dbesc($decrypted_dfrn_id),
374                         dbesc($dfrn_pubkey),
375                         intval($dfrn_record)
376                 );
377                 if(! count($r)) {
378                         $message = t('Unable to set your contact credentials on our system.');
379                         xml_status(3,$message);
380                 }
381
382                 // We're good but now we have to scrape the profile photo and send notifications.
383
384                 require_once("Photo.php");
385
386                 $photo_failure = false;
387
388                 $r = q("SELECT `photo` FROM `contact` WHERE `id` = %d LIMIT 1",
389                         intval($dfrn_record));
390                 if(count($r)) {
391
392                         $filename = basename($r[0]['photo']);
393                         $img_str = fetch_url($r[0]['photo'],true);
394                         $img = new Photo($img_str);
395                         if($img->is_valid()) {
396
397                                 $img->scaleImageSquare(175);
398                                         
399                                 $hash = photo_new_resource();
400
401                                 $r = $img->store($local_uid, $dfrn_record, $hash, $filename, t('Contact Photos') , 4);
402
403                                 if($r === false)
404                                         $photo_failure = true;
405                                         
406                                 $img->scaleImage(80);
407                                 $r = $img->store($local_uid, $dfrn_record, $hash, $filename, t('Contact Photos') , 5);
408
409                                 if($r === false)
410                                         $photo_failure = true;
411
412                                 $photo = $a->get_baseurl() . '/photo/' . $hash . '-4.jpg';
413                                 $thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.jpg';      
414                         }
415                         else
416                                 $photo_failure = true;
417                 }
418                 else
419                         $photo_failure = true;
420
421                 if($photo_failure) {
422                         $photo = $a->get_baseurl() . '/images/default-profile.jpg';
423                         $thumb = $a->get_baseurl() . '/images/default-profile-sm.jpg';
424                 }
425
426                 $new_relation = REL_FAN;
427                 if(($relation == REL_VIP) || ($duplex))
428                         $new_relation = REL_BUD;
429
430                 $r = q("UPDATE `contact` SET 
431                         `photo` = '%s', 
432                         `thumb` = '%s', 
433                         `rel` = %d, 
434                         `name-date` = '%s', 
435                         `uri-date` = '%s', 
436                         `avatar-date` = '%s', 
437                         `blocked` = 0, 
438                         `pending` = 0,
439                         `duplex` = %d, 
440                         `network` = 'dfrn' WHERE `id` = %d LIMIT 1
441                 ",
442                         dbesc($photo),
443                         dbesc($thumb),
444                         intval($new_relation),
445                         dbesc(datetime_convert()),
446                         dbesc(datetime_convert()),
447                         dbesc(datetime_convert()),
448                         intval($duplex),
449                         intval($dfrn_record)
450                 );
451                 if($r === false) { // indicates schema is messed up or total db failure
452                         $message = t('Unable to update your contact profile details on our system');
453                         xml_status(3,$message);
454                 }
455
456                 // Otherwise everything seems to have worked and we are almost done. Yay!
457                 // Send an email notification
458
459                 $r = q("SELECT * FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
460                         WHERE `contact`.`id` = %d LIMIT 1",
461                         intval($dfrn_record)
462                 );
463                 if((count($r)) && ($r[0]['notify-flags'] & NOTIFY_CONFIRM)) {
464
465                         $tpl = (($new_relation == REL_BUD) 
466                                 ? load_view_file('view/friend_complete_eml.tpl')
467                                 : load_view_file('view/intro_complete_eml.tpl'));
468                 
469                         $email_tpl = replace_macros($tpl, array(
470                                 '$sitename' => $a->config['sitename'],
471                                 '$siteurl' =>  $a->get_baseurl(),
472                                 '$username' => $r[0]['username'],
473                                 '$email' => $r[0]['email'],
474                                 '$fn' => $r[0]['name'],
475                                 '$dfrn_url' => $r[0]['url'],
476                                 '$uid' => $newuid )
477                         );
478         
479                         $res = mail($r[0]['email'], t("Connection accepted at ") . $a->config['sitename'],
480                                 $email_tpl, 'From: ' . t('Administrator') . '@' . $_SERVER[SERVER_NAME] );
481                         if(!$res) {
482                                 notice( t("Email notification failed.") . EOL );
483                         }
484                 }
485                 xml_status(0); // Success
486                 return; // NOTREACHED
487
488                         ////////////////////// End of this scenario ///////////////////////////////////////////////
489         }
490
491         // somebody arrived here by mistake or they are fishing. Send them to the homepage.
492
493         goaway($a->get_baseurl());
494         // NOTREACHED
495
496 }