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