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