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