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'];
83 if($contact['network'] === 'dfrn') {
85 // Generate a key pair for all further communications with this person.
86 // We have a keypair for every contact, and a site key for unknown people.
87 // This provides a means to carry on relationships with other people if
88 // any single key is compromised. It is a robust key. We're much more
89 // worried about key leakage than anybody cracking it.
91 $res = openssl_pkey_new(array(
92 'digest_alg' => 'whirlpool',
93 'private_key_bits' => 4096,
94 'encrypt_key' => false )
100 openssl_pkey_export($res, $private_key);
102 $pubkey = openssl_pkey_get_details($res);
103 $public_key = $pubkey["key"];
105 // Save the private key. Send them the public key.
107 $r = q("UPDATE `contact` SET `prvkey` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
115 // Per the protocol document, we will verify both ends by encrypting the dfrn_id with our
116 // site private key (person on the other end can decrypt it with our site public key).
117 // Then encrypt our profile URL with the other person's site public key. They can decrypt
118 // it with their site private key. If the decryption on the other end fails for either
119 // item, it indicates tampering or key failure on at least one site and we will not be
120 // able to provide a secure communication pathway.
122 // If other site is willing to accept full encryption, (aes_allow is 1 AND we have php5.3
123 // or later) then we encrypt the personal public key we send them using AES-256-CBC and a
124 // random key which is encrypted with their site public key.
126 $src_aes_key = random_string();
129 openssl_private_encrypt($dfrn_id,$result,$user[0]['prvkey']);
131 $params['dfrn_id'] = bin2hex($result);
132 $params['public_key'] = $public_key;
135 $my_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
137 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
138 $params['source_url'] = bin2hex($params['source_url']);
140 if($aes_allow && function_exists('openssl_encrypt')) {
141 openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
142 $params['aes_key'] = bin2hex($params['aes_key']);
143 $params['public_key'] = bin2hex(openssl_encrypt($public_key,'AES-256-CBC',$src_aes_key));
146 $params['dfrn_version'] = DFRN_PROTOCOL_VERSION ;
148 $params['duplex'] = 1;
150 // POST all this stuff to the other site.
152 $res = post_url($dfrn_confirm,$params);
154 // Now figure out what they responded. Try to be robust if the remote site is
155 // having difficulty and throwing up errors of some kind.
157 $leading_junk = substr($res,0,strpos($res,'<?xml'));
159 $res = substr($res,strpos($res,'<?xml'));
162 // No XML at all, this exchange is messed up really bad.
163 // We shouldn't proceed, because the xml parser might choke,
164 // and $status is going to be zero, which indicates success.
165 // We can hardly call this a success.
167 notice( t('Response from remote site was not understood.') . EOL);
171 if(strlen($leading_junk) && get_config('system','debugging')) {
173 // This might be more common. Mixed error text and some XML.
174 // If we're configured for debugging, show the text. Proceed in either case.
176 notice( t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL );
179 $xml = simplexml_load_string($res);
180 $status = (int) $xml->status;
181 $message = unxmlify($xml->message); // human readable text of what may have gone wrong.
184 notice( t("Confirmation completed successfully.") . EOL);
186 notice( t('Remote site reported: ') . $message . EOL);
189 // birthday paradox - generate new dfrn-id and fall through.
190 $new_dfrn_id = random_string();
191 $r = q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
198 notice( t("Temporary failure. Please wait and try again.") . EOL);
200 notice( t('Remote site reported: ') . $message . EOL);
205 notice( t("Introduction failed or was revoked.") . EOL);
207 notice( t('Remote site reported: ') . $message . EOL);
211 if(($status == 0) && ($intro_id)) {
213 // Success. Delete the notification.
215 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d LIMIT 1",
226 // We have now established a relationship with the other site.
227 // Let's make our own personal copy of their profile photo so we don't have
228 // to always load it from their site.
230 require_once("Photo.php");
232 $photos = import_profile_photo($contact['photo'],$uid,$contact_id);
234 if($contact['network'] === 'dfrn') {
236 $new_relation = REL_VIP;
237 if(($relation == REL_FAN) || ($duplex))
238 $new_relation = REL_BUD;
240 $r = q("UPDATE `contact` SET `photo` = '%s',
246 `avatar-date` = '%s',
250 `network` = 'dfrn' WHERE `id` = %d LIMIT 1
255 intval($new_relation),
256 dbesc(datetime_convert()),
257 dbesc(datetime_convert()),
258 dbesc(datetime_convert()),
268 // $contact['network'] !== 'dfrn'
270 $arr = lrdd($contact['url']);
272 foreach($arr as $link) {
273 if($link['@attributes']['rel'] === 'salmon')
274 $notify = $link['@attributes']['href'];
275 if($link['@attributes']['rel'] === NAMESPACE_FEED)
276 $poll = $link['@attributes']['href'];
280 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d LIMIT 1",
285 $r = q("UPDATE `contact` SET `photo` = '%s',
290 `avatar-date` = '%s',
295 WHERE `id` = %d LIMIT 1
300 dbesc(datetime_convert()),
301 dbesc(datetime_convert()),
302 dbesc(datetime_convert()),
310 notice( t('Unable to set contact photo.') . EOL);
313 // Let's send our user to the contact editor in case they want to
314 // do anything special with this new friend.
316 if($handsfree === null)
317 goaway($a->get_baseurl() . '/contacts/' . intval($contact_id));
324 // End of first scenario. [Local confirmation of remote friend request].
328 // Begin scenario two. This is the remote response to the above scenario.
329 // This will take place on the site that originally initiated the friend request.
330 // In the section above where the confirming party makes a POST and
331 // retrieves xml status information, they are communicating with the following code.
333 if(x($_POST,'source_url')) {
335 // We are processing an external confirmation to an introduction created by our user.
337 $public_key = $_POST['public_key'];
338 $dfrn_id = hex2bin($_POST['dfrn_id']);
339 $source_url = hex2bin($_POST['source_url']);
340 $aes_key = $_POST['aes_key'];
341 $duplex = $_POST['duplex'];
342 $version_id = (float) $_POST['dfrn_version'];
345 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
348 $aes_key = hex2bin($aes_key);
349 $public_key = hex2bin($public_key);
352 // Find our user's account
354 $r = q("SELECT * FROM `user` WHERE `nickname` = '%s' LIMIT 1",
358 $message = t('No user record found for ') . '\'' . $node . '\'';
359 xml_status(3,$message); // failure
363 $my_prvkey = $r[0]['prvkey'];
364 $local_uid = $r[0]['uid'];
367 if(! strstr($my_prvkey,'BEGIN RSA PRIVATE KEY')) {
368 $message = t('Our site encryption key is apparently messed up.');
369 xml_status(3,$message);
374 $decrypted_source_url = "";
375 openssl_private_decrypt($source_url,$decrypted_source_url,$my_prvkey);
378 if(! strlen($decrypted_source_url)) {
379 $message = t('Empty site URL was provided or URL could not be decrypted by us.');
380 xml_status(3,$message);
384 $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
385 dbesc($decrypted_source_url),
390 // this is either a bogus confirmation (?) or we deleted the original introduction.
391 $message = t('Contact record was not found for you on our site.');
392 xml_status(3,$message);
393 return; // NOTREACHED
396 $relation = $ret[0]['rel'];
398 // Decrypt all this stuff we just received
400 $foreign_pubkey = $ret[0]['site-pubkey'];
401 $dfrn_record = $ret[0]['id'];
403 $decrypted_dfrn_id = "";
404 openssl_public_decrypt($dfrn_id,$decrypted_dfrn_id,$foreign_pubkey);
406 if(strlen($aes_key)) {
407 $decrypted_aes_key = "";
408 openssl_private_decrypt($aes_key,$decrypted_aes_key,$my_prvkey);
409 $dfrn_pubkey = openssl_decrypt($public_key,'AES-256-CBC',$decrypted_aes_key);
412 $dfrn_pubkey = $public_key;
415 $r = q("SELECT * FROM `contact` WHERE `dfrn-id` = '%s' LIMIT 1",
416 dbesc($decrypted_dfrn_id),
420 $message = t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
421 xml_status(1,$message); // Birthday paradox - duplicate dfrn-id
425 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d LIMIT 1",
426 dbesc($decrypted_dfrn_id),
431 $message = t('Unable to set your contact credentials on our system.');
432 xml_status(3,$message);
435 // We're good but now we have to scrape the profile photo and send notifications.
439 $r = q("SELECT `photo` FROM `contact` WHERE `id` = %d LIMIT 1",
440 intval($dfrn_record));
443 $photo = $r[0]['photo'];
445 $photo = $a->get_baseurl() . '/images/default-profile.jpg';
447 require_once("Photo.php");
449 $photos = import_profile_photo($photo,$local_uid,$dfrn_record);
451 $new_relation = REL_FAN;
452 if(($relation == REL_VIP) || ($duplex))
453 $new_relation = REL_BUD;
455 $r = q("UPDATE `contact` SET
461 `avatar-date` = '%s',
465 `network` = 'dfrn' WHERE `id` = %d LIMIT 1
469 intval($new_relation),
470 dbesc(datetime_convert()),
471 dbesc(datetime_convert()),
472 dbesc(datetime_convert()),
476 if($r === false) { // indicates schema is messed up or total db failure
477 $message = t('Unable to update your contact profile details on our system');
478 xml_status(3,$message);
481 // Otherwise everything seems to have worked and we are almost done. Yay!
482 // Send an email notification
484 $r = q("SELECT * FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
485 WHERE `contact`.`id` = %d LIMIT 1",
488 if((count($r)) && ($r[0]['notify-flags'] & NOTIFY_CONFIRM)) {
490 $tpl = (($new_relation == REL_BUD)
491 ? load_view_file('view/friend_complete_eml.tpl')
492 : load_view_file('view/intro_complete_eml.tpl'));
494 $email_tpl = replace_macros($tpl, array(
495 '$sitename' => $a->config['sitename'],
496 '$siteurl' => $a->get_baseurl(),
497 '$username' => $r[0]['username'],
498 '$email' => $r[0]['email'],
499 '$fn' => $r[0]['name'],
500 '$dfrn_url' => $r[0]['url'],
504 $res = mail($r[0]['email'], t("Connection accepted at ") . $a->config['sitename'],
505 $email_tpl, 'From: ' . t('Administrator') . '@' . $_SERVER[SERVER_NAME] );
507 // pointless throwing an error here and confusing the person at the other end of the wire.
510 xml_status(0); // Success
511 return; // NOTREACHED
513 ////////////////////// End of this scenario ///////////////////////////////////////////////
516 // somebody arrived here by mistake or they are fishing. Send them to the homepage.
518 goaway($a->get_baseurl());