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'] = bin2hex($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);
108 $params['source_url'] = bin2hex($params['source_url']);
110 if($aes_allow && function_exists('openssl_encrypt')) {
111 openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
112 $params['aes_key'] = bin2hex($params['aes_key']);
113 $params['public_key'] = bin2hex(openssl_encrypt($public_key,'AES-256-CBC',$src_aes_key));
116 $params['dfrn_version'] = '2.0';
118 $params['duplex'] = 1;
120 // POST all this stuff to the other site.
122 $res = post_url($dfrn_confirm,$params);
124 // Now figure out what they responded. Try to be robust if the remote site is
125 // having difficulty and throwing up errors of some kind.
127 $leading_junk = substr($res,0,strpos($res,'<?xml'));
129 $res = substr($res,strpos($res,'<?xml'));
132 // No XML at all, this exchange is messed up really bad.
133 // We shouldn't proceed, because the xml parser might choke,
134 // and $status is going to be zero, which indicates success.
135 // We can hardly call this a success.
137 notice( t('Response from remote site was not understood.') . EOL);
141 if(strlen($leading_junk) && get_config('system','debugging')) {
143 // This might be more common. Mixed error text and some XML.
144 // If we're configured for debugging, show the text. Proceed in either case.
146 notice( t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL );
149 $xml = simplexml_load_string($res);
150 $status = (int) $xml->status;
151 $message = unxmlify($xml->message); // human readable text of what may have gone wrong.
154 notice( t("Confirmation completed successfully.") . EOL);
156 notice( t('Remote site reported: ') . $message . EOL);
159 // birthday paradox - generate new dfrn-id and fall through.
160 $new_dfrn_id = random_string();
161 $r = q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
168 notice( t("Temporary failure. Please wait and try again.") . EOL);
170 notice( t('Remote site reported: ') . $message . EOL);
175 notice( t("Introduction failed or was revoked.") . EOL);
177 notice( t('Remote site reported: ') . $message . EOL);
181 if(($status == 0) && ($intro_id)) {
183 // Success. Delete the notification.
185 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d LIMIT 1",
195 // We have now established a relationship with the other site.
196 // Let's make our own personal copy of their profile photo so we don't have
197 // to always load it from their site.
199 require_once("Photo.php");
201 $photo_failure = false;
203 $r = q("SELECT `photo` FROM `contact` WHERE `id` = %d LIMIT 1",
204 intval($contact_id));
207 $filename = basename($r[0]['photo']);
208 $img_str = fetch_url($r[0]['photo'],true);
209 $img = new Photo($img_str);
210 if($img->is_valid()) {
212 $img->scaleImageSquare(175);
214 $hash = photo_new_resource();
216 $r = $img->store($uid, $contact_id, $hash, $filename, t('Contact Photos'), 4 );
219 $photo_failure = true;
221 $img->scaleImage(80);
223 $r = $img->store($uid, $contact_id, $hash, $filename, t('Contact Photos'), 5 );
226 $photo_failure = true;
228 $photo = $a->get_baseurl() . '/photo/' . $hash . '-4.jpg';
229 $thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.jpg';
232 $photo_failure = true;
235 $photo_failure = true;
238 $photo = $a->get_baseurl() . '/images/default-profile.jpg';
239 $thumb = $a->get_baseurl() . '/images/default-profile-sm.jpg';
242 $new_relation = REL_VIP;
243 if(($relation == REL_FAN) || ($duplex))
244 $new_relation = REL_BUD;
246 $r = q("UPDATE `contact` SET `photo` = '%s',
251 `avatar-date` = '%s',
255 `network` = 'dfrn' WHERE `id` = %d LIMIT 1
259 intval($new_relation),
260 dbesc(datetime_convert()),
261 dbesc(datetime_convert()),
262 dbesc(datetime_convert()),
267 notice( t('Unable to set contact photo.') . EOL);
270 // Let's send our user to the contact editor in case they want to
271 // do anything special with this new friend.
273 goaway($a->get_baseurl() . '/contacts/' . intval($contact_id));
279 // End of first scenario. [Local confirmation of remote friend request].
283 // Begin scenario two. This is the remote response to the above scenario.
284 // This will take place on the site that originally initiated the friend request.
285 // In the section above where the confirming party makes a POST and
286 // retrieves xml status information, they are communicating with the following code.
288 if(x($_POST,'source_url')) {
290 // We are processing an external confirmation to an introduction created by our user.
292 $public_key = $_POST['public_key'];
293 $dfrn_id = hex2bin($_POST['dfrn_id']);
294 $source_url = hex2bin($_POST['source_url']);
295 $aes_key = hex2bin($_POST['aes_key']);
296 $duplex = $_POST['duplex'];
297 $version_id = $_POST['dfrn_version'];
299 // Find our user's account
301 $r = q("SELECT * FROM `user` WHERE `nickname` = '%s' LIMIT 1",
305 $message = t('No user record found for ') . '\'' . $node . '\'';
306 xml_status(3,$message); // failure
310 $my_prvkey = $r[0]['prvkey'];
311 $local_uid = $r[0]['uid'];
314 if(! strstr($my_prvkey,'BEGIN RSA PRIVATE KEY')) {
315 $message = t('Our site encryption key is apparently messed up.');
316 xml_status(3,$message);
321 $decrypted_source_url = "";
322 openssl_private_decrypt($source_url,$decrypted_source_url,$my_prvkey);
325 if(! strlen($decrypted_source_url)) {
326 $message = t('Empty site URL was provided or URL could not be decrypted by us.');
327 xml_status(3,$message);
331 $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
332 dbesc($decrypted_source_url),
337 // this is either a bogus confirmation (?) or we deleted the original introduction.
338 $message = t('Contact record was not found for you on our site.');
339 xml_status(3,$message);
340 return; // NOTREACHED
343 $relation = $ret[0]['rel'];
345 // Decrypt all this stuff we just received
347 $foreign_pubkey = $ret[0]['site-pubkey'];
348 $dfrn_record = $ret[0]['id'];
350 $decrypted_dfrn_id = "";
351 openssl_public_decrypt($dfrn_id,$decrypted_dfrn_id,$foreign_pubkey);
353 if(strlen($aes_key)) {
354 $decrypted_aes_key = "";
355 openssl_private_decrypt($aes_key,$decrypted_aes_key,$my_prvkey);
356 $dfrn_pubkey = openssl_decrypt($public_key,'AES-256-CBC',$decrypted_aes_key);
359 $dfrn_pubkey = $public_key;
362 $r = q("SELECT * FROM `contact` WHERE `dfrn-id` = '%s' LIMIT 1",
363 dbesc($decrypted_dfrn_id),
367 $message = t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
368 xml_status(1,$message); // Birthday paradox - duplicate dfrn-id
372 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d LIMIT 1",
373 dbesc($decrypted_dfrn_id),
378 $message = t('Unable to set your contact credentials on our system.');
379 xml_status(3,$message);
382 // We're good but now we have to scrape the profile photo and send notifications.
384 require_once("Photo.php");
386 $photo_failure = false;
388 $r = q("SELECT `photo` FROM `contact` WHERE `id` = %d LIMIT 1",
389 intval($dfrn_record));
392 $filename = basename($r[0]['photo']);
393 $img_str = fetch_url($r[0]['photo'],true);
394 $img = new Photo($img_str);
395 if($img->is_valid()) {
397 $img->scaleImageSquare(175);
399 $hash = photo_new_resource();
401 $r = $img->store($local_uid, $dfrn_record, $hash, $filename, t('Contact Photos') , 4);
404 $photo_failure = true;
406 $img->scaleImage(80);
407 $r = $img->store($local_uid, $dfrn_record, $hash, $filename, t('Contact Photos') , 5);
410 $photo_failure = true;
412 $photo = $a->get_baseurl() . '/photo/' . $hash . '-4.jpg';
413 $thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.jpg';
416 $photo_failure = true;
419 $photo_failure = true;
422 $photo = $a->get_baseurl() . '/images/default-profile.jpg';
423 $thumb = $a->get_baseurl() . '/images/default-profile-sm.jpg';
426 $new_relation = REL_FAN;
427 if(($relation == REL_VIP) || ($duplex))
428 $new_relation = REL_BUD;
430 $r = q("UPDATE `contact` SET
436 `avatar-date` = '%s',
440 `network` = 'dfrn' WHERE `id` = %d LIMIT 1
444 intval($new_relation),
445 dbesc(datetime_convert()),
446 dbesc(datetime_convert()),
447 dbesc(datetime_convert()),
451 if($r === false) { // indicates schema is messed up or total db failure
452 $message = t('Unable to update your contact profile details on our system');
453 xml_status(3,$message);
456 // Otherwise everything seems to have worked and we are almost done. Yay!
457 // Send an email notification
459 $r = q("SELECT * FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
460 WHERE `contact`.`id` = %d LIMIT 1",
463 if((count($r)) && ($r[0]['notify-flags'] & NOTIFY_CONFIRM)) {
465 $tpl = (($new_relation == REL_BUD)
466 ? load_view_file('view/friend_complete_eml.tpl')
467 : load_view_file('view/intro_complete_eml.tpl'));
469 $email_tpl = replace_macros($tpl, array(
470 '$sitename' => $a->config['sitename'],
471 '$siteurl' => $a->get_baseurl(),
472 '$username' => $r[0]['username'],
473 '$email' => $r[0]['email'],
474 '$fn' => $r[0]['name'],
475 '$dfrn_url' => $r[0]['url'],
479 $res = mail($r[0]['email'], t("Connection accepted at ") . $a->config['sitename'],
480 $email_tpl, 'From: ' . t('Administrator') . '@' . $_SERVER[SERVER_NAME] );
482 notice( t("Email notification failed.") . EOL );
485 xml_status(0); // Success
486 return; // NOTREACHED
488 ////////////////////// End of this scenario ///////////////////////////////////////////////
491 // somebody arrived here by mistake or they are fishing. Send them to the homepage.
493 goaway($a->get_baseurl());