3 // There are two possible entry points. Both are called via POST.
5 function dfrn_confirm_post(&$a) {
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:
14 if(! x($_POST,'source_url')) {
19 notice( t('Permission denied.') . EOL );
23 // These come from the friend request notification form.
25 $dfrn_id = ((x($_POST,'dfrn_id')) ? notags(trim($_POST['dfrn_id'])) : "");
26 $intro_id = intval($_POST['intro_id']);
27 $duplex = intval($_POST['duplex']);
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.
33 $r = q("SELECT * FROM `contact` WHERE `issued-id` = '%s' AND `uid` = %d LIMIT 1",
39 notice( t('Contact not found.') . EOL );
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'];
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.
56 $res = openssl_pkey_new(array(
57 'digest_alg' => 'whirlpool',
58 'private_key_bits' => 4096,
59 'encrypt_key' => false )
65 openssl_pkey_export($res, $private_key);
67 $pubkey = openssl_pkey_get_details($res);
68 $public_key = $pubkey["key"];
70 // Save the private key. Send them the public key.
72 $r = q("UPDATE `contact` SET `prvkey` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
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.
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.
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
96 $src_aes_key = random_string();
99 openssl_private_encrypt($dfrn_id,$result,$a->user['prvkey']);
101 $params['dfrn_id'] = $result;
102 $params['public_key'] = $public_key;
105 $my_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
107 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
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);
114 $params['dfrn_version'] = '2.0';
116 $params['duplex'] = 1;
118 // POST all this stuff to the other site.
120 $res = post_url($dfrn_confirm,$params);
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.
125 $leading_junk = substr($res,0,strpos($res,'<?xml'));
127 $res = substr($res,strpos($res,'<?xml'));
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.
135 notice( t('Response from remote site was not understood.') . EOL);
139 if(strlen($leading_junk) && get_config('system','debugging')) {
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.
144 notice( t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL );
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.
152 notice( t("Confirmation completed successfully.") . EOL);
154 notice( t('Remote site reported: ') . $message . EOL);
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",
166 notice( t("Temporary failure. Please wait and try again.") . EOL);
168 notice( t('Remote site reported: ') . $message . EOL);
173 notice( t("Introduction failed or was revoked.") . EOL);
175 notice( t('Remote site reported: ') . $message . EOL);
179 if(($status == 0) && ($intro_id)) {
181 // Success. Delete the notification.
183 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d LIMIT 1",
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.
197 require_once("Photo.php");
199 $photo_failure = false;
201 $r = q("SELECT `photo` FROM `contact` WHERE `id` = %d LIMIT 1",
202 intval($contact_id));
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()) {
210 $img->scaleImageSquare(175);
212 $hash = photo_new_resource();
214 $r = $img->store($uid, $contact_id, $hash, $filename, t('Contact Photos'), 4 );
217 $photo_failure = true;
219 $img->scaleImage(80);
221 $r = $img->store($uid, $contact_id, $hash, $filename, t('Contact Photos'), 5 );
224 $photo_failure = true;
226 $photo = $a->get_baseurl() . '/photo/' . $hash . '-4.jpg';
227 $thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.jpg';
230 $photo_failure = true;
233 $photo_failure = true;
236 $photo = $a->get_baseurl() . '/images/default-profile.jpg';
237 $thumb = $a->get_baseurl() . '/images/default-profile-sm.jpg';
240 $new_relation = REL_VIP;
241 if(($relation == REL_FAN) || ($duplex))
242 $new_relation = REL_BUD;
244 $r = q("UPDATE `contact` SET `photo` = '%s',
249 `avatar-date` = '%s',
253 `network` = 'dfrn' WHERE `id` = %d LIMIT 1
257 intval($new_relation),
258 dbesc(datetime_convert()),
259 dbesc(datetime_convert()),
260 dbesc(datetime_convert()),
265 notice( t('Unable to set contact photo.') . EOL);
268 // Let's send our user to the contact editor in case they want to
269 // do anything special with this new friend.
271 goaway($a->get_baseurl() . '/contacts/' . intval($contact_id));
277 // End of first scenario. [Local confirmation of remote friend request].
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.
286 if(x($_POST,'source_url')) {
288 // We are processing an external confirmation to an introduction created by our user.
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'];
297 // Find our user's account
299 $r = q("SELECT * FROM `user` WHERE `nickname` = '%s' LIMIT 1",
303 $message = t('No user record found for ') . '\'' . $node . '\'';
304 xml_status(3,$message); // failure
308 $my_prvkey = $r[0]['prvkey'];
309 $local_uid = $r[0]['uid'];
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);
319 $decrypted_source_url = "";
320 openssl_private_decrypt($source_url,$decrypted_source_url,$my_prvkey);
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);
329 $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
330 dbesc($decrypted_source_url),
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
341 $relation = $ret[0]['rel'];
343 // Decrypt all this stuff we just received
345 $foreign_pubkey = $ret[0]['site-pubkey'];
346 $dfrn_record = $ret[0]['id'];
348 $decrypted_dfrn_id = "";
349 openssl_public_decrypt($dfrn_id,$decrypted_dfrn_id,$foreign_pubkey);
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);
357 $dfrn_pubkey = $public_key;
360 $r = q("SELECT * FROM `contact` WHERE `dfrn-id` = '%s' LIMIT 1",
361 dbesc($decrypted_dfrn_id),
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
370 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d LIMIT 1",
371 dbesc($decrypted_dfrn_id),
376 $message = t('Unable to set your contact credentials on our system.');
377 xml_status(3,$message);
380 // We're good but now we have to scrape the profile photo and send notifications.
382 require_once("Photo.php");
384 $photo_failure = false;
386 $r = q("SELECT `photo` FROM `contact` WHERE `id` = %d LIMIT 1",
387 intval($dfrn_record));
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()) {
395 $img->scaleImageSquare(175);
397 $hash = photo_new_resource();
399 $r = $img->store($local_uid, $dfrn_record, $hash, $filename, t('Contact Photos') , 4);
402 $photo_failure = true;
404 $img->scaleImage(80);
405 $r = $img->store($local_uid, $dfrn_record, $hash, $filename, t('Contact Photos') , 5);
408 $photo_failure = true;
410 $photo = $a->get_baseurl() . '/photo/' . $hash . '-4.jpg';
411 $thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.jpg';
414 $photo_failure = true;
417 $photo_failure = true;
420 $photo = $a->get_baseurl() . '/images/default-profile.jpg';
421 $thumb = $a->get_baseurl() . '/images/default-profile-sm.jpg';
424 $new_relation = REL_FAN;
425 if(($relation == REL_VIP) || ($duplex))
426 $new_relation = REL_BUD;
428 $r = q("UPDATE `contact` SET
434 `avatar-date` = '%s',
438 `network` = 'dfrn' WHERE `id` = %d LIMIT 1
442 intval($new_relation),
443 dbesc(datetime_convert()),
444 dbesc(datetime_convert()),
445 dbesc(datetime_convert()),
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);
454 // Otherwise everything seems to have worked and we are almost done. Yay!
455 // Send an email notification
457 $r = q("SELECT * FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
458 WHERE `contact`.`id` = %d LIMIT 1",
461 if((count($r)) && ($r[0]['notify-flags'] & NOTIFY_CONFIRM)) {
463 $tpl = (($new_relation == REL_BUD)
464 ? load_view_file('view/friend_complete_eml.tpl')
465 : load_view_file('view/intro_complete_eml.tpl'));
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'],
477 $res = mail($r[0]['email'], t("Connection accepted at ") . $a->config['sitename'],
478 $email_tpl, 'From: ' . t('Administrator') . '@' . $_SERVER[SERVER_NAME] );
480 notice( t("Email notification failed.") . EOL );
483 xml_status(0); // Success
484 return; // NOTREACHED
486 ////////////////////// End of this scenario ///////////////////////////////////////////////
489 // somebody arrived here by mistake or they are fishing. Send them to the homepage.
491 goaway($a->get_baseurl());