5 * Purpose: Friendship acceptance for DFRN contacts
7 * There are two possible entry points and three scenarios.
9 * 1. A form was submitted by our user approving a friendship that originated elsewhere.
10 * This may also be called from dfrn_request to automatically approve a friendship.
12 * 2. We may be the target or other side of the conversation to scenario 1, and will
13 * interact with that process on our own user's behalf.
17 function dfrn_confirm_post(&$a,$handsfree = null) {
19 if(is_array($handsfree)) {
22 * We were called directly from dfrn_request due to automatic friend acceptance.
23 * Any $_POST parameters we may require are supplied in the $handsfree array.
27 $node = $handsfree['node'];
28 $a->interactive = false; // notice() becomes a no-op since nobody is there to see it
38 * Main entry point. Scenario 1. Our user received a friend request notification (perhaps
39 * from another site) and clicked 'Approve'.
40 * $POST['source_url'] is not set. If it is, it indicates Scenario 2.
42 * We may also have been called directly from dfrn_request ($handsfree != null) due to
43 * this being a page type which supports automatic friend acceptance. That is also Scenario 1
44 * since we are operating on behalf of our registered user to approve a friendship.
48 if(! x($_POST,'source_url')) {
50 $uid = ((is_array($handsfree)) ? $handsfree['uid'] : local_user());
53 notice( t('Permission denied.') . EOL );
57 $user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
62 notice( t('Profile not found.') . EOL );
67 // These data elements may come from either the friend request notification form or $handsfree array.
69 if(is_array($handsfree)) {
70 logger('dfrn_confirm: Confirm in handsfree mode');
71 $dfrn_id = $handsfree['dfrn_id'];
72 $intro_id = $handsfree['intro_id'];
73 $duplex = $handsfree['duplex'];
76 $dfrn_id = ((x($_POST,'dfrn_id')) ? notags(trim($_POST['dfrn_id'])) : "");
77 $intro_id = ((x($_POST,'intro_id')) ? intval($_POST['intro_id']) : 0 );
78 $duplex = ((x($_POST,'duplex')) ? intval($_POST['duplex']) : 0 );
79 $cid = ((x($_POST,'contact_id')) ? intval($_POST['contact_id']) : 0 );
84 * Ensure that dfrn_id has precedence when we go to find the contact record.
85 * We only want to search based on contact id if there is no dfrn_id,
86 * e.g. for OStatus network followers.
93 logger('dfrn_confirm: Confirming request for dfrn_id (issued) ' . $dfrn_id);
95 logger('dfrn_confirm: Confirming follower with contact_id: ' . $cid);
100 * The other person will have been issued an ID when they first requested friendship.
101 * Locate their record. At this time, their record will have both pending and blocked set to 1.
102 * There won't be any dfrn_id if this is a network follower, so use the contact_id instead.
106 $r = q("SELECT * FROM `contact` WHERE ( ( `issued-id` != '' AND `issued-id` = '%s' ) OR ( `id` = %d AND `id` != 0 ) ) AND `uid` = %d LIMIT 1",
113 logger('dfrn_confirm: Contact not found in DB.');
114 notice( t('Contact not found.') . EOL );
120 $contact_id = $contact['id'];
121 $relation = $contact['rel'];
122 $site_pubkey = $contact['site-pubkey'];
123 $dfrn_confirm = $contact['confirm'];
124 $aes_allow = $contact['aes_allow'];
126 $network = ((strlen($contact['issued-id'])) ? 'dfrn' : 'stat');
128 if($network === 'dfrn') {
132 * Generate a key pair for all further communications with this person.
133 * We have a keypair for every contact, and a site key for unknown people.
134 * This provides a means to carry on relationships with other people if
135 * any single key is compromised. It is a robust key. We're much more
136 * worried about key leakage than anybody cracking it.
140 $res = openssl_pkey_new(array(
141 'digest_alg' => 'sha1',
142 'private_key_bits' => 4096,
143 'encrypt_key' => false )
148 openssl_pkey_export($res, $private_key);
150 $pubkey = openssl_pkey_get_details($res);
151 $public_key = $pubkey["key"];
153 // Save the private key. Send them the public key.
155 $r = q("UPDATE `contact` SET `prvkey` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
165 * Per the DFRN protocol, we will verify both ends by encrypting the dfrn_id with our
166 * site private key (person on the other end can decrypt it with our site public key).
167 * Then encrypt our profile URL with the other person's site public key. They can decrypt
168 * it with their site private key. If the decryption on the other end fails for either
169 * item, it indicates tampering or key failure on at least one site and we will not be
170 * able to provide a secure communication pathway.
172 * If other site is willing to accept full encryption, (aes_allow is 1 AND we have php5.3
173 * or later) then we encrypt the personal public key we send them using AES-256-CBC and a
174 * random key which is encrypted with their site public key.
178 $src_aes_key = random_string();
181 openssl_private_encrypt($dfrn_id,$result,$user[0]['prvkey']);
183 $params['dfrn_id'] = bin2hex($result);
184 $params['public_key'] = $public_key;
187 $my_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
189 openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
190 $params['source_url'] = bin2hex($params['source_url']);
192 if($aes_allow && function_exists('openssl_encrypt')) {
193 openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
194 $params['aes_key'] = bin2hex($params['aes_key']);
195 $params['public_key'] = bin2hex(openssl_encrypt($public_key,'AES-256-CBC',$src_aes_key));
198 $params['dfrn_version'] = DFRN_PROTOCOL_VERSION ;
200 $params['duplex'] = 1;
202 logger('dfrn_confirm: Confirm: posting data to ' . $dfrn_confirm . ': ' . print_r($params,true), LOGGER_DATA);
206 * POST all this stuff to the other site.
207 * Temporarily raise the network timeout to 120 seconds because the default 60
208 * doesn't always give the other side quite enough time to decrypt everything.
212 $a->config['system']['curl_timeout'] = 120;
214 $res = post_url($dfrn_confirm,$params);
216 logger('dfrn_confirm: Confirm: received data: ' . $res, LOGGER_DATA);
218 // Now figure out what they responded. Try to be robust if the remote site is
219 // having difficulty and throwing up errors of some kind.
221 $leading_junk = substr($res,0,strpos($res,'<?xml'));
223 $res = substr($res,strpos($res,'<?xml'));
226 // No XML at all, this exchange is messed up really bad.
227 // We shouldn't proceed, because the xml parser might choke,
228 // and $status is going to be zero, which indicates success.
229 // We can hardly call this a success.
231 notice( t('Response from remote site was not understood.') . EOL);
235 if(strlen($leading_junk) && get_config('system','debugging')) {
237 // This might be more common. Mixed error text and some XML.
238 // If we're configured for debugging, show the text. Proceed in either case.
240 notice( t('Unexpected response from remote site: ') . EOL . $leading_junk . EOL );
243 $xml = simplexml_load_string($res);
244 $status = (int) $xml->status;
245 $message = unxmlify($xml->message); // human readable text of what may have gone wrong.
248 notice( t("Confirmation completed successfully.") . EOL);
250 notice( t('Remote site reported: ') . $message . EOL);
253 // birthday paradox - generate new dfrn-id and fall through.
254 $new_dfrn_id = random_string();
255 $r = q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
262 notice( t("Temporary failure. Please wait and try again.") . EOL);
264 notice( t('Remote site reported: ') . $message . EOL);
269 notice( t("Introduction failed or was revoked.") . EOL);
271 notice( t('Remote site reported: ') . $message . EOL);
275 if(($status == 0) && ($intro_id)) {
277 // Success. Delete the notification.
279 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d LIMIT 1",
293 * We have now established a relationship with the other site.
294 * Let's make our own personal copy of their profile photo so we don't have
295 * to always load it from their site.
297 * We will also update the contact record with the nature and scope of the relationship.
301 require_once("Photo.php");
303 $photos = import_profile_photo($contact['photo'],$uid,$contact_id);
305 logger('dfrn_confirm: confirm - imported photos');
307 if($network === 'dfrn') {
309 $new_relation = REL_VIP;
310 if(($relation == REL_FAN) || ($duplex))
311 $new_relation = REL_BUD;
313 if(($relation == REL_FAN) && ($duplex))
316 $r = q("UPDATE `contact` SET `photo` = '%s',
322 `avatar-date` = '%s',
326 `network` = 'dfrn' WHERE `id` = %d LIMIT 1
331 intval($new_relation),
332 dbesc(datetime_convert()),
333 dbesc(datetime_convert()),
334 dbesc(datetime_convert()),
340 // $network !== 'dfrn'
345 $arr = lrdd($contact['url']);
347 foreach($arr as $link) {
348 if($link['@attributes']['rel'] === 'salmon')
349 $notify = $link['@attributes']['href'];
350 if($link['@attributes']['rel'] === NAMESPACE_FEED)
351 $poll = $link['@attributes']['href'];
355 $r = q("DELETE FROM `intro` WHERE `id` = %d AND `uid` = %d LIMIT 1",
361 $r = q("UPDATE `contact` SET `photo` = '%s',
366 `avatar-date` = '%s',
372 WHERE `id` = %d LIMIT 1
377 dbesc(datetime_convert()),
378 dbesc(datetime_convert()),
379 dbesc(datetime_convert()),
387 notice( t('Unable to set contact photo.') . EOL);
390 // Let's send our user to the contact editor in case they want to
391 // do anything special with this new friend.
393 if($handsfree === null)
394 goaway($a->get_baseurl() . '/contacts/' . intval($contact_id));
403 * End of Scenario 1. [Local confirmation of remote friend request].
405 * Begin Scenario 2. This is the remote response to the above scenario.
406 * This will take place on the site that originally initiated the friend request.
407 * In the section above where the confirming party makes a POST and
408 * retrieves xml status information, they are communicating with the following code.
412 if(x($_POST,'source_url')) {
414 // We are processing an external confirmation to an introduction created by our user.
416 $public_key = ((x($_POST,'public_key')) ? $_POST['public_key'] : '');
417 $dfrn_id = ((x($_POST,'dfrn_id')) ? hex2bin($_POST['dfrn_id']) : '');
418 $source_url = ((x($_POST,'source_url')) ? hex2bin($_POST['source_url']) : '');
419 $aes_key = ((x($_POST,'aes_key')) ? $_POST['aes_key'] : '');
420 $duplex = ((x($_POST,'duplex')) ? intval($_POST['duplex']) : 0 );
421 $version_id = ((x($_POST,'dfrn_version')) ? (float) $_POST['dfrn_version'] : 2.0);
423 logger('dfrn_confirm: requestee contacted: ' . $node);
425 logger('dfrn_confirm: request: POST=' . print_r($_POST,true), LOGGER_DATA);
427 // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
430 $aes_key = hex2bin($aes_key);
431 $public_key = hex2bin($public_key);
434 // Find our user's account
436 $r = q("SELECT * FROM `user` WHERE `nickname` = '%s' LIMIT 1",
440 $message = t('No user record found for ') . '\'' . $node . '\'';
441 xml_status(3,$message); // failure
445 $my_prvkey = $r[0]['prvkey'];
446 $local_uid = $r[0]['uid'];
449 if(! strstr($my_prvkey,'BEGIN RSA PRIVATE KEY')) {
450 $message = t('Our site encryption key is apparently messed up.');
451 xml_status(3,$message);
456 $decrypted_source_url = "";
457 openssl_private_decrypt($source_url,$decrypted_source_url,$my_prvkey);
460 if(! strlen($decrypted_source_url)) {
461 $message = t('Empty site URL was provided or URL could not be decrypted by us.');
462 xml_status(3,$message);
466 $ret = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
467 dbesc($decrypted_source_url),
472 // this is either a bogus confirmation (?) or we deleted the original introduction.
473 $message = t('Contact record was not found for you on our site.');
474 xml_status(3,$message);
475 return; // NOTREACHED
478 $relation = $ret[0]['rel'];
480 // Decrypt all this stuff we just received
482 $foreign_pubkey = $ret[0]['site-pubkey'];
483 $dfrn_record = $ret[0]['id'];
485 $decrypted_dfrn_id = "";
486 openssl_public_decrypt($dfrn_id,$decrypted_dfrn_id,$foreign_pubkey);
488 if(strlen($aes_key)) {
489 $decrypted_aes_key = "";
490 openssl_private_decrypt($aes_key,$decrypted_aes_key,$my_prvkey);
491 $dfrn_pubkey = openssl_decrypt($public_key,'AES-256-CBC',$decrypted_aes_key);
494 $dfrn_pubkey = $public_key;
497 $r = q("SELECT * FROM `contact` WHERE `dfrn-id` = '%s' LIMIT 1",
498 dbesc($decrypted_dfrn_id)
501 $message = t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
502 xml_status(1,$message); // Birthday paradox - duplicate dfrn-id
506 $r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d LIMIT 1",
507 dbesc($decrypted_dfrn_id),
512 $message = t('Unable to set your contact credentials on our system.');
513 xml_status(3,$message);
516 // We're good but now we have to scrape the profile photo and send notifications.
520 $r = q("SELECT `photo` FROM `contact` WHERE `id` = %d LIMIT 1",
521 intval($dfrn_record));
524 $photo = $r[0]['photo'];
526 $photo = $a->get_baseurl() . '/images/default-profile.jpg';
528 require_once("Photo.php");
530 $photos = import_profile_photo($photo,$local_uid,$dfrn_record);
532 logger('dfrn_confirm: request - photos imported');
534 $new_relation = REL_FAN;
535 if(($relation == REL_VIP) || ($duplex))
536 $new_relation = REL_BUD;
538 if(($relation == REL_VIP) && ($duplex))
541 $r = q("UPDATE `contact` SET
548 `avatar-date` = '%s',
552 `network` = 'dfrn' WHERE `id` = %d LIMIT 1
557 intval($new_relation),
558 dbesc(datetime_convert()),
559 dbesc(datetime_convert()),
560 dbesc(datetime_convert()),
564 if($r === false) { // indicates schema is messed up or total db failure
565 $message = t('Unable to update your contact profile details on our system');
566 xml_status(3,$message);
569 // Otherwise everything seems to have worked and we are almost done. Yay!
570 // Send an email notification
572 logger('dfrn_confirm: request: info updated');
574 $r = q("SELECT * FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
575 WHERE `contact`.`id` = %d LIMIT 1",
578 if((count($r)) && ($r[0]['notify-flags'] & NOTIFY_CONFIRM)) {
580 $tpl = (($new_relation == REL_BUD)
581 ? load_view_file('view/friend_complete_eml.tpl')
582 : load_view_file('view/intro_complete_eml.tpl'));
584 $email_tpl = replace_macros($tpl, array(
585 '$sitename' => $a->config['sitename'],
586 '$siteurl' => $a->get_baseurl(),
587 '$username' => $r[0]['username'],
588 '$email' => $r[0]['email'],
589 '$fn' => $r[0]['name'],
590 '$dfrn_url' => $r[0]['url'],
594 $res = mail($r[0]['email'], t("Connection accepted at ") . $a->config['sitename'],
595 $email_tpl, 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] );
597 // pointless throwing an error here and confusing the person at the other end of the wire.
600 xml_status(0); // Success
601 return; // NOTREACHED
603 ////////////////////// End of this scenario ///////////////////////////////////////////////
606 // somebody arrived here by mistake or they are fishing. Send them to the homepage.
608 goaway($a->get_baseurl());