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