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