3 // There are two possible entry points.
6 function dfrn_confirm_post(&$a,$handsfree = null) {
8 if(is_array($handsfree)) {
10 // called directly from dfrn_request due to automatic friend acceptance
11 // any $_POST parameters we may require are supplied in the $handsfree array
13 $node = $handsfree['node'];
14 $a->interactive = false; // notice() becomes a no-op since nobody is there to see it
22 // Main entry point. Our user received a friend request notification (perhaps
23 // from another site) and clicked 'Approve'. $POST['source_url'] is not set.
24 // OR we have been called directly from dfrn_request ($handsfree != null) due to
25 // this being a page type which supports automatic friend acceptance.
27 if(! x($_POST,'source_url')) {
29 $uid = ((is_array($handsfree)) ? $handsfree['uid'] : local_user());
32 notice( t('Permission denied.') . EOL );
36 $user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
41 notice( t('Profile not found.') . EOL );
46 // These come from either the friend request notification form or $handsfree array.
48 if(is_array($handsfree)) {
49 $dfrn_id = $handsfree['dfrn_id'];
50 $intro_id = $handsfree['intro_id'];
51 $duplex = $handsfree['duplex'];
54 $dfrn_id = ((x($_POST,'dfrn_id')) ? notags(trim($_POST['dfrn_id'])) : "");
55 $intro_id = intval($_POST['intro_id']);
56 $duplex = intval($_POST['duplex']);
57 $cid = intval($_POST['contact_id']);
60 logger('dfrn_confirm: Confirming request for dfrn_id ' . $dfrn_id);
62 // The other person will have been issued an ID when they first requested friendship.
63 // Locate their record. At this time, their record will have both pending and blocked set to 1.
64 // There won't be any dfrn_id if this is a network follower, so use the contact_id instead.
66 $r = q("SELECT * FROM `contact` WHERE ( ( `issued-id` != '' AND `issued-id` = '%s' ) OR ( `id` = %d AND `id` != 0 ) ) AND `uid` = %d LIMIT 1",
73 notice( t('Contact not found.') . EOL );
79 $contact_id = $contact['id'];
80 $relation = $contact['rel'];
81 $site_pubkey = $contact['site-pubkey'];
82 $dfrn_confirm = $contact['confirm'];
83 $aes_allow = $contact['aes_allow'];
85 $network = ((strlen($contact['issued-id'])) ? 'dfrn' : 'stat');
87 if($network === 'dfrn') {
89 // Generate a key pair for all further communications with this person.
90 // We have a keypair for every contact, and a site key for unknown people.
91 // This provides a means to carry on relationships with other people if
92 // any single key is compromised. It is a robust key. We're much more
93 // worried about key leakage than anybody cracking it.
95 $res = openssl_pkey_new(array(
96 'digest_alg' => 'whirlpool',
97 'private_key_bits' => 4096,
98 'encrypt_key' => false )
104 openssl_pkey_export($res, $private_key);
106 $pubkey = openssl_pkey_get_details($res);
107 $public_key = $pubkey["key"];
109 // Save the private key. Send them the public key.
111 $r = q("UPDATE `contact` SET `prvkey` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
119 // Per the protocol document, we will verify both ends by encrypting the dfrn_id with our
120 // site private key (person on the other end can decrypt it with our site public key).
121 // Then encrypt our profile URL with the other person's site public key. They can decrypt
122 // it with their site private key. If the decryption on the other end fails for either
123 // item, it indicates tampering or key failure on at least one site and we will not be
124 // able to provide a secure communication pathway.
126 // If other site is willing to accept full encryption, (aes_allow is 1 AND we have php5.3
127 // or later) then we encrypt the personal public key we send them using AES-256-CBC and a
128 // random key which is encrypted with their site public key.
130 $src_aes_key = random_string();
133 openssl_private_encrypt($dfrn_id,$result,$user[0]['prvkey']);
135 $params['dfrn_id'] = bin2hex($result);
136 $params['public_key'] = $public_key;
139 $my_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
141 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
142 $params['source_url'] = bin2hex($params['source_url']);
144 if($aes_allow && function_exists('openssl_encrypt')) {
145 openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
146 $params['aes_key'] = bin2hex($params['aes_key']);
147 $params['public_key'] = bin2hex(openssl_encrypt($public_key,'AES-256-CBC',$src_aes_key));
150 $params['dfrn_version'] = DFRN_PROTOCOL_VERSION ;
152 $params['duplex'] = 1;
154 logger('dfrn_confirm: Confirm: posted data: ' . print_r($params,true), LOGGER_DATA);
156 // POST all this stuff to the other site.
158 $res = post_url($dfrn_confirm,$params);
160 logger('dfrn_confirm: Confirm: received data: ' . $res, LOGGER_DATA);
162 // Now figure out what they responded. Try to be robust if the remote site is
163 // having difficulty and throwing up errors of some kind.
165 $leading_junk = substr($res,0,strpos($res,'<?xml'));
167 $res = substr($res,strpos($res,'<?xml'));
170 // No XML at all, this exchange is messed up really bad.
171 // We shouldn't proceed, because the xml parser might choke,
172 // and $status is going to be zero, which indicates success.
173 // We can hardly call this a success.
175 notice( t('Response from remote site was not understood.') . EOL);
179 if(strlen($leading_junk) && get_config('system','debugging')) {
181 // This might be more common. Mixed error text and some XML.
182 // If we're configured for debugging, show the text. Proceed in either case.
184 notice( t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL );
187 $xml = simplexml_load_string($res);
188 $status = (int) $xml->status;
189 $message = unxmlify($xml->message); // human readable text of what may have gone wrong.
192 notice( t("Confirmation completed successfully.") . EOL);
194 notice( t('Remote site reported: ') . $message . EOL);
197 // birthday paradox - generate new dfrn-id and fall through.
198 $new_dfrn_id = random_string();
199 $r = q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
206 notice( t("Temporary failure. Please wait and try again.") . EOL);
208 notice( t('Remote site reported: ') . $message . EOL);
213 notice( t("Introduction failed or was revoked.") . EOL);
215 notice( t('Remote site reported: ') . $message . EOL);
219 if(($status == 0) && ($intro_id)) {
221 // Success. Delete the notification.
223 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d LIMIT 1",
234 // We have now established a relationship with the other site.
235 // Let's make our own personal copy of their profile photo so we don't have
236 // to always load it from their site.
238 require_once("Photo.php");
240 $photos = import_profile_photo($contact['photo'],$uid,$contact_id);
242 logger('dfrn_confirm: confirm - imported photos');
244 if($network === 'dfrn') {
246 $new_relation = REL_VIP;
247 if(($relation == REL_FAN) || ($duplex))
248 $new_relation = REL_BUD;
250 if(($relation == REL_FAN) && ($duplex))
253 $r = q("UPDATE `contact` SET `photo` = '%s',
259 `avatar-date` = '%s',
263 `network` = 'dfrn' WHERE `id` = %d LIMIT 1
268 intval($new_relation),
269 dbesc(datetime_convert()),
270 dbesc(datetime_convert()),
271 dbesc(datetime_convert()),
281 // $network !== 'dfrn'
283 $arr = lrdd($contact['url']);
285 foreach($arr as $link) {
286 if($link['@attributes']['rel'] === 'salmon')
287 $notify = $link['@attributes']['href'];
288 if($link['@attributes']['rel'] === NAMESPACE_FEED)
289 $poll = $link['@attributes']['href'];
293 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d LIMIT 1",
299 $r = q("UPDATE `contact` SET `photo` = '%s',
304 `avatar-date` = '%s',
310 WHERE `id` = %d LIMIT 1
315 dbesc(datetime_convert()),
316 dbesc(datetime_convert()),
317 dbesc(datetime_convert()),
325 notice( t('Unable to set contact photo.') . EOL);
328 // Let's send our user to the contact editor in case they want to
329 // do anything special with this new friend.
331 if($handsfree === null)
332 goaway($a->get_baseurl() . '/contacts/' . intval($contact_id));
339 // End of first scenario. [Local confirmation of remote friend request].
343 // Begin scenario two. This is the remote response to the above scenario.
344 // This will take place on the site that originally initiated the friend request.
345 // In the section above where the confirming party makes a POST and
346 // retrieves xml status information, they are communicating with the following code.
348 if(x($_POST,'source_url')) {
350 // We are processing an external confirmation to an introduction created by our user.
352 $public_key = $_POST['public_key'];
353 $dfrn_id = hex2bin($_POST['dfrn_id']);
354 $source_url = hex2bin($_POST['source_url']);
355 $aes_key = $_POST['aes_key'];
356 $duplex = $_POST['duplex'];
357 $version_id = (float) $_POST['dfrn_version'];
360 logger('dfrn_confirm: request: POST=' . print_r($_POST,true), LOGGER_DATA);
362 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
365 $aes_key = hex2bin($aes_key);
366 $public_key = hex2bin($public_key);
369 // Find our user's account
371 $r = q("SELECT * FROM `user` WHERE `nickname` = '%s' LIMIT 1",
375 $message = t('No user record found for ') . '\'' . $node . '\'';
376 xml_status(3,$message); // failure
380 $my_prvkey = $r[0]['prvkey'];
381 $local_uid = $r[0]['uid'];
384 if(! strstr($my_prvkey,'BEGIN RSA PRIVATE KEY')) {
385 $message = t('Our site encryption key is apparently messed up.');
386 xml_status(3,$message);
391 $decrypted_source_url = "";
392 openssl_private_decrypt($source_url,$decrypted_source_url,$my_prvkey);
395 if(! strlen($decrypted_source_url)) {
396 $message = t('Empty site URL was provided or URL could not be decrypted by us.');
397 xml_status(3,$message);
401 $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
402 dbesc($decrypted_source_url),
407 // this is either a bogus confirmation (?) or we deleted the original introduction.
408 $message = t('Contact record was not found for you on our site.');
409 xml_status(3,$message);
410 return; // NOTREACHED
413 $relation = $ret[0]['rel'];
415 // Decrypt all this stuff we just received
417 $foreign_pubkey = $ret[0]['site-pubkey'];
418 $dfrn_record = $ret[0]['id'];
420 $decrypted_dfrn_id = "";
421 openssl_public_decrypt($dfrn_id,$decrypted_dfrn_id,$foreign_pubkey);
423 if(strlen($aes_key)) {
424 $decrypted_aes_key = "";
425 openssl_private_decrypt($aes_key,$decrypted_aes_key,$my_prvkey);
426 $dfrn_pubkey = openssl_decrypt($public_key,'AES-256-CBC',$decrypted_aes_key);
429 $dfrn_pubkey = $public_key;
432 $r = q("SELECT * FROM `contact` WHERE `dfrn-id` = '%s' LIMIT 1",
433 dbesc($decrypted_dfrn_id)
436 $message = t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
437 xml_status(1,$message); // Birthday paradox - duplicate dfrn-id
441 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d LIMIT 1",
442 dbesc($decrypted_dfrn_id),
447 $message = t('Unable to set your contact credentials on our system.');
448 xml_status(3,$message);
451 // We're good but now we have to scrape the profile photo and send notifications.
455 $r = q("SELECT `photo` FROM `contact` WHERE `id` = %d LIMIT 1",
456 intval($dfrn_record));
459 $photo = $r[0]['photo'];
461 $photo = $a->get_baseurl() . '/images/default-profile.jpg';
463 require_once("Photo.php");
465 $photos = import_profile_photo($photo,$local_uid,$dfrn_record);
467 logger('dfrn_confirm: request - photos imported');
469 $new_relation = REL_FAN;
470 if(($relation == REL_VIP) || ($duplex))
471 $new_relation = REL_BUD;
473 if(($relation == REL_VIP) && ($duplex))
476 $r = q("UPDATE `contact` SET
483 `avatar-date` = '%s',
487 `network` = 'dfrn' WHERE `id` = %d LIMIT 1
492 intval($new_relation),
493 dbesc(datetime_convert()),
494 dbesc(datetime_convert()),
495 dbesc(datetime_convert()),
499 if($r === false) { // indicates schema is messed up or total db failure
500 $message = t('Unable to update your contact profile details on our system');
501 xml_status(3,$message);
504 // Otherwise everything seems to have worked and we are almost done. Yay!
505 // Send an email notification
507 $r = q("SELECT * FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
508 WHERE `contact`.`id` = %d LIMIT 1",
511 if((count($r)) && ($r[0]['notify-flags'] & NOTIFY_CONFIRM)) {
513 $tpl = (($new_relation == REL_BUD)
514 ? load_view_file('view/friend_complete_eml.tpl')
515 : load_view_file('view/intro_complete_eml.tpl'));
517 $email_tpl = replace_macros($tpl, array(
518 '$sitename' => $a->config['sitename'],
519 '$siteurl' => $a->get_baseurl(),
520 '$username' => $r[0]['username'],
521 '$email' => $r[0]['email'],
522 '$fn' => $r[0]['name'],
523 '$dfrn_url' => $r[0]['url'],
527 $res = mail($r[0]['email'], t("Connection accepted at ") . $a->config['sitename'],
528 $email_tpl, 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] );
530 // pointless throwing an error here and confusing the person at the other end of the wire.
533 xml_status(0); // Success
534 return; // NOTREACHED
536 ////////////////////// End of this scenario ///////////////////////////////////////////////
539 // somebody arrived here by mistake or they are fishing. Send them to the homepage.
541 goaway($a->get_baseurl());