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'];
52 logger('dfrn_confirm: Confirm in handsfree mode');
55 $dfrn_id = ((x($_POST,'dfrn_id')) ? notags(trim($_POST['dfrn_id'])) : "");
56 $intro_id = intval($_POST['intro_id']);
57 $duplex = intval($_POST['duplex']);
58 $cid = intval($_POST['contact_id']);
61 logger('dfrn_confirm: Confirming request for dfrn_id (issued) ' . $dfrn_id);
64 // The other person will have been issued an ID when they first requested friendship.
65 // Locate their record. At this time, their record will have both pending and blocked set to 1.
66 // There won't be any dfrn_id if this is a network follower, so use the contact_id instead.
68 $r = q("SELECT * FROM `contact` WHERE ( ( `issued-id` != '' AND `issued-id` = '%s' ) OR ( `id` = %d AND `id` != 0 ) ) AND `uid` = %d LIMIT 1",
75 notice( t('Contact not found.') . EOL );
81 $contact_id = $contact['id'];
82 $relation = $contact['rel'];
83 $site_pubkey = $contact['site-pubkey'];
84 $dfrn_confirm = $contact['confirm'];
85 $aes_allow = $contact['aes_allow'];
87 $network = ((strlen($contact['issued-id'])) ? 'dfrn' : 'stat');
89 if($network === 'dfrn') {
91 // Generate a key pair for all further communications with this person.
92 // We have a keypair for every contact, and a site key for unknown people.
93 // This provides a means to carry on relationships with other people if
94 // any single key is compromised. It is a robust key. We're much more
95 // worried about key leakage than anybody cracking it.
97 $res = openssl_pkey_new(array(
98 'digest_alg' => 'whirlpool',
99 'private_key_bits' => 4096,
100 'encrypt_key' => false )
106 openssl_pkey_export($res, $private_key);
108 $pubkey = openssl_pkey_get_details($res);
109 $public_key = $pubkey["key"];
111 // Save the private key. Send them the public key.
113 $r = q("UPDATE `contact` SET `prvkey` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
121 // Per the protocol document, we will verify both ends by encrypting the dfrn_id with our
122 // site private key (person on the other end can decrypt it with our site public key).
123 // Then encrypt our profile URL with the other person's site public key. They can decrypt
124 // it with their site private key. If the decryption on the other end fails for either
125 // item, it indicates tampering or key failure on at least one site and we will not be
126 // able to provide a secure communication pathway.
128 // If other site is willing to accept full encryption, (aes_allow is 1 AND we have php5.3
129 // or later) then we encrypt the personal public key we send them using AES-256-CBC and a
130 // random key which is encrypted with their site public key.
132 $src_aes_key = random_string();
135 openssl_private_encrypt($dfrn_id,$result,$user[0]['prvkey']);
137 $params['dfrn_id'] = bin2hex($result);
138 $params['public_key'] = $public_key;
141 $my_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
143 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
144 $params['source_url'] = bin2hex($params['source_url']);
146 if($aes_allow && function_exists('openssl_encrypt')) {
147 openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
148 $params['aes_key'] = bin2hex($params['aes_key']);
149 $params['public_key'] = bin2hex(openssl_encrypt($public_key,'AES-256-CBC',$src_aes_key));
152 $params['dfrn_version'] = DFRN_PROTOCOL_VERSION ;
154 $params['duplex'] = 1;
156 logger('dfrn_confirm: Confirm: posted data: ' . print_r($params,true), LOGGER_DATA);
158 // POST all this stuff to the other site.
160 $res = post_url($dfrn_confirm,$params);
162 logger('dfrn_confirm: Confirm: received data: ' . $res, LOGGER_DATA);
164 // Now figure out what they responded. Try to be robust if the remote site is
165 // having difficulty and throwing up errors of some kind.
167 $leading_junk = substr($res,0,strpos($res,'<?xml'));
169 $res = substr($res,strpos($res,'<?xml'));
172 // No XML at all, this exchange is messed up really bad.
173 // We shouldn't proceed, because the xml parser might choke,
174 // and $status is going to be zero, which indicates success.
175 // We can hardly call this a success.
177 notice( t('Response from remote site was not understood.') . EOL);
181 if(strlen($leading_junk) && get_config('system','debugging')) {
183 // This might be more common. Mixed error text and some XML.
184 // If we're configured for debugging, show the text. Proceed in either case.
186 notice( t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL );
189 $xml = simplexml_load_string($res);
190 $status = (int) $xml->status;
191 $message = unxmlify($xml->message); // human readable text of what may have gone wrong.
194 notice( t("Confirmation completed successfully.") . EOL);
196 notice( t('Remote site reported: ') . $message . EOL);
199 // birthday paradox - generate new dfrn-id and fall through.
200 $new_dfrn_id = random_string();
201 $r = q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
208 notice( t("Temporary failure. Please wait and try again.") . EOL);
210 notice( t('Remote site reported: ') . $message . EOL);
215 notice( t("Introduction failed or was revoked.") . EOL);
217 notice( t('Remote site reported: ') . $message . EOL);
221 if(($status == 0) && ($intro_id)) {
223 // Success. Delete the notification.
225 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d LIMIT 1",
236 // We have now established a relationship with the other site.
237 // Let's make our own personal copy of their profile photo so we don't have
238 // to always load it from their site.
240 require_once("Photo.php");
242 $photos = import_profile_photo($contact['photo'],$uid,$contact_id);
244 logger('dfrn_confirm: confirm - imported photos');
246 if($network === 'dfrn') {
248 $new_relation = REL_VIP;
249 if(($relation == REL_FAN) || ($duplex))
250 $new_relation = REL_BUD;
252 if(($relation == REL_FAN) && ($duplex))
255 $r = q("UPDATE `contact` SET `photo` = '%s',
261 `avatar-date` = '%s',
265 `network` = 'dfrn' WHERE `id` = %d LIMIT 1
270 intval($new_relation),
271 dbesc(datetime_convert()),
272 dbesc(datetime_convert()),
273 dbesc(datetime_convert()),
283 // $network !== 'dfrn'
285 $arr = lrdd($contact['url']);
287 foreach($arr as $link) {
288 if($link['@attributes']['rel'] === 'salmon')
289 $notify = $link['@attributes']['href'];
290 if($link['@attributes']['rel'] === NAMESPACE_FEED)
291 $poll = $link['@attributes']['href'];
295 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d LIMIT 1",
301 $r = q("UPDATE `contact` SET `photo` = '%s',
306 `avatar-date` = '%s',
312 WHERE `id` = %d LIMIT 1
317 dbesc(datetime_convert()),
318 dbesc(datetime_convert()),
319 dbesc(datetime_convert()),
327 notice( t('Unable to set contact photo.') . EOL);
330 // Let's send our user to the contact editor in case they want to
331 // do anything special with this new friend.
333 if($handsfree === null)
334 goaway($a->get_baseurl() . '/contacts/' . intval($contact_id));
341 // End of first scenario. [Local confirmation of remote friend request].
345 // Begin scenario two. This is the remote response to the above scenario.
346 // This will take place on the site that originally initiated the friend request.
347 // In the section above where the confirming party makes a POST and
348 // retrieves xml status information, they are communicating with the following code.
350 if(x($_POST,'source_url')) {
352 // We are processing an external confirmation to an introduction created by our user.
354 $public_key = $_POST['public_key'];
355 $dfrn_id = hex2bin($_POST['dfrn_id']);
356 $source_url = hex2bin($_POST['source_url']);
357 $aes_key = $_POST['aes_key'];
358 $duplex = $_POST['duplex'];
359 $version_id = (float) $_POST['dfrn_version'];
361 logger('dfrn_confirm: requestee contacted: ' . $node);
363 logger('dfrn_confirm: request: POST=' . print_r($_POST,true), LOGGER_DATA);
365 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
368 $aes_key = hex2bin($aes_key);
369 $public_key = hex2bin($public_key);
372 // Find our user's account
374 $r = q("SELECT * FROM `user` WHERE `nickname` = '%s' LIMIT 1",
378 $message = t('No user record found for ') . '\'' . $node . '\'';
379 xml_status(3,$message); // failure
383 $my_prvkey = $r[0]['prvkey'];
384 $local_uid = $r[0]['uid'];
387 if(! strstr($my_prvkey,'BEGIN RSA PRIVATE KEY')) {
388 $message = t('Our site encryption key is apparently messed up.');
389 xml_status(3,$message);
394 $decrypted_source_url = "";
395 openssl_private_decrypt($source_url,$decrypted_source_url,$my_prvkey);
398 if(! strlen($decrypted_source_url)) {
399 $message = t('Empty site URL was provided or URL could not be decrypted by us.');
400 xml_status(3,$message);
404 $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
405 dbesc($decrypted_source_url),
410 // this is either a bogus confirmation (?) or we deleted the original introduction.
411 $message = t('Contact record was not found for you on our site.');
412 xml_status(3,$message);
413 return; // NOTREACHED
416 $relation = $ret[0]['rel'];
418 // Decrypt all this stuff we just received
420 $foreign_pubkey = $ret[0]['site-pubkey'];
421 $dfrn_record = $ret[0]['id'];
423 $decrypted_dfrn_id = "";
424 openssl_public_decrypt($dfrn_id,$decrypted_dfrn_id,$foreign_pubkey);
426 if(strlen($aes_key)) {
427 $decrypted_aes_key = "";
428 openssl_private_decrypt($aes_key,$decrypted_aes_key,$my_prvkey);
429 $dfrn_pubkey = openssl_decrypt($public_key,'AES-256-CBC',$decrypted_aes_key);
432 $dfrn_pubkey = $public_key;
435 $r = q("SELECT * FROM `contact` WHERE `dfrn-id` = '%s' LIMIT 1",
436 dbesc($decrypted_dfrn_id)
439 $message = t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
440 xml_status(1,$message); // Birthday paradox - duplicate dfrn-id
444 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d LIMIT 1",
445 dbesc($decrypted_dfrn_id),
450 $message = t('Unable to set your contact credentials on our system.');
451 xml_status(3,$message);
454 // We're good but now we have to scrape the profile photo and send notifications.
458 $r = q("SELECT `photo` FROM `contact` WHERE `id` = %d LIMIT 1",
459 intval($dfrn_record));
462 $photo = $r[0]['photo'];
464 $photo = $a->get_baseurl() . '/images/default-profile.jpg';
466 require_once("Photo.php");
468 $photos = import_profile_photo($photo,$local_uid,$dfrn_record);
470 logger('dfrn_confirm: request - photos imported');
472 $new_relation = REL_FAN;
473 if(($relation == REL_VIP) || ($duplex))
474 $new_relation = REL_BUD;
476 if(($relation == REL_VIP) && ($duplex))
479 $r = q("UPDATE `contact` SET
486 `avatar-date` = '%s',
490 `network` = 'dfrn' WHERE `id` = %d LIMIT 1
495 intval($new_relation),
496 dbesc(datetime_convert()),
497 dbesc(datetime_convert()),
498 dbesc(datetime_convert()),
502 if($r === false) { // indicates schema is messed up or total db failure
503 $message = t('Unable to update your contact profile details on our system');
504 xml_status(3,$message);
507 // Otherwise everything seems to have worked and we are almost done. Yay!
508 // Send an email notification
510 logger('dfrn_confirm: request: info updated');
512 $r = q("SELECT * FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
513 WHERE `contact`.`id` = %d LIMIT 1",
516 if((count($r)) && ($r[0]['notify-flags'] & NOTIFY_CONFIRM)) {
518 $tpl = (($new_relation == REL_BUD)
519 ? load_view_file('view/friend_complete_eml.tpl')
520 : load_view_file('view/intro_complete_eml.tpl'));
522 $email_tpl = replace_macros($tpl, array(
523 '$sitename' => $a->config['sitename'],
524 '$siteurl' => $a->get_baseurl(),
525 '$username' => $r[0]['username'],
526 '$email' => $r[0]['email'],
527 '$fn' => $r[0]['name'],
528 '$dfrn_url' => $r[0]['url'],
532 $res = mail($r[0]['email'], t("Connection accepted at ") . $a->config['sitename'],
533 $email_tpl, 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] );
535 // pointless throwing an error here and confusing the person at the other end of the wire.
538 xml_status(0); // Success
539 return; // NOTREACHED
541 ////////////////////// End of this scenario ///////////////////////////////////////////////
544 // somebody arrived here by mistake or they are fishing. Send them to the homepage.
546 goaway($a->get_baseurl());