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 may require 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 '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.
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 either the friend request notification form or $handsfree array.
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']);
56 $cid = intval($_POST['contact_id']);
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.
63 $r = q("SELECT * FROM `contact` WHERE ( ( `issued-id` != '' AND `issued-id` = '%s' ) OR ( `id` = %d AND `id` != 0 ) ) AND `uid` = %d LIMIT 1",
70 notice( t('Contact not found.') . EOL );
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'];
82 $network = ((strlen($contact['issued-id'])) ? 'dfrn' : 'stat');
84 if($network === 'dfrn') {
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.
92 $res = openssl_pkey_new(array(
93 'digest_alg' => 'whirlpool',
94 'private_key_bits' => 4096,
95 'encrypt_key' => false )
101 openssl_pkey_export($res, $private_key);
103 $pubkey = openssl_pkey_get_details($res);
104 $public_key = $pubkey["key"];
106 // Save the private key. Send them the public key.
108 $r = q("UPDATE `contact` SET `prvkey` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
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.
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.
127 $src_aes_key = random_string();
130 openssl_private_encrypt($dfrn_id,$result,$user[0]['prvkey']);
132 $params['dfrn_id'] = bin2hex($result);
133 $params['public_key'] = $public_key;
136 $my_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
138 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
139 $params['source_url'] = bin2hex($params['source_url']);
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));
147 $params['dfrn_version'] = DFRN_PROTOCOL_VERSION ;
149 $params['duplex'] = 1;
151 // POST all this stuff to the other site.
153 $res = post_url($dfrn_confirm,$params);
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.
158 $leading_junk = substr($res,0,strpos($res,'<?xml'));
160 $res = substr($res,strpos($res,'<?xml'));
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.
168 notice( t('Response from remote site was not understood.') . EOL);
172 if(strlen($leading_junk) && get_config('system','debugging')) {
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.
177 notice( t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL );
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.
185 notice( t("Confirmation completed successfully.") . EOL);
187 notice( t('Remote site reported: ') . $message . EOL);
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",
199 notice( t("Temporary failure. Please wait and try again.") . EOL);
201 notice( t('Remote site reported: ') . $message . EOL);
206 notice( t("Introduction failed or was revoked.") . EOL);
208 notice( t('Remote site reported: ') . $message . EOL);
212 if(($status == 0) && ($intro_id)) {
214 // Success. Delete the notification.
216 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d LIMIT 1",
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.
231 require_once("Photo.php");
233 $photos = import_profile_photo($contact['photo'],$uid,$contact_id);
235 if($network === 'dfrn') {
237 $new_relation = REL_VIP;
238 if(($relation == REL_FAN) || ($duplex))
239 $new_relation = REL_BUD;
241 $r = q("UPDATE `contact` SET `photo` = '%s',
247 `avatar-date` = '%s',
251 `network` = 'dfrn' WHERE `id` = %d LIMIT 1
256 intval($new_relation),
257 dbesc(datetime_convert()),
258 dbesc(datetime_convert()),
259 dbesc(datetime_convert()),
269 // $network !== 'dfrn'
271 $arr = lrdd($contact['url']);
273 foreach($arr as $link) {
274 if($link['@attributes']['rel'] === 'salmon')
275 $notify = $link['@attributes']['href'];
276 if($link['@attributes']['rel'] === NAMESPACE_FEED)
277 $poll = $link['@attributes']['href'];
281 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d LIMIT 1",
287 $r = q("UPDATE `contact` SET `photo` = '%s',
292 `avatar-date` = '%s',
298 WHERE `id` = %d LIMIT 1
303 dbesc(datetime_convert()),
304 dbesc(datetime_convert()),
305 dbesc(datetime_convert()),
313 notice( t('Unable to set contact photo.') . EOL);
316 // Let's send our user to the contact editor in case they want to
317 // do anything special with this new friend.
319 if($handsfree === null)
320 goaway($a->get_baseurl() . '/contacts/' . intval($contact_id));
327 // End of first scenario. [Local confirmation of remote friend request].
331 // Begin scenario two. This is the remote response to the above scenario.
332 // This will take place on the site that originally initiated the friend request.
333 // In the section above where the confirming party makes a POST and
334 // retrieves xml status information, they are communicating with the following code.
336 if(x($_POST,'source_url')) {
338 // We are processing an external confirmation to an introduction created by our user.
340 $public_key = $_POST['public_key'];
341 $dfrn_id = hex2bin($_POST['dfrn_id']);
342 $source_url = hex2bin($_POST['source_url']);
343 $aes_key = $_POST['aes_key'];
344 $duplex = $_POST['duplex'];
345 $version_id = (float) $_POST['dfrn_version'];
348 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
351 $aes_key = hex2bin($aes_key);
352 $public_key = hex2bin($public_key);
355 // Find our user's account
357 $r = q("SELECT * FROM `user` WHERE `nickname` = '%s' LIMIT 1",
361 $message = t('No user record found for ') . '\'' . $node . '\'';
362 xml_status(3,$message); // failure
366 $my_prvkey = $r[0]['prvkey'];
367 $local_uid = $r[0]['uid'];
370 if(! strstr($my_prvkey,'BEGIN RSA PRIVATE KEY')) {
371 $message = t('Our site encryption key is apparently messed up.');
372 xml_status(3,$message);
377 $decrypted_source_url = "";
378 openssl_private_decrypt($source_url,$decrypted_source_url,$my_prvkey);
381 if(! strlen($decrypted_source_url)) {
382 $message = t('Empty site URL was provided or URL could not be decrypted by us.');
383 xml_status(3,$message);
387 $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
388 dbesc($decrypted_source_url),
393 // this is either a bogus confirmation (?) or we deleted the original introduction.
394 $message = t('Contact record was not found for you on our site.');
395 xml_status(3,$message);
396 return; // NOTREACHED
399 $relation = $ret[0]['rel'];
401 // Decrypt all this stuff we just received
403 $foreign_pubkey = $ret[0]['site-pubkey'];
404 $dfrn_record = $ret[0]['id'];
406 $decrypted_dfrn_id = "";
407 openssl_public_decrypt($dfrn_id,$decrypted_dfrn_id,$foreign_pubkey);
409 if(strlen($aes_key)) {
410 $decrypted_aes_key = "";
411 openssl_private_decrypt($aes_key,$decrypted_aes_key,$my_prvkey);
412 $dfrn_pubkey = openssl_decrypt($public_key,'AES-256-CBC',$decrypted_aes_key);
415 $dfrn_pubkey = $public_key;
418 $r = q("SELECT * FROM `contact` WHERE `dfrn-id` = '%s' LIMIT 1",
419 dbesc($decrypted_dfrn_id),
423 $message = t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
424 xml_status(1,$message); // Birthday paradox - duplicate dfrn-id
428 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d LIMIT 1",
429 dbesc($decrypted_dfrn_id),
434 $message = t('Unable to set your contact credentials on our system.');
435 xml_status(3,$message);
438 // We're good but now we have to scrape the profile photo and send notifications.
442 $r = q("SELECT `photo` FROM `contact` WHERE `id` = %d LIMIT 1",
443 intval($dfrn_record));
446 $photo = $r[0]['photo'];
448 $photo = $a->get_baseurl() . '/images/default-profile.jpg';
450 require_once("Photo.php");
452 $photos = import_profile_photo($photo,$local_uid,$dfrn_record);
454 $new_relation = REL_FAN;
455 if(($relation == REL_VIP) || ($duplex))
456 $new_relation = REL_BUD;
458 $r = q("UPDATE `contact` SET
465 `avatar-date` = '%s',
469 `network` = 'dfrn' WHERE `id` = %d LIMIT 1
474 intval($new_relation),
475 dbesc(datetime_convert()),
476 dbesc(datetime_convert()),
477 dbesc(datetime_convert()),
481 if($r === false) { // indicates schema is messed up or total db failure
482 $message = t('Unable to update your contact profile details on our system');
483 xml_status(3,$message);
486 // Otherwise everything seems to have worked and we are almost done. Yay!
487 // Send an email notification
489 $r = q("SELECT * FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
490 WHERE `contact`.`id` = %d LIMIT 1",
493 if((count($r)) && ($r[0]['notify-flags'] & NOTIFY_CONFIRM)) {
495 $tpl = (($new_relation == REL_BUD)
496 ? load_view_file('view/friend_complete_eml.tpl')
497 : load_view_file('view/intro_complete_eml.tpl'));
499 $email_tpl = replace_macros($tpl, array(
500 '$sitename' => $a->config['sitename'],
501 '$siteurl' => $a->get_baseurl(),
502 '$username' => $r[0]['username'],
503 '$email' => $r[0]['email'],
504 '$fn' => $r[0]['name'],
505 '$dfrn_url' => $r[0]['url'],
509 $res = mail($r[0]['email'], t("Connection accepted at ") . $a->config['sitename'],
510 $email_tpl, 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] );
512 // pointless throwing an error here and confusing the person at the other end of the wire.
515 xml_status(0); // Success
516 return; // NOTREACHED
518 ////////////////////// End of this scenario ///////////////////////////////////////////////
521 // somebody arrived here by mistake or they are fishing. Send them to the homepage.
523 goaway($a->get_baseurl());