]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_confirm.php
infrastructure for swat0 (#fsw)
[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                 $photos = import_profile_photo($contact['photo'],$uid,$contact_id);
233
234                 if($contact['network'] === 'dfrn') {
235
236                         $new_relation = REL_VIP;
237                         if(($relation == REL_FAN) || ($duplex))
238                                 $new_relation = REL_BUD;
239
240                         $r = q("UPDATE `contact` SET `photo` = '%s', 
241                                 `thumb` = '%s', 
242                                 `rel` = %d, 
243                                 `name-date` = '%s', 
244                                 `uri-date` = '%s', 
245                                 `avatar-date` = '%s', 
246                                 `blocked` = 0, 
247                                 `pending` = 0,
248                                 `duplex` = %d,
249                                 `network` = 'dfrn' WHERE `id` = %d LIMIT 1
250                         ",
251                                 dbesc($photos[0]),
252                                 dbesc($photos[1]),
253                                 intval($new_relation),
254                                 dbesc(datetime_convert()),
255                                 dbesc(datetime_convert()),
256                                 dbesc(datetime_convert()),
257                                 intval($duplex),
258                                 intval($contact_id)
259                         );
260                 }
261                 else {  
262
263                         $notify = '';
264                         $poll   = '';
265
266                         // $contact['network'] !== 'dfrn'
267
268                         $arr = lrdd($contact['url']);
269                         if(count($arr)) {
270                                 foreach($arr as $link) {
271                                         if($link['@attributes']['rel'] === 'salmon')
272                                                 $notify = $link['@attributes']['href'];
273                                         if($link['@attributes']['rel'] === NAMESPACE_FEED)
274                                                 $poll = $link['@attributes']['href'];
275                                 }
276                         }
277
278                         $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d LIMIT 1",
279                                 intval($intro_id),
280                                 intval($uid)
281                         );
282
283                         $r = q("UPDATE `contact` SET `photo` = '%s', 
284                                 `thumb` = '%s', 
285                                 `name-date` = '%s', 
286                                 `uri-date` = '%s', 
287                                 `avatar-date` = '%s', 
288                                 `notify` = '%s',
289                                 `poll` = '%s',
290                                 `blocked` = 0, 
291                                 `pending` = 0
292                                 WHERE `id` = %d LIMIT 1
293                         ",
294                                 dbesc($photos[0]),
295                                 dbesc($photos[1]),
296                                 dbesc(datetime_convert()),
297                                 dbesc(datetime_convert()),
298                                 dbesc(datetime_convert()),
299                                 dbesc($notify),
300                                 dbesc($poll),
301                                 intval($contact_id)
302                         );                      
303                 }
304
305                 if($r === false)
306                                 notice( t('Unable to set contact photo.') . EOL);
307
308
309                 // Let's send our user to the contact editor in case they want to
310                 // do anything special with this new friend.
311
312                 if($handsfree === null)
313                         goaway($a->get_baseurl() . '/contacts/' . intval($contact_id));
314                 return;  //NOTREACHED
315
316         }
317
318
319
320         // End of first scenario. [Local confirmation of remote friend request].
321
322
323
324         // Begin scenario two. This is the remote response to the above scenario.
325         // This will take place on the site that originally initiated the friend request.
326         // In the section above where the confirming party makes a POST and 
327         // retrieves xml status information, they are communicating with the following code.
328
329         if(x($_POST,'source_url')) {
330
331                 // We are processing an external confirmation to an introduction created by our user.
332
333                 $public_key = $_POST['public_key'];
334                 $dfrn_id    = hex2bin($_POST['dfrn_id']);
335                 $source_url = hex2bin($_POST['source_url']);
336                 $aes_key    = $_POST['aes_key'];
337                 $duplex     = $_POST['duplex'];
338                 $version_id = (float) $_POST['dfrn_version'];
339
340
341                 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
342
343                 if(x($aes_key)) {
344                         $aes_key = hex2bin($aes_key);
345                         $public_key = hex2bin($public_key);
346                 }
347
348                 // Find our user's account
349
350                 $r = q("SELECT * FROM `user` WHERE `nickname` = '%s' LIMIT 1",
351                         dbesc($node));
352
353                 if(! count($r)) {
354                         $message = t('No user record found for ') . '\'' . $node . '\'';
355                         xml_status(3,$message); // failure
356                         // NOTREACHED
357                 }
358
359                 $my_prvkey = $r[0]['prvkey'];
360                 $local_uid = $r[0]['uid'];
361
362
363                 if(! strstr($my_prvkey,'BEGIN RSA PRIVATE KEY')) {
364                         $message = t('Our site encryption key is apparently messed up.');
365                         xml_status(3,$message);
366                 }
367
368                 // verify everything
369
370                 $decrypted_source_url = "";
371                 openssl_private_decrypt($source_url,$decrypted_source_url,$my_prvkey);
372
373
374                 if(! strlen($decrypted_source_url)) {
375                         $message = t('Empty site URL was provided or URL could not be decrypted by us.');
376                         xml_status(3,$message);
377                         // NOTREACHED
378                 }
379
380                 $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
381                         dbesc($decrypted_source_url),
382                         intval($local_uid)
383                 );
384
385                 if(! count($ret)) {
386                         // this is either a bogus confirmation (?) or we deleted the original introduction.
387                         $message = t('Contact record was not found for you on our site.');
388                         xml_status(3,$message);
389                         return; // NOTREACHED 
390                 }
391
392                 $relation = $ret[0]['rel'];
393
394                 // Decrypt all this stuff we just received
395
396                 $foreign_pubkey = $ret[0]['site-pubkey'];
397                 $dfrn_record    = $ret[0]['id'];
398
399                 $decrypted_dfrn_id = "";
400                 openssl_public_decrypt($dfrn_id,$decrypted_dfrn_id,$foreign_pubkey);
401
402                 if(strlen($aes_key)) {
403                         $decrypted_aes_key = "";
404                         openssl_private_decrypt($aes_key,$decrypted_aes_key,$my_prvkey);
405                         $dfrn_pubkey = openssl_decrypt($public_key,'AES-256-CBC',$decrypted_aes_key);
406                 }
407                 else {
408                         $dfrn_pubkey = $public_key;
409                 }
410
411                 $r = q("SELECT * FROM `contact` WHERE `dfrn-id` = '%s' LIMIT 1",
412                         dbesc($decrypted_dfrn_id),
413                         intval($local_uid)
414                 );
415                 if(count($r)) {
416                         $message = t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
417                         xml_status(1,$message); // Birthday paradox - duplicate dfrn-id
418                         // NOTREACHED
419                 }
420
421                 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d LIMIT 1",
422                         dbesc($decrypted_dfrn_id),
423                         dbesc($dfrn_pubkey),
424                         intval($dfrn_record)
425                 );
426                 if(! count($r)) {
427                         $message = t('Unable to set your contact credentials on our system.');
428                         xml_status(3,$message);
429                 }
430
431                 // We're good but now we have to scrape the profile photo and send notifications.
432
433
434
435                 $r = q("SELECT `photo` FROM `contact` WHERE `id` = %d LIMIT 1",
436                         intval($dfrn_record));
437
438                 if(count($r))
439                         $photo = $r[0]['photo'];
440                 else
441                         $photo = $a->get_baseurl() . '/images/default-profile.jpg';
442                                 
443                 require_once("Photo.php");
444
445                 $photos = import_profile_photo($photo,$local_uid,$dfrn_record);
446
447                 $new_relation = REL_FAN;
448                 if(($relation == REL_VIP) || ($duplex))
449                         $new_relation = REL_BUD;
450
451                 $r = q("UPDATE `contact` SET 
452                         `photo` = '%s', 
453                         `thumb` = '%s', 
454                         `rel` = %d, 
455                         `name-date` = '%s', 
456                         `uri-date` = '%s', 
457                         `avatar-date` = '%s', 
458                         `blocked` = 0, 
459                         `pending` = 0,
460                         `duplex` = %d, 
461                         `network` = 'dfrn' WHERE `id` = %d LIMIT 1
462                 ",
463                         dbesc($photos[0]),
464                         dbesc($photos[1]),
465                         intval($new_relation),
466                         dbesc(datetime_convert()),
467                         dbesc(datetime_convert()),
468                         dbesc(datetime_convert()),
469                         intval($duplex),
470                         intval($dfrn_record)
471                 );
472                 if($r === false) {    // indicates schema is messed up or total db failure
473                         $message = t('Unable to update your contact profile details on our system');
474                         xml_status(3,$message);
475                 }
476
477                 // Otherwise everything seems to have worked and we are almost done. Yay!
478                 // Send an email notification
479
480                 $r = q("SELECT * FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
481                         WHERE `contact`.`id` = %d LIMIT 1",
482                         intval($dfrn_record)
483                 );
484                 if((count($r)) && ($r[0]['notify-flags'] & NOTIFY_CONFIRM)) {
485
486                         $tpl = (($new_relation == REL_BUD) 
487                                 ? load_view_file('view/friend_complete_eml.tpl')
488                                 : load_view_file('view/intro_complete_eml.tpl'));
489                 
490                         $email_tpl = replace_macros($tpl, array(
491                                 '$sitename' => $a->config['sitename'],
492                                 '$siteurl' =>  $a->get_baseurl(),
493                                 '$username' => $r[0]['username'],
494                                 '$email' => $r[0]['email'],
495                                 '$fn' => $r[0]['name'],
496                                 '$dfrn_url' => $r[0]['url'],
497                                 '$uid' => $newuid )
498                         );
499         
500                         $res = mail($r[0]['email'], t("Connection accepted at ") . $a->config['sitename'],
501                                 $email_tpl, 'From: ' . t('Administrator') . '@' . $_SERVER[SERVER_NAME] );
502                         if(!$res) {
503                                 // pointless throwing an error here and confusing the person at the other end of the wire.
504                         }
505                 }
506                 xml_status(0); // Success
507                 return; // NOTREACHED
508
509                         ////////////////////// End of this scenario ///////////////////////////////////////////////
510         }
511
512         // somebody arrived here by mistake or they are fishing. Send them to the homepage.
513
514         goaway($a->get_baseurl());
515         // NOTREACHED
516
517 }