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