3 // There are two possible entry points.
5 function dfrn_confirm_post(&$a,$handsfree = null) {
7 if(is_array($handsfree)) {
9 // called directly from dfrn_request due to automatic friend acceptance
10 // any $_POST parameters we might need are supplied in the $handsfree array
12 $node = $handsfree['node'];
13 $a->interactive = false; // notice() becomes a no-op since nobody is there to see it
21 // Main entry point. Our user received a friend request notification (perhaps
22 // from another site) and clicked 'Accept'. $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.
26 if(! x($_POST,'source_url')) {
28 $uid = ((is_array($handsfree)) ? $handsfree['uid'] : local_user());
31 notice( t('Permission denied.') . EOL );
35 $user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
40 notice( t('Profile not found.') . EOL );
45 // These come from the friend request notification form or $handsfree reply.
47 if(is_array($handsfree)) {
48 $dfrn_id = $handsfree['dfrn_id'];
49 $intro_id = $handsfree['intro_id'];
50 $duplex = $handsfree['duplex'];
53 $dfrn_id = ((x($_POST,'dfrn_id')) ? notags(trim($_POST['dfrn_id'])) : "");
54 $intro_id = intval($_POST['intro_id']);
55 $duplex = intval($_POST['duplex']);
58 // The other person will have been issued an ID when they first requested friendship.
59 // Locate their record. At this time, their record will have both pending and blocked set to 1.
61 $r = q("SELECT * FROM `contact` WHERE `issued-id` = '%s' AND `uid` = %d LIMIT 1",
67 notice( t('Contact not found.') . EOL );
71 $contact_id = $r[0]['id'];
72 $relation = $r[0]['rel'];
73 $site_pubkey = $r[0]['site-pubkey'];
74 $dfrn_confirm = $r[0]['confirm'];
75 $aes_allow = $r[0]['aes_allow'];
78 // Generate a key pair for all further communications with this person.
79 // We have a keypair for every contact, and a site key for unknown people.
80 // This provides a means to carry on relationships with other people if
81 // any single key is compromised. It is a robust key. We're much more
82 // worried about key leakage than anybody cracking it.
84 $res = openssl_pkey_new(array(
85 'digest_alg' => 'whirlpool',
86 'private_key_bits' => 4096,
87 'encrypt_key' => false )
93 openssl_pkey_export($res, $private_key);
95 $pubkey = openssl_pkey_get_details($res);
96 $public_key = $pubkey["key"];
98 // Save the private key. Send them the public key.
100 $r = q("UPDATE `contact` SET `prvkey` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
108 // Per the protocol document, we will verify both ends by encrypting the dfrn_id with our
109 // site private key (person on the other end can decrypt it with our site public key).
110 // Then encrypt our profile URL with the other person's site public key. They can decrypt
111 // it with their site private key. If the decryption on the other end fails for either
112 // item, it indicates tampering or key failure on at least one site and we will not be
113 // able to provide a secure communication pathway.
115 // If other site is willing to accept full encryption, (aes_allow is 1 AND we have php5.3
116 // or later) then we encrypt the personal public key we send them using AES-256-CBC and a
117 // random key which is encrypted with their site public key.
119 $src_aes_key = random_string();
122 openssl_private_encrypt($dfrn_id,$result,$user[0]['prvkey']);
124 $params['dfrn_id'] = bin2hex($result);
125 $params['public_key'] = $public_key;
128 $my_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
130 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
131 $params['source_url'] = bin2hex($params['source_url']);
133 if($aes_allow && function_exists('openssl_encrypt')) {
134 openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
135 $params['aes_key'] = bin2hex($params['aes_key']);
136 $params['public_key'] = bin2hex(openssl_encrypt($public_key,'AES-256-CBC',$src_aes_key));
139 $params['dfrn_version'] = DFRN_PROTOCOL_VERSION ;
141 $params['duplex'] = 1;
143 // POST all this stuff to the other site.
145 $res = post_url($dfrn_confirm,$params);
147 // Now figure out what they responded. Try to be robust if the remote site is
148 // having difficulty and throwing up errors of some kind.
150 $leading_junk = substr($res,0,strpos($res,'<?xml'));
152 $res = substr($res,strpos($res,'<?xml'));
155 // No XML at all, this exchange is messed up really bad.
156 // We shouldn't proceed, because the xml parser might choke,
157 // and $status is going to be zero, which indicates success.
158 // We can hardly call this a success.
160 notice( t('Response from remote site was not understood.') . EOL);
164 if(strlen($leading_junk) && get_config('system','debugging')) {
166 // This might be more common. Mixed error text and some XML.
167 // If we're configured for debugging, show the text. Proceed in either case.
169 notice( t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL );
172 $xml = simplexml_load_string($res);
173 $status = (int) $xml->status;
174 $message = unxmlify($xml->message); // human readable text of what may have gone wrong.
177 notice( t("Confirmation completed successfully.") . EOL);
179 notice( t('Remote site reported: ') . $message . EOL);
182 // birthday paradox - generate new dfrn-id and fall through.
183 $new_dfrn_id = random_string();
184 $r = q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
191 notice( t("Temporary failure. Please wait and try again.") . EOL);
193 notice( t('Remote site reported: ') . $message . EOL);
198 notice( t("Introduction failed or was revoked.") . EOL);
200 notice( t('Remote site reported: ') . $message . EOL);
204 if(($status == 0) && ($intro_id)) {
206 // Success. Delete the notification.
208 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d LIMIT 1",
218 // We have now established a relationship with the other site.
219 // Let's make our own personal copy of their profile photo so we don't have
220 // to always load it from their site.
222 require_once("Photo.php");
224 $photo_failure = false;
226 $r = q("SELECT `photo` FROM `contact` WHERE `id` = %d LIMIT 1",
227 intval($contact_id));
230 $filename = basename($r[0]['photo']);
231 $img_str = fetch_url($r[0]['photo'],true);
232 $img = new Photo($img_str);
233 if($img->is_valid()) {
235 $img->scaleImageSquare(175);
237 $hash = photo_new_resource();
239 $r = $img->store($uid, $contact_id, $hash, $filename, t('Contact Photos'), 4 );
242 $photo_failure = true;
244 $img->scaleImage(80);
246 $r = $img->store($uid, $contact_id, $hash, $filename, t('Contact Photos'), 5 );
249 $photo_failure = true;
251 $photo = $a->get_baseurl() . '/photo/' . $hash . '-4.jpg';
252 $thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.jpg';
255 $photo_failure = true;
258 $photo_failure = true;
261 $photo = $a->get_baseurl() . '/images/default-profile.jpg';
262 $thumb = $a->get_baseurl() . '/images/default-profile-sm.jpg';
265 $new_relation = REL_VIP;
266 if(($relation == REL_FAN) || ($duplex))
267 $new_relation = REL_BUD;
269 $r = q("UPDATE `contact` SET `photo` = '%s',
274 `avatar-date` = '%s',
278 `network` = 'dfrn' WHERE `id` = %d LIMIT 1
282 intval($new_relation),
283 dbesc(datetime_convert()),
284 dbesc(datetime_convert()),
285 dbesc(datetime_convert()),
290 notice( t('Unable to set contact photo.') . EOL);
293 // Let's send our user to the contact editor in case they want to
294 // do anything special with this new friend.
296 if($handsfree === null)
297 goaway($a->get_baseurl() . '/contacts/' . intval($contact_id));
303 // End of first scenario. [Local confirmation of remote friend request].
307 // Begin scenario two. This is the remote response to the above scenario.
308 // This will take place on the site that originally initiated the friend request.
309 // In the section above where the confirming party makes a POST and
310 // retrieves xml status information, they are communicating with the following code.
312 if(x($_POST,'source_url')) {
314 // We are processing an external confirmation to an introduction created by our user.
316 $public_key = $_POST['public_key'];
317 $dfrn_id = hex2bin($_POST['dfrn_id']);
318 $source_url = hex2bin($_POST['source_url']);
319 $aes_key = $_POST['aes_key'];
320 $duplex = $_POST['duplex'];
321 $version_id = (float) $_POST['dfrn_version'];
324 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
327 $aes_key = hex2bin($aes_key);
328 $public_key = hex2bin($public_key);
331 // Find our user's account
333 $r = q("SELECT * FROM `user` WHERE `nickname` = '%s' LIMIT 1",
337 $message = t('No user record found for ') . '\'' . $node . '\'';
338 xml_status(3,$message); // failure
342 $my_prvkey = $r[0]['prvkey'];
343 $local_uid = $r[0]['uid'];
346 if(! strstr($my_prvkey,'BEGIN RSA PRIVATE KEY')) {
347 $message = t('Our site encryption key is apparently messed up.');
348 xml_status(3,$message);
353 $decrypted_source_url = "";
354 openssl_private_decrypt($source_url,$decrypted_source_url,$my_prvkey);
357 if(! strlen($decrypted_source_url)) {
358 $message = t('Empty site URL was provided or URL could not be decrypted by us.');
359 xml_status(3,$message);
363 $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
364 dbesc($decrypted_source_url),
369 // this is either a bogus confirmation (?) or we deleted the original introduction.
370 $message = t('Contact record was not found for you on our site.');
371 xml_status(3,$message);
372 return; // NOTREACHED
375 $relation = $ret[0]['rel'];
377 // Decrypt all this stuff we just received
379 $foreign_pubkey = $ret[0]['site-pubkey'];
380 $dfrn_record = $ret[0]['id'];
382 $decrypted_dfrn_id = "";
383 openssl_public_decrypt($dfrn_id,$decrypted_dfrn_id,$foreign_pubkey);
385 if(strlen($aes_key)) {
386 $decrypted_aes_key = "";
387 openssl_private_decrypt($aes_key,$decrypted_aes_key,$my_prvkey);
388 $dfrn_pubkey = openssl_decrypt($public_key,'AES-256-CBC',$decrypted_aes_key);
391 $dfrn_pubkey = $public_key;
394 $r = q("SELECT * FROM `contact` WHERE `dfrn-id` = '%s' LIMIT 1",
395 dbesc($decrypted_dfrn_id),
399 $message = t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
400 xml_status(1,$message); // Birthday paradox - duplicate dfrn-id
404 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d LIMIT 1",
405 dbesc($decrypted_dfrn_id),
410 $message = t('Unable to set your contact credentials on our system.');
411 xml_status(3,$message);
414 // We're good but now we have to scrape the profile photo and send notifications.
416 require_once("Photo.php");
418 $photo_failure = false;
420 $r = q("SELECT `photo` FROM `contact` WHERE `id` = %d LIMIT 1",
421 intval($dfrn_record));
424 $filename = basename($r[0]['photo']);
425 $img_str = fetch_url($r[0]['photo'],true);
426 $img = new Photo($img_str);
427 if($img->is_valid()) {
429 $img->scaleImageSquare(175);
431 $hash = photo_new_resource();
433 $r = $img->store($local_uid, $dfrn_record, $hash, $filename, t('Contact Photos') , 4);
436 $photo_failure = true;
438 $img->scaleImage(80);
439 $r = $img->store($local_uid, $dfrn_record, $hash, $filename, t('Contact Photos') , 5);
442 $photo_failure = true;
444 $photo = $a->get_baseurl() . '/photo/' . $hash . '-4.jpg';
445 $thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.jpg';
448 $photo_failure = true;
451 $photo_failure = true;
454 $photo = $a->get_baseurl() . '/images/default-profile.jpg';
455 $thumb = $a->get_baseurl() . '/images/default-profile-sm.jpg';
458 $new_relation = REL_FAN;
459 if(($relation == REL_VIP) || ($duplex))
460 $new_relation = REL_BUD;
462 $r = q("UPDATE `contact` SET
468 `avatar-date` = '%s',
472 `network` = 'dfrn' WHERE `id` = %d LIMIT 1
476 intval($new_relation),
477 dbesc(datetime_convert()),
478 dbesc(datetime_convert()),
479 dbesc(datetime_convert()),
483 if($r === false) { // indicates schema is messed up or total db failure
484 $message = t('Unable to update your contact profile details on our system');
485 xml_status(3,$message);
488 // Otherwise everything seems to have worked and we are almost done. Yay!
489 // Send an email notification
491 $r = q("SELECT * FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
492 WHERE `contact`.`id` = %d LIMIT 1",
495 if((count($r)) && ($r[0]['notify-flags'] & NOTIFY_CONFIRM)) {
497 $tpl = (($new_relation == REL_BUD)
498 ? load_view_file('view/friend_complete_eml.tpl')
499 : load_view_file('view/intro_complete_eml.tpl'));
501 $email_tpl = replace_macros($tpl, array(
502 '$sitename' => $a->config['sitename'],
503 '$siteurl' => $a->get_baseurl(),
504 '$username' => $r[0]['username'],
505 '$email' => $r[0]['email'],
506 '$fn' => $r[0]['name'],
507 '$dfrn_url' => $r[0]['url'],
511 $res = mail($r[0]['email'], t("Connection accepted at ") . $a->config['sitename'],
512 $email_tpl, 'From: ' . t('Administrator') . '@' . $_SERVER[SERVER_NAME] );
514 // pointless throwing an error here and confusing the person at the other end of the wire.
517 xml_status(0); // Success
518 return; // NOTREACHED
520 ////////////////////// End of this scenario ///////////////////////////////////////////////
523 // somebody arrived here by mistake or they are fishing. Send them to the homepage.
525 goaway($a->get_baseurl());